Programs & Examples On #Newenvironment

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

Html.ActionLink as a button or an image, not a link

Even later response, but I just ran into a similar issue and ended up writing my own Image link HtmlHelper extension.

You can find an implementation of it on my blog in the link above.

Just added in case someone is hunting down an implementation.

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

Why do I get "'property cannot be assigned" when sending an SMTP email?

First go to https://myaccount.google.com/lesssecureapps and make Allow less secure apps true.

Then use the below code. This below code will work only if your from email address is from gmail.

static void SendEmail()
    {
        string mailBodyhtml =
            "<p>some text here</p>";
        var msg = new MailMessage("[email protected]", "[email protected]", "Hello", mailBodyhtml);
        msg.To.Add("[email protected]");
        msg.IsBodyHtml = true;
        var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "[email protected]" then host should be "smtp.hotmail.com"**
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new NetworkCredential("[email protected]", "password");
        smtpClient.EnableSsl = true;
        smtpClient.Send(msg);
        Console.WriteLine("Email Sent Successfully");
    }

Calculate days between two Dates in Java 8

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document.

Version of Apache installed on a Debian machine

For me apachectl -V did not work, but apachectl fullstatus gave me my version.

What steps are needed to stream RTSP from FFmpeg?

Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:

sudo apt install vlc ffmpeg

In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.

I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.

You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:

ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'

For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:

ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554

SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

convert(nvarchar(50), RequestID)

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

Storing money in a decimal column - what precision and scale?

4 decimal places would give you the accuracy to store the world's smallest currency sub-units. You can take it down further if you need micropayment (nanopayment?!) accuracy.

I too prefer DECIMAL to DBMS-specific money types, you're safer keeping that kind of logic in the application IMO. Another approach along the same lines is simply to use a [long] integer, with formatting into ¤unit.subunit for human readability (¤ = currency symbol) done at the application level.

Running Google Maps v2 on the Android emulator

I recommend using the emulator by Genymotion instead of Google's emulators. It launches way faster and responds almost in real-time. It also supports Google Play Services and therefore Google Maps.

Google Maps on Genymotion

Give it a try! Here is a blog post which helps you setting up the emulator.

jQuery, get html of a whole element

You can easily get child itself and all of its decedents (children) with Jquery's Clone() method, just

var child = $('#div div:nth-child(1)').clone();  

var child2 = $('#div div:nth-child(2)').clone();

You will get this for first query as asked in question

<div id="div1">
     <p>Some Content</p>
</div>

How much RAM is SQL Server actually using?

The simplest way to see ram usage if you have RDP access / console access would be just launch task manager - click processes - show processes from all users, sort by RAM - This will give you SQL's usage.

As was mentioned above, to decrease the size (which will take effect immediately, no restart required) launch sql management studio, click the server, properties - memory and decrease the max. There's no exactly perfect number, but make sure the server has ram free for other tasks.

The answers about perfmon are correct and should be used, but they aren't as obvious a method as task manager IMHO.

VBA Public Array : how to?

You are using the wrong type. The Array(...) function returns a Variant, not a String.

Thus, in the Declaration section of your module (it does not need to be a different module!), you define

Public colHeader As Variant

and somewhere at the beginning of your program code (for example, in the Workbook_Open event) you initialize it with

colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Another (simple) alternative would be to create a function that returns the array, e.g. something like

Public Function GetHeaders() As Variant
    GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function

This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.

Remove files from Git commit

Just wanted to complement the top answer as I had to run an extra command:

git reset --soft HEAD^
git checkout origin/master <filepath>

Cheers!

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

Change bootstrap navbar collapse breakpoint without using LESS

In addition to @Skely answer, to make dropdown menus inside the navbar work, also add their classes to be overriden. Final code bellow:

    @media (min-width: 768px) and (max-width: 991px) {
        .navbar-nav .open .dropdown-menu {
            position: static;
            float: none;
            width: auto;
            margin-top: 0;
            background-color: transparent;
            border: 0;
            -webkit-box-shadow: none;
            box-shadow: none;
        }
        .navbar-nav .open .dropdown-menu > li > a {
            line-height: 20px;
        }
        .navbar-nav .open .dropdown-menu > li > a,
        .navbar-nav .open .dropdown-menu .dropdown-header {
            padding: 5px 15px 5px 25px;
        }
        .dropdown-menu > li > a {
            display: block;
            padding: 3px 20px;
            clear: both;
            font-weight: normal;
            line-height: 1.42857143;
            color: #333;
            white-space: nowrap;
        }
        .navbar-header {
            float: none;
        }
        .navbar-toggle {
            display: block;
        }
        .navbar-collapse {
            border-top: 1px solid transparent;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
        }
        .navbar-collapse.collapse {
            display: none!important;
        }
        .navbar-nav {
            float: none!important;
            /*margin: 7.5px -15px;*/
            margin: 7.5px 50px 7.5px -15px
        }
        .navbar-nav>li {
            float: none;
        }
        .navbar-nav>li>a {
            padding-top: 10px;
            padding-bottom: 10px;
        }
        .navbar-text {
            float: none;
            margin: 15px 0;
        }
        /* since 3.1.0 */
        .navbar-collapse.collapse.in { 
            display: block!important;
        }
        .collapsing {
            overflow: hidden!important;
        }
    }

demo code

Dynamic function name in javascript?

This utility function merge multiple functions into one (using a custom name), only requirement is that provided functions are properly "new lined" at start and end of its scoop.

const createFn = function(name, functions, strict=false) {

    var cr = `\n`, a = [ 'return function ' + name + '(p) {' ];

    for(var i=0, j=functions.length; i<j; i++) {
        var str = functions[i].toString();
        var s = str.indexOf(cr) + 1;
        a.push(str.substr(s, str.lastIndexOf(cr) - s));
    }
    if(strict == true) {
        a.unshift('\"use strict\";' + cr)
    }
    return new Function(a.join(cr) + cr + '}')();
}

// test
var a = function(p) {
    console.log("this is from a");
}
var b = function(p) {
    console.log("this is from b");
}
var c = function(p) {
    console.log("p == " + p);
}

var abc = createFn('aGreatName', [a,b,c])

console.log(abc) // output: function aGreatName()

abc(123)

// output
this is from a
this is from b
p == 123

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

How to find the size of a table in SQL?

And in PostgreSQL:

SELECT pg_size_pretty(pg_relation_size('tablename'));

How to get image size (height & width) using JavaScript?

Using JQuery you do this:

var imgWidth = $("#imgIDWhatever").width();

How do I activate C++ 11 in CMake?

What works for me is to set the following line in your CMakeLists.txt:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Setting this command activates the C++11 features for the compiler and after executing the cmake .. command, you should be able to use range based for loops in your code and compile it without any errors.

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

The Apache module PHP version might for some odd reason not be picking up the php.ini file as the CLI version I'd suggest having a good look at:

  • Any differences in the .ini files that differ between php -i and phpinfo() via a web page*
  • If there are no differences then to look at the permissions of mysql.so and the .ini files but I think that Apache parses these as the root user

To be really clear here, don't go searching for php.ini files on the file system, have a look at what PHP says that it's looking at

Redirect stderr and stdout in Bash

do_something 2>&1 | tee -a some_file

This is going to redirect stderr to stdout and stdout to some_file and print it to stdout.

If using maven, usually you put log4j.properties under java or resources?

Add the below code from the resources tags in your pom.xml inside build tags. so it means resources tags must be inside of build tags in your pom.xml

<build>
    <resources>
        <resource>
            <directory>src/main/java/resources</directory>
                <filtering>true</filtering> 
         </resource>
     </resources>
<build/>

Python: avoiding pylint warnings about too many arguments

Do you want a better way to pass the arguments or just a way to stop pylint from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting pylint-controlling comments in your code along the lines of:

#pylint: disable=R0913

or, better:

#pylint: disable=too-many-arguments

remembering to turn them back on as soon as practicable.

In my opinion, there's nothing inherently wrong with passing a lot of arguments and solutions advocating wrapping them all up in some container argument don't really solve any problems, other than stopping pylint from nagging you :-).

If you need to pass twenty arguments, then pass them. It may be that this is required because your function is doing too much and a re-factoring could assist there, and that's something you should look at. But it's not a decision we can really make unless we see what the 'real' code is.

jQuery preventDefault() not triggered

i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:

your jQuery script needs to be after the elements you are referring to !

so your script needs to be after the html-code you want to access!

seems like jQuery can't access it otherwise.

Sharing a variable between multiple different threads

In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:

public class Test {
  class Control {
    public volatile boolean flag = false;
  }
  final Control control = new Control();

  class T1 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  class T2 implements Runnable {
    @Override
    public void run() {
      while ( !control.flag ) {

      }
    }
  }

  private void test() {
    T1 main = new T1();
    T2 help = new T2();

    new Thread(main).start();
    new Thread(help).start();
  }

  public static void main(String[] args) throws InterruptedException {
    try {
      Test test = new Test();
      test.test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

How to use multiple @RequestMapping annotations in spring?

The following is acceptable as well:

@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath", 
                     "/fixedPath/{some-name}/{some-id}/fixed" }, 
            produces = "application/json")

Same can be applied to @RequestMapping as well

Numpy: Divide each row by a vector element

As has been mentioned, slicing with None or with np.newaxes is a great way to do this. Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function. There really are a lot of ways to do this.

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

how can I debug a jar at runtime?

You can activate JVM's debugging capability when starting up the java command with a special option:

java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar

Starting up jar.jar like that on the command line will:

  • put this JVM instance in the role of a server (server=y) listening on port 8000 (address=8000)
  • write Listening for transport dt_socket at address: 8000 to stdout and
  • then pause the application (suspend=y) until some debugger connects. The debugger acts as the client in this scenario.

Common options for selecting a debugger are:

  • Eclipse Debugger: Under Run -> Debug Configurations... -> select Remote Java Application -> click the New launch configuration button. Provide an arbitrary Name for this debug configuration, Connection Type: Standard (Socket Attach) and as Connection Properties the entries Host: localhost, Port: 8000. Apply the Changes and click Debug. At the moment the Eclipse Debugger has successfully connected to the JVM, jar.jar should begin executing.
  • jdb command-line tool: Start it up with jdb -connect com.sun.jdi.SocketAttach:port=8000

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

You should use this example with AUTHID CURRENT_USER :

CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
   AUTHID CURRENT_USER
IS
   SEQ_NAME       VARCHAR2 (100);
   FINAL_QUERY    VARCHAR2 (100);
   COUNT_NUMBER   NUMBER := 0;
   cur_id         NUMBER;
BEGIN
   SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;

   SELECT COUNT (*)
     INTO COUNT_NUMBER
     FROM USER_SEQUENCES
    WHERE SEQUENCE_NAME = SEQ_NAME;

   DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);

   IF COUNT_NUMBER = 0
   THEN
      --DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
      -- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
      -- ELSE
      SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
        INTO FINAL_QUERY
        FROM DUAL;

      DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
      cur_id := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
      DBMS_SQL.CLOSE_CURSOR (cur_id);
   -- EXECUTE IMMEDIATE FINAL_QUERY;

   END IF;

   COMMIT;
END;
/

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

But if i take the piece of sql and run it from sql management studio, it will run without issue.

If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.

The real crux of the issue is:

I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")

Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

   a  b
 1  2  4
 2  3  3
 3  4  2
 4  5  1

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

Angular 2 'component' is not a known element

I got the same issue, and it was happening because of different feature module included this component by mistake. When removed it from the other feature, it worked!

How to convert a multipart file to File?

You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

The source for the MultipartFile save to disk.

File file = new File(directory, filename);

// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);

// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

Creating a node class in Java

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

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

    public int getSize() {
        return size;
    }

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

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

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

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

    public class ItemInfoNode {

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

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

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

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

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

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

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

EDIT:

Declare ItemInfo as this:

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

    public ItemInfo(){
    }

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

    public String getName() {
        return name;
    }

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

    public String getRfdNumber() {
        return rfdNumber;
    }

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

    public double getPrice() {
        return price;
    }

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

    public String getOriginalPosition() {
        return originalPosition;
    }

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

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

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

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

Removing an item from a select box

Remove an option:

_x000D_
_x000D_
$("#selectBox option[value='option1']").remove();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Add an option:

_x000D_
_x000D_
$("#selectBox").append('<option value="option5">option5</option>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
  <option value="option1">option1</option>_x000D_
  <option value="option2">option2</option>_x000D_
  <option value="option3">option3</option>_x000D_
  <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

Merge, update, and pull Git branches without using checkouts

Enter git-forward-merge:

Without needing to checkout destination, git-forward-merge <source> <destination> merges source into destination branch.

https://github.com/schuyler1d/git-forward-merge

Only works for automatic merges, if there are conflicts you need to use the regular merge.

PHP MySQL Query Where x = $variable

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];

What is the correct way to create a single-instance WPF application?

MSDN actually has a sample application for both C# and VB to do exactly this: http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx

The most common and reliable technique for developing single-instance detection is to use the Microsoft .NET Framework remoting infrastructure (System.Remoting). The Microsoft .NET Framework (version 2.0) includes a type, WindowsFormsApplicationBase, which encapsulates the required remoting functionality. To incorporate this type into a WPF application, a type needs to derive from it, and be used as a shim between the application static entry point method, Main, and the WPF application's Application type. The shim detects when an application is first launched, and when subsequent launches are attempted, and yields control the WPF Application type to determine how to process the launches.

  • For C# people just take a deep breath and forget about the whole 'I don't wanna include VisualBasic DLL'. Because of this and what Scott Hanselman says and the fact that this pretty much is the cleanest solution to the problem and is designed by people who know a lot more about the framework than you do.
  • From a usability standpoint the fact is if your user is loading an application and it is already open and you're giving them an error message like 'Another instance of the app is running. Bye' then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.

The framework already has support for this - its just that some idiot named the DLL Microsoft.VisualBasic and it didn't get put into Microsoft.ApplicationUtils or something like that. Get over it - or open up Reflector.

Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to take a look at this too.

How to get a variable type in Typescript?

The other answers are right, but when you're dealing with interfaces you cannot use typeof or instanceof because interfaces don't get compiled to javascript.

Instead you can use a typecast + function check typeguard to check your variable:

interface Car {
    drive(): void;
    honkTheHorn(): void;
}

interface Bike {
    drive(): void;
    ringTheBell(): void;
}

function start(vehicle: Bike | Car ) {
    vehicle.drive();

    // typecast and check if the function exists
    if ((<Bike>vehicle).ringTheBell) {
        const bike = (<Bike>vehicle);
        bike.ringTheBell();
    } else {
        const car = (<Car>vehicle);
        car.honkTheHorn();
    }
}

And this is the compiled JavaScript in ES2017:

function start(vehicle) {
    vehicle.drive();
    if (vehicle.ringTheBell) {
        const bike = vehicle;
        bike.ringTheBell();
    }
    else {
        const car = vehicle;
        car.honkTheHorn();
    }
}

535-5.7.8 Username and Password not accepted

UPDATE:

Notice: This setting is not available for accounts with 2-Step Verification enabled, which mean you have to disable 2 factor authentication.

enter image description here

If you disable the 2-Step Verification:

enter image description here

Getting the minimum of two values in SQL

Use a temp table to insert the range of values, then select the min/max of the temp table from within a stored procedure or UDF. This is a basic construct, so feel free to revise as needed.

For example:

CREATE PROCEDURE GetMinSpeed() AS
BEGIN

    CREATE TABLE #speed (Driver NVARCHAR(10), SPEED INT);
    '
    ' Insert any number of data you need to sort and pull from
    '
    INSERT INTO #speed (N'Petty', 165)
    INSERT INTO #speed (N'Earnhardt', 172)
    INSERT INTO #speed (N'Patrick', 174)

    SELECT MIN(SPEED) FROM #speed

    DROP TABLE #speed

END

How to get text from each cell of an HTML table?

Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef (just a string) and a TD with an image that contains a title attribute with Overdue by in it:

    public ReadOnlyCollection<IWebElement> GetTableRows()
    {
        this.iwebElement = GetElement();
        return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
    }

And within my main code:

        ...
        ReadOnlyCollection<IWebElement> TableRows;
        TableRows = f.Grid_Fault.GetTableRows();

        foreach (IWebElement row in TableRows)
        {
            if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
              row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
                return true;
        }

How to get input textfield values when enter key is pressed in react js?

Adding onKeyPress will work onChange in Text Field.

<TextField
  onKeyPress={(ev) => {
    console.log(`Pressed keyCode ${ev.key}`);
    if (ev.key === 'Enter') {
      // Do code here
      ev.preventDefault();
    }
  }}
/>

How to set alignment center in TextBox in ASP.NET?

Add the css styling text-align: center to the control.

Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:

<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>

This certificate has an invalid issuer Apple Push Services

In Apple's Developer's portal, add a new certificate, and when asked "What type of certificate do you need?" choose "WorldWide developer relations certificate". Generate the new certificate, download and install. The moment you do that, you will no longer see the message you have described.

Edit:
The certificate can be downloaded from the following page: https://www.apple.com/certificateauthority/ You can choose one of the following two certificates: "WWDR Certificate (Expiring 02/07/23)" or "WWDR Certificate (Expiring 02/14/16)"

jQuery: How can I create a simple overlay?

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

How to add extra whitespace in PHP?

is this for display purposes? if so you really should consider separating your display form your logic and use style sheets for formatting. being server side php should really allow providing and accepting data. while you could surely use php to do what you are asking I am a very firm believer in keeping display and logic with as much separation as possible. with styles you can do all of your typesetting.

give output class wrappers and style accordingly.

What is the difference between association, aggregation and composition?

Association is generalized concept of relations. It includes both Composition and Aggregation.

Composition(mixture) is a way to wrap simple objects or data types into a single unit. Compositions are a critical building block of many basic data structures

Aggregation(collection) differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true.

Both denotes relationship between object and only differ in their strength.

Trick to remember the difference : has A -Aggregation and Own - cOmpositoin

enter image description here

Now let observe the following image

relations

enter image description here

Analogy:

Composition: The following picture is image composition i.e. using individual images making one image.
enter image description here

Aggregation : collection of image in single location

enter image description here

For example, A university owns various departments, and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Note however:

If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.

http://msdn.microsoft.com/en-us/library/ms173763.aspx

Vuejs: Event on route change

Setup a watcher on the $route in your component like this:

watch:{
    $route (to, from){
        this.show = false;
    }
} 

This observes for route changes and when changed ,sets show to false

How to copy a selection to the OS X clipboard

You can visually select text and type :w !pbcopy<CR>

Or you can include the below key mappings in your ~/.vimrc file. They cut/copy text in visual mode to the operating system's clipboard.

vmap <C-x> :!pbcopy<CR>  
vmap <C-c> :w !pbcopy<CR><CR> 

source: http://drydevelopment.com/blog/vim-pbcopy-on-os-x

Where can I download Eclipse Android bundle?

The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:

  1. Start Eclipse, then select Help > Install New Software.
  2. Click Add, in the top-right corner.
  3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/
  4. Click OK.
  5. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
  6. In the next window, you'll see a list of the tools to be downloaded. Click Next.
  7. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK
  8. When the installation completes, restart Eclipse.

Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.


Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.

Print string to text file

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python

Rounding a double to turn it into an int (java)

You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round() method. You need to either call Math.round(n), or statically import Math.round, and then call it like you have.

How do I use select with date condition?

If you put in

SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009' 

it will automatically convert the string '1/20/2009' into the DateTime format for a date of 1/20/2009 00:00:00. So by using >= you should get every user whose registration date is 1/20/2009 or more recent.

Edit: I put this in the comment section but I should probably link it here as well. This is an article detailing some more in depth ways of working with DateTime's in you queries: http://www.databasejournal.com/features/mssql/article.php/2209321/Working-with-SQL-Server-DateTime-Variables-Part-Three---Searching-for-Particular-Date-Values-and-Ranges.htm

List of remotes for a Git repository?

FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:

$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
     R   W     android
     R   W     bistro
     R   W     checkpn
...

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

UIScrollView Scrollable Content Size Ambiguity

In my case I received the issue of incorrect content size and content Size Ambiguity in iPad but was working in case of iPhone. I have done the following changes in storyboard to resolve the issue.

  1. Add scrollview in UIView and add constraints leading, top, trailing and bottom to 0,0,0,0.
  2. Set height of scroll view as per the requirements for eg. 100.
  3. Add UIView to scroll view and add constraints leading, top, trailing and bottom to 0,0,0,0 and align centre(X) and center(Y) constraints.
  4. Deselect “Content Layout Guides” in size inspector of scroll view.

How to write both h1 and h2 in the same line?

In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.

<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>

Will give you:

What the...heck is going on?

and not

What the... 
heck is going on?

Is it better to use NOT or <> when comparing values?

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

StartTime = Timer
For x = 1 to 100000000
   If 4 <> 3 Then
   End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
   If Not (4 = 3) Then
   End if
Next
WScript.echo Timer-StartTime

The results I get on my machine:

4.783203
5.552734

Add SUM of values of two LISTS into new LIST

one-liner solution

list(map(lambda x,y: x+y, a,b))

Is it possible to set an object to null?

You can set any pointer to NULL, though NULL is simply defined as 0 in C++:

myObject *foo = NULL;

Also note that NULL is defined if you include standard headers, but is not built into the language itself. If NULL is undefined, you can use 0 instead, or include this:

#ifndef NULL
#define NULL 0
#endif

As an aside, if you really want to set an object, not a pointer, to NULL, you can read about the Null Object Pattern.

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

Convert a Unix timestamp to time in JavaScript

function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }

How to avoid using Select in Excel VBA

Working with the .Parent feature, this example shows how setting only one myRng reference enables dynamic access to the entire environment without any .Select, .Activate, .Activecell, .ActiveWorkbook, .ActiveSheet and so on. (There isn't any generic .Child feature.)

Sub ShowParents()
    Dim myRng As Range
    Set myRng = ActiveCell
    Debug.Print myRng.Address                    ' An address of the selected cell
    Debug.Print myRng.Parent.name                ' The name of sheet, where MyRng is in
    Debug.Print myRng.Parent.Parent.name         ' The name of workbook, where MyRng is in
    Debug.Print myRng.Parent.Parent.Parent.name  ' The name of application, where MyRng is in

    ' You may use this feature to set reference to these objects
    Dim mySh  As Worksheet
    Dim myWbk As Workbook
    Dim myApp As Application

    Set mySh = myRng.Parent
    Set myWbk = myRng.Parent.Parent
    Set myApp = myRng.Parent.Parent.Parent
    Debug.Print mySh.name, mySh.Cells(10, 1).Value
    Debug.Print myWbk.name, myWbk.Sheets.Count
    Debug.Print myApp.name, myApp.Workbooks.Count

    ' You may use dynamically addressing
    With myRng
        .Copy

        ' Pastes in D1 on sheet 2 in the same workbook, where the copied cell is
        .Parent.Parent.Sheets(2).Range("D1").PasteSpecial xlValues

        ' Or myWbk.Sheets(2).Range("D1").PasteSpecial xlValues

        ' We may dynamically call active application too
        .Parent.Parent.Parent.CutCopyMode = False

        ' Or myApp.CutCopyMode = False
    End With
End Sub

Changing SqlConnection timeout

You can also use the SqlConnectionStringBuilder

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 10;
using (var connection = new SqlConnection(builder.ToString()))
{
    // code goes here
}

Running stages in parallel with Jenkins workflow / pipeline

that syntax is now deprecated, you will get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
       parallel firstTask: {
       ^

WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
       parallel secondTask: {
       ^

2 errors

You should do something like:

stage("Parallel") {
    steps {
        parallel (
            "firstTask" : {
                //do some stuff
            },
            "secondTask" : {
                // Do some other stuff in parallel
            }
        )
    }
}

Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:

pipeline {
  stages {
    stage("Work 1"){
     steps{
      parallel ( "Build common Library":   
            {
              node('<Label>'){
                  /// your stuff
                  }
            },

        "Build Utilities" : {
            node('<Label>'){
               /// your stuff
              }
           }
         )
    }
}

All VMs should be labelled as to use as a pool.

What does -> mean in C++?

x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

How to access site running apache server over lan without internet connection

Your firewall does not allow any new connection to share information without your consent. ONLY thing to do is give your consent to your firewall.

  1. Go to Firewall settings in Control Panel

  2. Click on Advanced Settings

  3. Click on Inbound Rules and Add a new rule.

  4. Choose 'Type Of Rule' to Port.

  5. Allow this for All Programs.

  6. Allow this rule to be applied on all Profiles i.e. Domain, Private, Public.

  7. Give this rule any name.

That's it. Now another PC and mobiles connected on the same network can access the local sites. Lets Start Development.

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

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

So, you could define the variable with:

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

Custom exception type

From WebReference:

throw { 
  name:        "System Error", 
  level:       "Show Stopper", 
  message:     "Error detected. Please contact the system administrator.", 
  htmlMessage: "Error detected. Please contact the <a href=\"mailto:[email protected]\">system administrator</a>.",
  toString:    function(){return this.name + ": " + this.message;} 
}; 

How can I view all historical changes to a file in SVN

You could use git-svn to import the repository into a Git repository, then use git log -p filename. This shows each log entry for the file followed by the corresponding diff.

When and why do I need to use cin.ignore() in C++?

Ignore is exactly what the name implies.

It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.

It works with both input and output buffers.

Essentially, for std::cin statements you use ignore before you do a getline call, because when a user inputs something with std::cin, they hit enter and a '\n' char gets into the cin buffer. Then if you use getline, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n') and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)

Select mySQL based only on month and year

$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;

JAX-WS and BASIC authentication, when user names and passwords are in a database

In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:

public class ClientHandler implements SOAPHandler<SOAPMessageContext>{

    public boolean handleMessage(final SOAPMessageContext soapMessageContext)
    {
        final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outInd.booleanValue())
        {
          try 
          {
               soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
               soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
          } 
          catch (Exception e)
          {
               e.printStackTrace();
               return false;
          }
         }
      return true;
     }
}

How to deny access to a file in .htaccess

I don't believe the currently accepted answer is correct. For example, I have the following .htaccess file in the root of a virtual server (apache 2.4):

<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>

This prevents external access to reminder.php which is in a subdirectory. I have a similar .htaccess file on my Apache 2.2 server with the same effect:

<Files "reminder.php">
        Order Deny,Allow
        Deny from all
        Allow from localhost
        Allow from 127.0.0.1
     Allow from xxx.yyy.zzz.aaa
</Files>

I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess file, viz <Files ./inscription/log.txt> which is causing it to fail. It would be simpler to put the .htaccess file in the same directory as log.txt i.e. in the inscription directory and it will work there.

Python conversion from binary string to hexadecimal

To convert binary string to hexadecimal string, we don't need any external libraries. Use formatted string literals (known as f-strings). This feature was added in python 3.6 (PEP 498)

>>> bs = '0000010010001101'
>>> hexs = f'{int(bs, 2):X}'
>>> print(hexs)
>>> '48D'

If you want hexadecimal strings in small-case, use small "x" as follows

f'{int(bs, 2):x}'

Where bs inside f-string is a variable which contains binary strings assigned prior

f-strings are lost more useful and effective. They are not being used at their full potential.

How to apply filters to *ngFor?

I'm not sure when it came in but they already made slice pipe that will do that. It's well documented too.

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

<p *ngFor="let feature of content?.keyFeatures | slice:1:5">
   {{ feature.description }}
</p>

How to declare array of zeros in python (or an array of a certain size)

use numpy

import numpy
zarray = numpy.zeros(100)

And then use the Histogram library function

Is it possible to use the instanceof operator in a switch statement?

If you want to avoid the verbosity of if(){} else if{}, you may consider switching this single file to kotlin and use the switch-like when expression in combination with is operator.

In any case Kotlin and java files can co-exist in a project.

when (this) { //switch-like statement in kotlin supporting class-pattern-matching and smart casts via `is` operator.
    is A -> doA()
    is B -> doB()
    is C -> doC()
}

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

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

Remember:

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

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

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

Creating a new directory in C

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h>
#include <sys/types.h>

int result = mkdir("/home/me/test.txt", 0777);

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

how to toggle attr() in jquery

For what it's worth.

$('.js-toggle-edit').on('click', function (e) {
    var bool = $('.js-editable').prop('readonly');
    $('.js-editable').prop('readonly', ! bool);
})

Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.

How to add leading zeros?

str_pad from the stringr package is an alternative.

anim = 25499:25504
str_pad(anim, width=6, pad="0")

In Mongoose, how do I sort by date? (node.js)

The correct answer is:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

One line if in VB .NET

Or

IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)

How to remove all event handlers from an event

From Removing All Event Handlers:

Directly no, in large part because you cannot simply set the event to null.

Indirectly, you could make the actual event private and create a property around it that tracks all of the delegates being added/subtracted to it.

Take the following:

List<EventHandler> delegates = new List<EventHandler>();

private event EventHandler MyRealEvent;

public event EventHandler MyEvent
{
    add
    {
        MyRealEvent += value;
        delegates.Add(value);
    }

    remove
    {
        MyRealEvent -= value;
        delegates.Remove(value);
    }
}

public void RemoveAllEvents()
{
    foreach(EventHandler eh in delegates)
    {
        MyRealEvent -= eh;
    }
    delegates.Clear();
}

What is the difference between 'java', 'javaw', and 'javaws'?

I have checked that the output redirection works with javaw:

javaw -cp ... mypath.MyClass ... arguments 1>log.txt 2>err.txt

It means, if the Java application prints out anything via System.out or System.err, it is written to those files, as also with using java (without w). Especially on starting java, the JRE may write starting errors (class not found) on the error output pipe. In this respect, it is essential to know about errors. I suggest to use the console redirection in any case if javaw is invoked.

In opposite if you use

start java .... 1>log.txt 2>err.txt

With the Windows console start command, the console output redirection does not work with java nor with javaw.

Explanation why it is so: I think that javaw opens an internal process in the OS (adequate using the java.lang.Process class), and transfers a known output redirection to this process. If no redirection is given on the command line, nothing is redirected and the internal started process for javaw doesn't have any console outputs. The behavior for java.lang.Process is similar. The virtual machine may use this internal feature for javaw too.

If you use 'start', the Windows console creates a new process for Windows to execute the command after start, but this mechanism does not use a given redirection for the started sub process, unfortunately.

UTF-8 encoded html pages show ? (questions marks) instead of characters

Looks like nobody mentioned

SET NAMES utf8;

I found this solution here and it helped me. How to apply it:

To be all UTF-8, issue the following statement just after you’ve made the connection to the database server: SET NAMES utf8;

Maybe this will help someone.

Reading from memory stream to string

In case of a very large stream length there is the hazard of memory leak due to Large Object Heap. i.e. The byte buffer created by stream.ToArray creates a copy of memory stream in Heap memory leading to duplication of reserved memory. I would suggest to use a StreamReader, a TextWriter and read the stream in chunks of char buffers.

In netstandard2.0 System.IO.StreamReader has a method ReadBlock

you can use this method in order to read the instance of a Stream (a MemoryStream instance as well since Stream is the super of MemoryStream):

private static string ReadStreamInChunks(Stream stream, int chunkLength)
{
    stream.Seek(0, SeekOrigin.Begin);
    string result;
    using(var textWriter = new StringWriter())
    using (var reader = new StreamReader(stream))
    {
        var readChunk = new char[chunkLength];
        int readChunkLength;
        //do while: is useful for the last iteration in case readChunkLength < chunkLength
        do
        {
            readChunkLength = reader.ReadBlock(readChunk, 0, chunkLength);
            textWriter.Write(readChunk,0,readChunkLength);
        } while (readChunkLength > 0);

        result = textWriter.ToString();
    }

    return result;
}

NB. The hazard of memory leak is not fully eradicated, due to the usage of MemoryStream, that can lead to memory leak for large memory stream instance (memoryStreamInstance.Size >85000 bytes). You can use Recyclable Memory stream, in order to avoid LOH. This is the relevant library

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Screen Size Class

-

  1. Hidden on all .d-none

  2. Hidden only on xs .d-none .d-sm-block

  3. Hidden only on sm .d-sm-none .d-md-block

  4. Hidden only on md .d-md-none .d-lg-block

  5. Hidden only on lg .d-lg-none .d-xl-block

  6. Hidden only on xl .d-xl-none

  7. Visible on all .d-block

  8. Visible only on xs .d-block .d-sm-none

  9. Visible only on sm .d-none .d-sm-block .d-md-none

  10. Visible only on md .d-none .d-md-block .d-lg-none

  11. Visible only on lg .d-none .d-lg-block .d-xl-none

  12. Visible only on xl .d-none .d-xl-block

Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

MongoDB via Mongoose JS - What is findByID?

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

How to check if a word is an English word with Python?

It won't work well with WordNet, because WordNet does not contain all english words. Another possibility based on NLTK without enchant is NLTK's words corpus

>>> from nltk.corpus import words
>>> "would" in words.words()
True
>>> "could" in words.words()
True
>>> "should" in words.words()
True
>>> "I" in words.words()
True
>>> "you" in words.words()
True

HashMap - getting First Key value

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

What is the most efficient way to loop through dataframes with pandas?

For sure, the fastest way to iterate over a dataframe is to access the underlying numpy ndarray either via df.values (as you do) or by accessing each column separately df.column_name.values. Since you want to have access to the index too, you can use df.index.values for that.

index = df.index.values
column_of_interest1 = df.column_name1.values
...
column_of_interestk = df.column_namek.values

for i in range(df.shape[0]):
   index_value = index[i]
   ...
   column_value_k = column_of_interest_k[i]

Not pythonic? Sure. But fast.

If you want to squeeze more juice out of the loop you will want to look into cython. Cython will let you gain huge speedups (think 10x-100x). For maximum performance check memory views for cython.

Develop Android app using C#

Here is a new one (Note: in Tech Preview stage): http://www.dot42.com

It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Disclosure: I work for this company


UPDATE: all sources are now on https://github.com/dot42

Python not working in command prompt?

Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:

  1. Press the windows key.
  2. Type "system env". Press enter.
  3. Press alt + n
  4. Press alt + e
  5. Press right, and then ; (that's a semicolon)
  6. Without adding a space, type this at the end: C:\Python27
  7. Hit enter twice. Hit esc.
  8. Use windows key + r to bring up the run dialog. Type in python and press enter.

JavaScript - Getting HTML form values

document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
    if(form.id == "wanted_id") {
        form = document.forms[i];
    }
}

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value;
jsFunction(wanted_value);

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java to jdk7, but the $JAVA_HOME environment variable still pointed to the old directory of Java 6.

How can I use ":" as an AWK field separator?

If you want to do it programatically, you can use the FS variable:

echo "1: " | awk 'BEGIN { FS=":" } /1/ { print $1 }'

Note that if you change it in the main loop rather than the BEGIN loop, it takes affect for the next line read in, since the current line has already been split.

How to simplify a null-safe compareTo() implementation?

One of the simple way of using NullSafe Comparator is to use Spring implementation of it, below is one of the simple example to refer :

public int compare(Object o1, Object o2) {
        ValidationMessage m1 = (ValidationMessage) o1;
        ValidationMessage m2 = (ValidationMessage) o2;
        int c;
        if (m1.getTimestamp() == m2.getTimestamp()) {
            c = NullSafeComparator.NULLS_HIGH.compare(m1.getProperty(), m2.getProperty());
            if (c == 0) {
                c = m1.getSeverity().compareTo(m2.getSeverity());
                if (c == 0) {
                    c = m1.getMessage().compareTo(m2.getMessage());
                }
            }
        }
        else {
            c = (m1.getTimestamp() > m2.getTimestamp()) ? -1 : 1;
        }
        return c;
    }

How to serialize an Object into a list of URL query parameters?

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

What is this Javascript "require"?

Two flavours of module.exports / require:

(see here)

Flavour 1
export file (misc.js):

var x = 5;
var addX = function(value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

other file:

var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));

Flavour 2
export file (user.js):

var User = function(name, email) {
  this.name = name;
  this.email = email;
};
module.exports = User;

other file:

var user = require('./user');
var u = new user();

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

Why has it failed to load main-class manifest attribute from a JAR file?

You can run with:

java -cp .;app.jar package.MainClass

It works for me if there is no manifest in the JAR file.

What is the default scope of a method in Java?

If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java

How do you select the entire excel sheet with Range using VBA?

you have a few options here:

  1. Using the UsedRange property
  2. find the last row and column used
  3. use a mimic of shift down and shift right

I personally use the Used Range and find last row and column method most of the time.

Here's how you would do it using the UsedRange property:

Sheets("Sheet_Name").UsedRange.Select

This statement will select all used ranges in the worksheet, note that sometimes this doesn't work very well when you delete columns and rows.

The alternative is to find the very last cell used in the worksheet

Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
    Range(Cells(1, 1), rngTemp).Select
End If

What this code is doing:

  1. Find the last cell containing any value
  2. select cell(1,1) all the way to the last cell

How to get cumulative sum

Without using any type of JOIN cumulative salary for a person fetch by using follow query:

SELECT * , (
  SELECT SUM( salary ) 
  FROM  `abc` AS table1
  WHERE table1.ID <=  `abc`.ID
    AND table1.name =  `abc`.Name
) AS cum
FROM  `abc` 
ORDER BY Name

What is a CSRF token? What is its importance and how does it work?

Yes, the post data is safe. But the origin of that data is not. This way somebody can trick user with JS into logging in to your site, while browsing attacker's web page.

In order to prevent that, django will send a random key both in cookie, and form data. Then, when users POSTs, it will check if two keys are identical. In case where user is tricked, 3rd party website cannot get your site's cookies, thus causing auth error.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

As complement to Mark's answer, the compile function does not have access to scope, but the link function does.

I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).

Using the "start" command with parameters passed to the started program

None of these answers worked for me.

Instead, I had to use the Call command:

Call "\\Path To Program\Program.exe" <parameters>

I'm not sure this actually waits for completion... the C++ Redistributable I was installing went fast enough that it didn't matter

Python: Best way to add to sys.path relative to the current running script

I'm using:

import sys,os
sys.path.append(os.getcwd())

GET URL parameter in PHP

Whomever gets nothing back, I think he just has to enclose the result in html tags,

Like this:

<html>
<head></head>
<body>
<?php
echo $_GET['link'];
?>
<body>
</html>

If two cells match, return value from third

I think what you want is something like:

=INDEX(B:B,MATCH(C2,A:A,0))  

I should mention that MATCH checks the position at which the value can be found within A:A (given the 0, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.

jquery function setInterval

You can use it like this:

$(document).ready(function(){

    setTimeout("swapImages()",1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
        setTimeout("swapImages()",1000);
}

});

Remove duplicate rows in MySQL

Deleting duplicates on MySQL tables is a common issue, that's genarally the result of a missing constraint to avoid those duplicates before hand. But this common issue usually comes with specific needs... that do require specific approaches. The approach should be different depending on, for example, the size of the data, the duplicated entry that should be kept (generally the first or the last one), whether there are indexes to be kept, or whether we want to perform any additional action on the duplicated data.

There are also some specificities on MySQL itself, such as not being able to reference the same table on a FROM cause when performing a table UPDATE (it'll raise MySQL error #1093). This limitation can be overcome by using an inner query with a temporary table (as suggested on some approaches above). But this inner query won't perform specially well when dealing with big data sources.

However, a better approach does exist to remove duplicates, that's both efficient and reliable, and that can be easily adapted to different needs.

The general idea is to create a new temporary table, usually adding a unique constraint to avoid further duplicates, and to INSERT the data from your former table into the new one, while taking care of the duplicates. This approach relies on simple MySQL INSERT queries, creates a new constraint to avoid further duplicates, and skips the need of using an inner query to search for duplicates and a temporary table that should be kept in memory (thus fitting big data sources too).

This is how it can be achieved. Given we have a table employee, with the following columns:

employee (id, first_name, last_name, start_date, ssn)

In order to delete the rows with a duplicate ssn column, and keeping only the first entry found, the following process can be followed:

-- create a new tmp_eployee table
CREATE TABLE tmp_employee LIKE employee;

-- add a unique constraint
ALTER TABLE tmp_employee ADD UNIQUE(ssn);

-- scan over the employee table to insert employee entries
INSERT IGNORE INTO tmp_employee SELECT * FROM employee ORDER BY id;

-- rename tables
RENAME TABLE employee TO backup_employee, tmp_employee TO employee;

Technical explanation

  • Line #1 creates a new tmp_eployee table with exactly the same structure as the employee table
  • Line #2 adds a UNIQUE constraint to the new tmp_eployee table to avoid any further duplicates
  • Line #3 scans over the original employee table by id, inserting new employee entries into the new tmp_eployee table, while ignoring duplicated entries
  • Line #4 renames tables, so that the new employee table holds all the entries without the duplicates, and a backup copy of the former data is kept on the backup_employee table

? Using this approach, 1.6M registers were converted into 6k in less than 200s.

Chetan, following this process, you could fast and easily remove all your duplicates and create a UNIQUE constraint by running:

CREATE TABLE tmp_jobs LIKE jobs;

ALTER TABLE tmp_jobs ADD UNIQUE(site_id, title, company);

INSERT IGNORE INTO tmp_jobs SELECT * FROM jobs ORDER BY id;

RENAME TABLE jobs TO backup_jobs, tmp_jobs TO jobs;

Of course, this process can be further modified to adapt it for different needs when deleting duplicates. Some examples follow.

? Variation for keeping the last entry instead of the first one

Sometimes we need to keep the last duplicated entry instead of the first one.

CREATE TABLE tmp_employee LIKE employee;

ALTER TABLE tmp_employee ADD UNIQUE(ssn);

INSERT IGNORE INTO tmp_employee SELECT * FROM employee ORDER BY id DESC;

RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
  • On line #3, the ORDER BY id DESC clause makes the last ID's to get priority over the rest

? Variation for performing some tasks on the duplicates, for example keeping a count on the duplicates found

Sometimes we need to perform some further processing on the duplicated entries that are found (such as keeping a count of the duplicates).

CREATE TABLE tmp_employee LIKE employee;

ALTER TABLE tmp_employee ADD UNIQUE(ssn);

ALTER TABLE tmp_employee ADD COLUMN n_duplicates INT DEFAULT 0;

INSERT INTO tmp_employee SELECT * FROM employee ORDER BY id ON DUPLICATE KEY UPDATE n_duplicates=n_duplicates+1;

RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
  • On line #3, a new column n_duplicates is created
  • On line #4, the INSERT INTO ... ON DUPLICATE KEY UPDATE query is used to perform an additional update when a duplicate is found (in this case, increasing a counter) The INSERT INTO ... ON DUPLICATE KEY UPDATE query can be used to perform different types of updates for the duplicates found.

? Variation for regenerating the auto-incremental field id

Sometimes we use an auto-incremental field and, in order the keep the index as compact as possible, we can take advantage of the deletion of the duplicates to regenerate the auto-incremental field in the new temporary table.

CREATE TABLE tmp_employee LIKE employee;

ALTER TABLE tmp_employee ADD UNIQUE(ssn);

INSERT IGNORE INTO tmp_employee SELECT (first_name, last_name, start_date, ssn) FROM employee ORDER BY id;

RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
  • On line #3, instead of selecting all the fields on the table, the id field is skipped so that the DB engine generates a new one automatically

? Further variations

Many further modifications are also doable depending on the desired behavior. As an example, the following queries will use a second temporary table to, besides 1) keep the last entry instead of the first one; and 2) increase a counter on the duplicates found; also 3) regenerate the auto-incremental field id while keeping the entry order as it was on the former data.

CREATE TABLE tmp_employee LIKE employee;

ALTER TABLE tmp_employee ADD UNIQUE(ssn);

ALTER TABLE tmp_employee ADD COLUMN n_duplicates INT DEFAULT 0;

INSERT INTO tmp_employee SELECT * FROM employee ORDER BY id DESC ON DUPLICATE KEY UPDATE n_duplicates=n_duplicates+1;

CREATE TABLE tmp_employee2 LIKE tmp_employee;

INSERT INTO tmp_employee2 SELECT (first_name, last_name, start_date, ssn) FROM tmp_employee ORDER BY id;

DROP TABLE tmp_employee;

RENAME TABLE employee TO backup_employee, tmp_employee2 TO employee;

Parse error: Syntax error, unexpected end of file in my PHP code

To supplement other answers, it could also be due to the auto-minification of your php script if you are using an ftp client like FileZilla. Ensure that the transfer type is set to Binary and not ASCII or auto. The ASCII or auto transfer type can minify your php code leading to this error.

How To Add An "a href" Link To A "div"?

Can't you surround it with an a tag?

  <a href="#"><div id="buttonOne">
        <div id="linkedinB">
            <img src="img/linkedinB.png" width="40" height="40">
        </div>
  </div></a>

How do I create a readable diff of two spreadsheets using git diff?

Use Altova DiffDog

Use diffdog's XML diff mode and Grid View to review the differences in an easy to read tabular format. Text diff'ing is MUCH HARDER for spreadsheets of any complexity. With this tool, at least two methods are viable under various circumstances.

  1. Save As .xml

    To detect the differences of a simple, one sheet spreadsheet, save the Excel spreadsheets to compare as XML Spreadsheet 2003 with a .xml extension.

  2. Save As .xlsx

    To detect the differences of most spreadsheets in a modularized document model, save the Excel spreadsheets to compare as an Excel Workbook in .xlsx form. Open the files to diff with diffdog. It informs you that the file is a ZIP archive, and asks if you want to open it for directory comparison. Upon agreeing to directory comparison, it becomes a relatively simple matter of double-clicking logical parts of the document to diff them (with the XML diff mode). Most parts of the .xslx document are XML-formatted data. The Grid View is extremely useful. It is trivial to diff individual sheets to focus the analysis on areas that are known to have changed.

Excel's propensity to tweak certain attribute names with every save is annoying, but diffdog's XML diff'ing capabilities include the ability to filter certain kinds of differences. For example, Excel spreadsheets in XML form contain row and c elements that have s attributes (style) that rename with every save. Setting up a filter like c:s makes it much easier to view only content changes.

diffdog has a lot of diff'ing capability. I've listed the XML diff modes only simply because I haven't used another tool that I liked better when it comes to differencing Excel documents.

Combine Points with lines with ggplot2

You may find that using the `group' aes will help you get the result you want. For example:

tu <- expand.grid(Land       = gl(2, 1, labels = c("DE", "BB")),
                  Altersgr   = gl(5, 1, labels = letters[1:5]),
                  Geschlecht = gl(2, 1, labels = c('m', 'w')),
                  Jahr       = 2000:2009)

set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)

ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) + 
  geom_point() + geom_line() + 
  facet_grid(Geschlecht ~ Land)

Which produces the plot found here:

enter image description here

MSSQL Error 'The underlying provider failed on Open'

I had the same issue few days ago, using "Integrated Security=True;" in the connection string you need to run the application pool identity under "localsystem" Sure this is not recommended but for testing it does the job.

This is how you can change the identity in IIS 7: http://www.iis.net/learn/manage/configuring-security/application-pool-identities

How to join (merge) data frames (inner, outer, left, right)

There are some good examples of doing this over at the R Wiki. I'll steal a couple here:

Merge Method

Since your keys are named the same the short way to do an inner join is merge():

merge(df1,df2)

a full inner join (all records from both tables) can be created with the "all" keyword:

merge(df1,df2, all=TRUE)

a left outer join of df1 and df2:

merge(df1,df2, all.x=TRUE)

a right outer join of df1 and df2:

merge(df1,df2, all.y=TRUE)

you can flip 'em, slap 'em and rub 'em down to get the other two outer joins you asked about :)

Subscript Method

A left outer join with df1 on the left using a subscript method would be:

df1[,"State"]<-df2[df1[ ,"Product"], "State"]

The other combination of outer joins can be created by mungling the left outer join subscript example. (yeah, I know that's the equivalent of saying "I'll leave it as an exercise for the reader...")

What does LINQ return when the results are empty

.ToList returns an empty list. (same as new List() );

How can I auto hide alert box after it showing it?

You can't close an alert box with Javascript.

You could, however, use a window instead:

var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)

How do you do exponentiation in C?

The non-recursive version of the function is not too hard - here it is for integers:

long powi(long x, unsigned n)
{
    long p = x;
    long r = 1;

    while (n > 0)
    {
        if (n % 2 == 1)
            r *= p;
        p *= p;
        n /= 2;
    }

    return(r);
}

(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

Keyboard shortcuts in WPF

Try this.

First create a RoutedCommand object:

RoutedCommand newCmd = new RoutedCommand();
newCmd.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control));
CommandBindings.Add(new CommandBinding(newCmd, btnNew_Click));

Changing password with Oracle SQL Developer

I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.

Steps:

  1. connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password

  2. find the "Other_users" node within the tree as the image below displays

enter image description here

3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"

enter image description here

4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".

enter image description here

And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.

Scroll RecyclerView to show selected item on top

what i did to restore the scroll position after refreshing the RecyclerView on button clicked:

if (linearLayoutManager != null) {

    index = linearLayoutManager.findFirstVisibleItemPosition();
    View v = linearLayoutManager.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
    Log.d("TAG", "visible position " + " " + index);
}

else{
    index = 0;
}

linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.scrollToPositionWithOffset(index, top);

getting the offset of the first visible item from the top before creating the linearLayoutManager object and after instantiating it the scrollToPositionWithOffset of the LinearLayoutManager object was called.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

PHP code to remove everything but numbers

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

Apache giving 403 forbidden errors

Check that :

  • Apache can physically access the file (the user that run apache, probably www-data or apache, can access the file in the filesystem)
  • Apache can list the content of the folder (read permission)
  • Apache has a "Allow" directive for that folder. There should be one for /var/www/, you can check default vhost for example.

Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log) which will describe why you get the 403 error exactly.

Finally, you may want to restart apache, just to be sure all that configuration is applied. This can be generally done with /etc/init.d/apache2 restart. On some system, the script will be called httpd. Just figure out.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

Excel Define a range based on a cell value

Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:

=SUM(A1:INDIRECT(CONCATENATE("A",B1)))

CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).

INDIRECT convert "A3" to a index.

see this link Using the value in a cell as a cell reference in a formula?

How to set the font size in Emacs?

Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.

Saving to CSV in Excel loses regional date format

Change the date and time settings for your computer in the "short date" format under calendar settings. This will change the format for everything yyyy-mm-dd or however you want it to display; but remember it will look like that even for files saved on your computer.

At least it works.

Tell Ruby Program to Wait some amount of time

sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).

Is it possible to get a list of files under a directory of a website? How?

Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.

How do I check if an object has a specific property in JavaScript?

OK, it looks like I had the right answer unless if you don't want inherited properties:

if (x.hasOwnProperty('key'))

Here are some other options to include inherited properties:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

GIT_CURL_VERBOSE=1 git [clone|fetch]…

should tell you where the problem is. In my case it was due to cURL not supporting PEM certificates when built against NSS, due to that support not being mainline in NSS (#726116 #804215 #402712 and more).

Various ways to remove local Git changes

For discard all i like to stash and drop that stash, it's the fastest way to discard all, especially if you work between multiple repos.

This will stash all changes in {0} key and instantly drop it from {0}

git stash && git stash drop

How to delete an object by id with entity framework

The same as @Nix with a small change to be strongly typed:

If you don't want to query for it just create an entity, and then delete it.

                Customer customer = new Customer () { Id = id };
                context.Customers.Attach(customer);
                context.Customers.DeleteObject(customer);
                context.SaveChanges();

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

How can I see what has changed in a file before committing to git?

Go to your respective git repo, then run the below command:

git diff filename

It will open the file with the changes marked, press return/enter key to scroll down the file.

P.S. filename should include the full path of the file or else you can run without the full file path by going in the respective directory/folder of the file

How to get current working directory in Java?

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();

ASP.NET MVC - Getting QueryString values

Query string parameters can be accepted simply by using an argument on the action - i.e.

public ActionResult Foo(string someValue, int someOtherValue) {...}

which will accept a query like .../someroute?someValue=abc&someOtherValue=123

Other than that, you can look at the request directly for more control.

Open window in JavaScript with HTML inserted

Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:

https://codepen.io/trusktr/pen/mdeQbKG?editors=0010

This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):

_x000D_
_x000D_
const winHtml = `<!DOCTYPE html>_x000D_
    <html>_x000D_
        <head>_x000D_
            <title>Window with Blob</title>_x000D_
        </head>_x000D_
        <body>_x000D_
            <h1>Hello from the new window!</h1>_x000D_
        </body>_x000D_
    </html>`;_x000D_
_x000D_
const winUrl = URL.createObjectURL(_x000D_
    new Blob([winHtml], { type: "text/html" })_x000D_
);_x000D_
_x000D_
const win = window.open(_x000D_
    winUrl,_x000D_
    "win",_x000D_
    `width=800,height=400,screenX=200,screenY=200`_x000D_
);
_x000D_
_x000D_
_x000D_

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

How to download an entire directory and subdirectories using wget?

wget -r --no-parent URL --user=username --password=password

the last two options are optional if you have the username and password for downloading, otherwise no need to use them.

You can also see more options in the link https://www.howtogeek.com/281663/how-to-use-wget-the-ultimate-command-line-downloading-tool/

Chart won't update in Excel (2007)

Ok I have a solution, really....

I found that the problem with my charts not updating first occurred shortly after I had hidden some data columns feeding the chart, and checked "show data hidden in rows and columns" in the Chart's "Select Data Source" msg box).

I found that if I went back into the "Select Data Source" msg box and unchecked/rechecked the "show data hidden in rows and columns" that the chart refreshes.

Programatically I inserted the following into a Macro that I linked a button to, it refreshes all of my charts quick enough for a workaround to a known bug. This code assumes one chart per worksheet but another for statement for charts 1 to N could be added if desired:

Sub RefreshCharts()

    Application.ScreenUpdating = False

For I = 1 To ActiveWorkbook.Worksheets.Count

Worksheets(I).Activate

    ActiveSheet.ChartObjects("Chart 1").Activate

    ActiveChart.PlotVisibleOnly = True

    ActiveChart.PlotVisibleOnly = False

Next I

    Application.ScreenUpdating = True

End Sub

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I run across this and at the beginning I found it really confusing to be honest and I think this confusion comes from using the word "CMD" because in fact what goes there acts as argument. So after digging a little bit I understood how it works. Basically:

ENTRYPOINT --> what you specify here would be the command to be executed when you container starts. If you omit this definition docker will use /bin/sh -c bash to run your container.

CMD --> these are the arguments appended to the ENTRYPOINT unless the user specifies some custom argument, i.e: docker run ubuntu <custom_cmd> in this case instead of appending what's specified on the image in the CMD section, docker will run ENTRYPOINT <custom_cmd>. In case ENTRYPOINT has not been specified, what goes here will be passed to /bin/sh -c acting in fact as the command to be executed when starting the container.

As everything it's better to explain what's going on by examples. So let's say I create a simple docker image by using the following specification Dockerfile:

From ubuntu
ENTRYPOINT ["sleep"]

Then I build it by running the following:

docker build . -t testimg

This will create a container that everytime you run it sleeps. So If I run it as following:

docker run testimg

I'll get the following:

sleep: missing operand
Try 'sleep --help' for more information.

This happens because the entry point is the "sleep" command which needs an argument. So to fix this I'll just provide the amount to sleep:

docker run testimg 5

This will run correctly and as consequence the container will run, sleeps 5 seconds and exits. As we can see in this example docker just appended what goes after the image name to the entry point binary docker run testimg <my_cmd>. What happens if we want to pass a default value (default argument) to the entry point? in this case we just need to specify it in the CMD section, for example:

From ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]

In this case if the user doesn't pass any argument the container will use the default value (10) and pass it to entry point sleep.

Now let's use just CMD and omit ENTRYPOINT definition:

FROM ubuntu
CMD ["sleep", "5"]

If we rebuild and run this image it will basically sleeps for 5 seconds.

So in summary, you can use ENTRYPOINT in order to make your container acts as an executable. You can use CMD to provide default arguments to your entry point or to run a custom command when starting your container that can be overridden from outside by user.

C# naming convention for constants?

Actually, it is

private const int TheAnswer = 42;

At least if you look at the .NET library, which IMO is the best way to decide naming conventions - so your code doesn't look out of place.

Why is an OPTIONS request sent and can I disable it?

One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com

Configure an IIS rewrite from your domain to the foreign domain - e.g.

<rewrite>
  <rules>
    <rule name="ForeignRewrite" stopProcessing="true">
        <match url="^api/v1/(.*)$" />
        <action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>

on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)

CSS width of a <span> tag

Having fixed the height and width you sholud tell the how to bahave if the text inside it overflows its area. So add in the css

overflow: auto;

How to convert a List<String> into a comma separated string without iterating List explicitly

With Java 8:

String csv = String.join(",", ids);

With Java 7-, there is a dirty way (note: it works only if you don't insert strings which contain ", " in your list) - obviously, List#toString will perform a loop to create idList but it does not appear in your code:

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");

Iterating over each line of ls -l output

The read(1) utility along with output redirection of the ls(1) command will do what you want.

Javascript AES encryption

In my searches for AES encryption i found this from some Standford students. Claims to be fastest out there. Supports CCM, OCB, GCM and Block encryption. http://crypto.stanford.edu/sjcl/

Binding value to input in Angular JS

{{widget.title}} Try this it will work

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How to dump a dict to a json file?

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

Redirect and Request dispatcher are two different methods to move form one page to another. if we are using redirect to a new page actually a new request is happening from the client side itself to the new page. so we can see the change in the URL. Since redirection is a new request the old request values are not available here.

Oracle date function for the previous month

Getting last nth months data retrieve

SELECT * FROM TABLE_NAME 
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE'; 

How do I divide so I get a decimal value?

quotient = 3 / 2;
remainder = 3 % 2;

// now you have them both

How do I import a sql data file into SQL Server?

In order to import your .sql try the following steps

  1. Start SQL Server Management Studio
  2. Connect to your Database
  3. Open the Query Editor
  4. Drag and Drop your .sql File into the editor
  5. Execute the import

"End of script output before headers" error in Apache

In my case I had a similar problem but with c ++ this in windows 10, the problem was solved by adding the environment variables (path) windows, the folder of the c ++ libraries, in my case I used the codeblock libraries:

C:\codeblocks\MinGW\bin

Apply CSS to jQuery Dialog Buttons

Why not just inspect the generated markup, note the class on the button of choice and style it yourself?

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

Cannot read property 'map' of undefined

The error occur mainly becuase the array isnt found. Just check if you have mapped to the correct array. Check the array name or declaration.

Diff files present in two different directories

If you specifically don't want to compare contents of files and only check which one are not present in both of the directories, you can compare lists of files, generated by another command.

diff <(find DIR1 -printf '%P\n' | sort) <(find DIR2 -printf '%P\n' | sort) | grep '^[<>]'

-printf '%P\n' tells find to not prefix output paths with the root directory.

I've also added sort to make sure the order of files will be the same in both calls of find.

The grep at the end removes information about identical input lines.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get an object's properties in JavaScript / jQuery?

To get listing of object properties/values:

  1. In Firefox - Firebug:

    console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    

Edits:

  1. <object> in the above is to be replaced with the variable reference to the object.
  2. console.log() is to be used in the console, if you're unsure what that is, you can replace it with an alert()

Pytorch reshape tensor dimension

import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape

>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'

How to return rows from left table not found in right table?

This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.

As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.

Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

You're looking for a query such as:

DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)

INSERT INTO @table1
(
    test
)
SELECT 1
UNION ALL SELECT 2

INSERT INTO @table2
(
    test
)
SELECT 1
UNION ALL SELECT 3

-- Here's the important part
SELECT  a.*
FROM    @table1 a
LEFT    join @table2 b on a.test = b.test -- this will return all rows from a
WHERE   b.test IS null -- this then excludes that which exist in both a and b

-- Returned results:

2

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

Load and execution sequence of a web page?

1) HTML is downloaded.

2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.

3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.

4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.

Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.

Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.

How to view the list of compile errors in IntelliJ?

I think this comes closest to what you wish:

(From IntelliJ IDEA Q&A for Eclipse Users):

enter image description here

The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.

Things to do:

  1. Switch to 'Problems' view in the Project pane:

    enter image description here

  2. Enable the setting to compile the project automatically :

    enter image description here

  3. Finally, look at the Problems view:

    enter image description here

Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:

enter image description here

enter image description here

Relevant Links: The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122

How do I add indices to MySQL tables?

You can use this syntax to add an index and control the kind of index (HASH or BTREE).

create index your_index_name on your_table_name(your_column_name) using HASH;
or
create index your_index_name on your_table_name(your_column_name) using BTREE;

You can learn about differences between BTREE and HASH indexes here: http://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html

What's the difference between deadlock and livelock?

All the content and examples here are from

Operating Systems: Internals and Design Principles
William Stallings
8º Edition

Deadlock: A situation in which two or more processes are unable to proceed because each is waiting for one the others to do something.

For example, consider two processes, P1 and P2, and two resources, R1 and R2. Suppose that each process needs access to both resources to perform part of its function. Then it is possible to have the following situation: the OS assigns R1 to P2, and R2 to P1. Each process is waiting for one of the two resources. Neither will release the resource that it already owns until it has acquired the other resource and performed the function requiring both resources. The two processes are deadlocked

Livelock: A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work:

Starvation: A situation in which a runnable process is overlooked indefinitely by the scheduler; although it is able to proceed, it is never chosen.

Suppose that three processes (P1, P2, P3) each require periodic access to resource R. Consider the situation in which P1 is in possession of the resource, and both P2 and P3 are delayed, waiting for that resource. When P1 exits its critical section, either P2 or P3 should be allowed access to R. Assume that the OS grants access to P3 and that P1 again requires access before P3 completes its critical section. If the OS grants access to P1 after P3 has finished, and subsequently alternately grants access to P1 and P3, then P2 may indefinitely be denied access to the resource, even though there is no deadlock situation.

APPENDIX A - TOPICS IN CONCURRENCY

Deadlock Example

If both processes set their flags to true before either has executed the while statement, then each will think that the other has entered its critical section, causing deadlock.

/* PROCESS 0 */
flag[0] = true;            // <- get lock 0
while (flag[1])            // <- is lock 1 free?
    /* do nothing */;      // <- no? so I wait 1 second, for example
                           // and test again.
                           // on more sophisticated setups we can ask
                           // to be woken when lock 1 is freed
/* critical section*/;     // <- do what we need (this will never happen)
flag[0] = false;           // <- releasing our lock

 /* PROCESS 1 */
flag[1] = true;
while (flag[0])
    /* do nothing */;
/* critical section*/;
flag[1] = false;

Livelock Example

/* PROCESS 0 */
flag[0] = true;          // <- get lock 0
while (flag[1]){         
    flag[0] = false;     // <- instead of sleeping, we do useless work
                         //    needed by the lock mechanism
    /*delay */;          // <- wait for a second
    flag[0] = true;      // <- and restart useless work again.
}
/*critical section*/;    // <- do what we need (this will never happen)
flag[0] = false; 

/* PROCESS 1 */
flag[1] = true;
while (flag[0]) {
    flag[1] = false;
    /*delay */;
    flag[1] = true;
}
/* critical section*/;
flag[1] = false;

[...] consider the following sequence of events:

  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.
  • P0 checks flag[1].
  • P1 checks flag[0].
  • P0 sets flag[0] to false.
  • P1 sets flag[1] to false.
  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.

This sequence could be extended indefinitely, and neither process could enter its critical section. Strictly speaking, this is not deadlock, because any alteration in the relative speed of the two processes will break this cycle and allow one to enter the critical section. This condition is referred to as livelock. Recall that deadlock occurs when a set of processes wishes to enter their critical sections but no process can succeed. With livelock, there are possible sequences of executions that succeed, but it is also possible to describe one or more execution sequences in which no process ever enters its critical section.

Not content from the book anymore.

And what about spinlocks?

Spinlock is a technique to avoid the cost of the OS lock mechanism. Typically you would do:

try
{
   lock = beginLock();
   doSomething();
}
finally
{
   endLock();
}

A problem start to appear when beginLock() costs much more than doSomething(). In very exagerated terms, imagine what happens when the beginLock costs 1 second, but doSomething cost just 1 millisecond.

In this case if you waited 1 millisecond, you would avoid being hindered for 1 second.

Why the beginLock would cost so much? If the lock is free is does not cost a lot (see https://stackoverflow.com/a/49712993/5397116), but if the lock is not free the OS will "freeze" your thread, setup a mechanism to wake you when the lock is freed, and then wake you again in the future.

All of this is much more expensive than some loops checking the lock. That is why sometimes is better to do a "spinlock".

For example:

void beginSpinLock(lock)
{
   if(lock) loopFor(1 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   if(lock) loopFor(2 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   // important is that the part above never 
   // cause the thread to sleep.
   // It is "burning" the time slice of this thread.
   // Hopefully for good.

   // some implementations fallback to OS lock mechanism
   // after a few tries
   if(lock) return beginLock(lock);
   else 
   {
     lock = true;
     return;
   }
}

If your implementation is not careful, you can fall on livelock, spending all CPU on the lock mechanism.

Also see:

https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?

Summary:

Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU usage will be low;

Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and not on your calculation;

Starvation: situation where one procress never gets the chance to run; by pure bad luck or by some of its property (low priority, for example);

Spinlock: technique of avoiding the cost waiting the lock to be freed.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I had same issue got it fixed. Use below steps to resolve issue in Xcode 6.4.

  1. Click on Show project navigator in Navigator window
  2. Now Select project immediately below navigator window
  3. Select Targets
  4. Select Build Phases tab
  5. Open Run Script drop-down option
  6. Select Run script only when installing checkbox

Screenshot for steps

Now, clean your project (cmd+shift+k) and build your project.

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Hope it helps someone on earth. In my case jQuery and $ were available but not when the plugin bootstrapped so I wrapped everything inside a setTimeout. Wrapping inside setTimeout helped me fix the error:

setTimeout(() => {
    /** Your code goes here */

    !function(t, e) {

    }(window);

})

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

Placeholder Mixin SCSS/CSS

This is for shorthand syntax

=placeholder
  &::-webkit-input-placeholder
    @content
  &:-moz-placeholder
    @content
  &::-moz-placeholder
    @content
  &:-ms-input-placeholder
    @content

use it like

input
  +placeholder
    color: red

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

Find the IP address of the client in an SSH session

Search for SSH connections for "myusername" account;

Take first result string;

Take 5th column;

Split by ":" and return 1st part (port number don't needed, we want just IP):

netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'


Another way:

who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'

Textarea to resize based on content length

You can achieve this by using a span and a textarea.

You have to update the span with the text in textarea each time the text is changed. Then set the css width and height of the textarea to the span's clientWidth and clientHeight property.

Eg:

.textArea {
    border: #a9a9a9 1px solid;
    overflow: hidden;
    width:  expression( document.getElementById("spnHidden").clientWidth );
    height: expression( document.getElementById("spnHidden").clientHeight );
}