Programs & Examples On #Gtksourceview

GtkSourceView is a portable C library that extends the standard GTK+ framework.

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

How to remove package using Angular CLI?

I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes. Be careful of untracked files from .gitignore.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

Apply these two things.

  1. You need to set the character set of your database to be utf8.

  2. You need to call the mysql_set_charset('utf8') in the file where you made the connection with the database and right after the selection of database like mysql_select_db use the mysql_set_charset. That will allow you to add and retrieve data properly in whatever the language.

Restart container within pod

We use a pretty convenient command line to force re-deployment of fresh images on integration pod.
We noticed that our alpine containers all run their "sustaining" command on PID 5. Therefore, sending it a SIGTERM signal takes the container down. imagePullPolicy being set to Always has the kubelet re-pull the latest image when it brings the container back.

kubectl exec -i [pod name] -c [container-name] -- kill -15 5

How can I show dots ("...") in a span with hidden overflow?

You can try this:

_x000D_
_x000D_
.classname{_x000D_
    width:250px;_x000D_
    overflow:hidden;_x000D_
    text-overflow:ellipsis;_x000D_
}
_x000D_
_x000D_
_x000D_

How to write specific CSS for mozilla, chrome and IE

use agent detector and then with your web language create program to create css

for example in python

csscreator()
    useragent = detector()
    if useragent == "Firefox":
         css = "your css"
    ...
    return css

wget: unable to resolve host address `http'

If using Vagrant try reloading your box. This solved my issue.

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

Trigger standard HTML5 validation (form) without using submit button?

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:

$(document).ready(function()
{
    $('#theIdOfMyForm').submit(function(event){
        if(!this.checkValidity())
        {
            event.preventDefault();
        }
    });
});

Then just call $('#theIdOfMyForm').submit(); in your code.

UPDATE

If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function()
{
    if(!this.validity.valid)
    {
        $(this).focus();
        // break
        return false;
    }
});

It will give focus on the first invalid input.

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

Datatables on-the-fly resizing

$(document).ready(function() {
    $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
        // var target = $(e.target).attr("href"); // activated tab
        // alert (target);
        $($.fn.dataTable.tables( true ) ).css('width', '100%');
        $($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
    } ); 
});

It works for me, with "autoWidth": false,

Why not inherit from List<T>?

Prefer Interfaces over Classes

Classes should avoid deriving from classes and instead implement the minimal interfaces necessary.

Inheritance breaks Encapsulation

Deriving from classes breaks encapsulation:

  • exposes internal details about how your collection is implemented
  • declares an interface (set of public functions and properties) that may not be appropriate

Among other things this makes it harder to refactor your code.

Classes are an Implementation Detail

Classes are an implementation detail that should be hidden from other parts of your code. In short a System.List is a specific implementation of an abstract data type, that may or may not be appropriate now and in the future.

Conceptually the fact that the System.List data type is called "list" is a bit of a red-herring. A System.List<T> is a mutable ordered collection that supports amortized O(1) operations for adding, inserting, and removing elements, and O(1) operations for retrieving the number of elements or getting and setting element by index.

The Smaller the Interface the more Flexible the Code

When designing a data structure, the simpler the interface is, the more flexible the code is. Just look at how powerful LINQ is for a demonstration of this.

How to Choose Interfaces

When you think "list" you should start by saying to yourself, "I need to represent a collection of baseball players". So let's say you decide to model this with a class. What you should do first is decide what the minimal amount of interfaces that this class will need to expose.

Some questions that can help guide this process:

  • Do I need to have the count? If not consider implementing IEnumerable<T>
  • Is this collection going to change after it has been initialized? If not consider IReadonlyList<T>.
  • Is it important that I can access items by index? Consider ICollection<T>
  • Is the order in which I add items to the collection important? Maybe it is an ISet<T>?
  • If you indeed want these thing then go ahead and implement IList<T>.

This way you will not be coupling other parts of the code to implementation details of your baseball players collection and will be free to change how it is implemented as long as you respect the interface.

By taking this approach you will find that code becomes easier to read, refactor, and reuse.

Notes about Avoiding Boilerplate

Implementing interfaces in a modern IDE should be easy. Right click and choose "Implement Interface". Then forward all of the implementations to a member class if you need to.

That said, if you find you are writing lots of boilerplate, it is potentially because you are exposing more functions than you should be. It is the same reason you shouldn't inherit from a class.

You can also design smaller interfaces that make sense for your application, and maybe just a couple of helper extension functions to map those interfaces to any others that you need. This is the approach I took in my own IArray interface for the LinqArray library.

How do I check if the mouse is over an element in jQuery?

You can use jQuery's mouseenter and mouseleave events. You can set a flag when the mouse enters the desired area and unset the flag when it leaves the area.

Flutter plugin not installed error;. When running flutter doctor

The best way to install it on Windows 

Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.18363.959], locale en-US)
[v] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[v] Android Studio (version 4.0)
[v] VS Code (version 1.47.3)
[!] Connected device
    ! No devices available

1- Open Android Studio File->Settings->Plugins and Make Sure You have Flutter and Dart Installed enter image description here

2- Go to VSCode to Extensions and install Flutter and Dart Extension

enter image description here

Hope It Solved the problem

How to set Google Chrome in WebDriver

public void setUp() throws Exception {

 System.setProperty("webdriver.chrome.driver","Absolute path of Chrome driver");

 driver =new ChromeDriver();
 baseUrl = "URL/";

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

Return a value if no rows are found in Microsoft tSQL

I liked James Jenkins reply with the ISNULL check, but I think he meant IFNULL. ISNULL does not have a second parameter like his syntax, but IFNULL has the second parameter after the expression being checked to substitute if a NULL is found.

Android - Set text to TextView

PUT THIS CODE IN YOUR XML FILE

<TextView
    android:id="@+id/textview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

PUT THIS CODE IN YOUR JAVA FILE

// Declaring components like TextView globally is a good habit

TextView mTextView = (TextView) findViewById(R.id.textview1);

// Put this in OnCreate

mTextView.setText("Welcome to Dynamic TextView");

Homebrew install specific version of formula?

I decided, against my better judgment, to create a formula for Maven 3.1.1, which homebrew/versions did not have. To do this:

  1. I forked homebrew/versions on github.
  2. I symlinked from $(brew --prefix)/Library/Taps to the local working copy of my fork. I'll call this my-homebrew/versions.
  3. I tested by specifying the formula as my-homebrew/versions/<formula>.
  4. I sent a pull request to homebrew/versions for my new formula.

Yay.

Set specific precision of a BigDecimal

You can use setScale() e.g.

double d = ...
BigDecimal db = new BigDecimal(d).setScale(12, BigDecimal.ROUND_HALF_UP);

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

what is the difference between ajax and jquery and which one is better?

Ajax is a way of using Javascript for communicating with serverside without loading the page over again. jQuery uses ajax for many of its functions, but it nothing else than a library that provides easier functionality.

With jQuery you dont have to think about creating xml objects ect ect, everything is done for you, but with straight up javascript ajax you need to program every single step of the ajax call.

How to unlock a file from someone else in Team Foundation Server

Based on stackptr answer I've created batch file UnlockOther.bat

@rem from https://stackoverflow.com/questions/3451637/how-to-unlock-a-file-from-someone-else-in-team-foundation-server
@rem tf undo {file path} /workspace:{workspace};{username

call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
@echo on
tf undo $/MyTfsProject/path/fileName.ext /workspace:CollegeMachine;CollegueName /login:MyLogin 
@pause

Self-references in object literals / initializers

I use the following code as alternative, and it works. And the variable can be array too. (@ Fausto R.)

var foo = {
  a: 5,
  b: 6,
  c: function() {
    return this.a + this.b;
  },

  d: [10,20,30],
  e: function(x) {
    this.d.push(x);
    return this.d;
  }
};
foo.c(); // 11
foo.e(40); // foo.d = [10,20,30,40]

sys.argv[1] meaning in script

sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

Getting last day of the month in a given string date

I use this one-liner on my JasperServer Reports:

new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)

Doesn't look nice but works for me. Basically it's adding 1 to the current month, get the first day of that month and subtract one day.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I believe James Hunt's answer will solve the problem.

@user3731784: In your new message, the compiler seems to be confused because of the "C:\Program Files\IAR systems\Embedded Workbench 7.0\430\lib\dlib\d1430fn.h" argument. Why are you giving this header file at the middle of other compiler switches? Please correct this and try again. Also, it probably is a good idea to give the source file name after all the compiler switches and not at the beginning.

Parse JSON response using jQuery

Try bellow code. This is help your code.

  $("#btnUpdate").on("click", function () {
            //alert("Alert Test");
            var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
            $.ajax({
                type: "GET",
                url: url,
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    debugger;

                    $.each(result.callback, function (index, value) {
                        alert(index + ': ' + value.Name);
                    });
                },
                failure: function (result) { alert('Fail'); }
            });
        });

I could not access your url. Bellow error is shows

XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.

How do I send a POST request with PHP?

I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query). The data is encoded using application/x-www-form-urlencoded.

function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward mentions that http_build_query may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, but be advised that in this case the data will be encoded using multipart/form-data.

I use this function with APIs that expect data to be encoded using application/x-www-form-urlencoded. That's why I use http_build_query().

Django model "doesn't declare an explicit app_label"

as a noob using Python3 ,I find it might be an import error instead of a Django error

wrong:

from someModule import someClass

right:

from .someModule import someClass

this happens a few days ago but I really can't reproduce it...I think only people new to Django may encounter this.here's what I remember:

try to register a model in admin.py:

from django.contrib import admin
from user import User
admin.site.register(User)

try to run server, error looks like this

some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

change user to .user ,problem solved

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

Sublime Text 2 - View whitespace characters

I use Unicode Character Highlighter, can show whitespaces and some other special characters.

Add this by, Package Control

Install packages, unicode ...

How to disable a button when an input is empty?

Using constants allows to combine multiple fields for verification:

_x000D_
_x000D_
class LoginFrm extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = {_x000D_
      email: '',_x000D_
      password: '',_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  handleEmailChange = (evt) => {_x000D_
    this.setState({ email: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handlePasswordChange = (evt) => {_x000D_
    this.setState({ password: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handleSubmit = () => {_x000D_
    const { email, password } = this.state;_x000D_
    alert(`Welcome ${email} password: ${password}`);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { email, password } = this.state;_x000D_
    const enabled =_x000D_
          email.length > 0 &&_x000D_
          password.length > 0;_x000D_
    return (_x000D_
      <form onSubmit={this.handleSubmit}>_x000D_
        <input_x000D_
          type="text"_x000D_
          placeholder="Email"_x000D_
          value={this.state.email}_x000D_
          onChange={this.handleEmailChange}_x000D_
        />_x000D_
        _x000D_
        <input_x000D_
          type="password"_x000D_
          placeholder="Password"_x000D_
          value={this.state.password}_x000D_
          onChange={this.handlePasswordChange}_x000D_
        />_x000D_
        <button disabled={!enabled}>Login</button>_x000D_
      </form>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

detect key press in python?

So I made this ..kind of game.. based on this post (using msvcr library and Python 3.7).

The following is the "main function" of the game, that is detecting the keys pressed:

# Requiered libraries - - - -
import msvcrt
# - - - - - - - - - - - - - -


def _secret_key(self):
    # Get the key pressed by the user and check if he/she wins.

    bk = chr(10) + "-"*25 + chr(10)

    while True:

        print(bk + "Press any key(s)" + bk)
        #asks the user to type any key(s)

        kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
        # Store key's value.

        if r'\xe0' in kp:
            kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
            # Refactor the variable in case of multi press.

        if kp == r'\xe0\x8a':
            # If user pressed the secret key, the game ends.
            # \x8a is CTRL+F12, that's the secret key.

            print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
            print("Press any key to exit the game")
            msvcrt.getch()
            break
        else:
            print("    You pressed:'", kp + "', that's not the secret key(s)\n")
            if self.select_continue() == "n":
                if self.secondary_options():
                    self._main_menu()
                break

If you want the full source code of the porgram you can see it or download it from here:

The Secret Key Game (GitHub)

(note: the secret keypress is: Ctrl+F12)

I hope you can serve as an example and help for those who come to consult this information.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I had similar problem with the data frame:

group time weight.loss
1 Control  wl1    4.500000
2    Diet  wl1    5.333333
3  DietEx  wl1    6.200000
4 Control  wl2    3.333333
5    Diet  wl2    3.916667
6  DietEx  wl2    6.100000
7 Control  wl3    2.083333
8    Diet  wl3    2.250000
9  DietEx  wl3    2.200000

I think the variable for x axis should be numeric, so that geom_line knows how to connect the points to draw the line.

after I change the 2nd column to numeric:

 group time weight.loss
1 Control    1    4.500000
2    Diet    1    5.333333
3  DietEx    1    6.200000
4 Control    2    3.333333
5    Diet    2    3.916667
6  DietEx    2    6.100000
7 Control    3    2.083333
8    Diet    3    2.250000
9  DietEx    3    2.200000

then it works.

Installing J2EE into existing eclipse IDE

Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..

Can't draw Histogram, 'x' must be numeric

Note that you could as well plot directly from ce (after the comma removing) using the column name :

hist(ce$Weight)

(As opposed to using hist(ce[1]), which would lead to the same "must be numeric" error.)

This also works for a database query result.

append new row to old csv file python

If the file exists and contains data, then it is possible to generate the fieldname parameter for csv.DictWriter automatically:

# read header automatically
with open(myFile, "r") as f:
    reader = csv.reader(f)
    for header in reader:
        break

# add row to CSV file
with open(myFile, "a", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writerow(myDict)

Converting String Array to an Integer Array

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

How to center content in a bootstrap column?

Bootstrap naming conventions carry styles of their own, col-XS-1 refers to a column being 8.33% of the containing element wide. Your text, would most likely expand far beyond the specified width, and couldn't possible be centered within it. If you wanted it to constrain to the div, you could use something like css word-break.

For centering the content within an element large enough to expand beyond the text, you have two options.

Option 1: HTML Center Tag

<div class="row">
  <div class="col-xs-1 center-block">
    <center>
      <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
    </center>
  </div>
</div>

Option 2: CSS Text-Align

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

If you wanted everything to constrain to the width of the column

<div class="row">
  <div class="col-xs-1 center-block" style="text-align:center;word-break:break-all;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

UPDATE - Using Bootstrap's text-center class

<div class="row">
  <div class="col-xs-1 center-block text-center">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

FlexBox Method

<div class="row">
  <div class="flexBox" style="
    display: flex;
    flex-flow: row wrap;
    justify-content: center;">
    <span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
  </div>
</div>

http://jsfiddle.net/usth0kd2/13/

MySQL - SELECT * INTO OUTFILE LOCAL ?

Using mysql CLI with -e option as Waverly360 suggests is a good one, but that might go out of memory and get killed on large results. (Havent find the reason behind it). If that is the case, and you need all records, my solution is: mysqldump + mysqldump2csv:

wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
mysqldump -u username -p --host=hostname database table | python mysqldump_to_csv.py > table.csv

Powershell command to hide user from exchange address lists

You can use the following script, just replace DOMAIN with the name of your domain. When executed it will prompt you for a userlogin then hide that user's account from the address lists.

$name=Read-Host "Enter login name of user to hide"
Set-Mailbox -Identity DOMAIN\$name -HiddenFromAddressListsEnabled $true

Brian.

OS X Framework Library not loaded: 'Image not found'

open xcode -> general -> Embedded Binaries -> add QBImagepicker.framework and RSKImageCropper -> clean project

just add QBImagePicker.framework and RSKImageCropper.framework at embedded binaries worked for me

Disable submit button on form submit

Simple and effective solution is

<form ... onsubmit="myButton.disabled = true; return true;">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Source: here

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

Download a single folder or directory from a GitHub repo

I work with CentOS 7 servers on which I don't have root access, nor git, svn, etc (nor want to!) so made a python script to download any github folder: https://github.com/andrrrl/github-folder-downloader

Usage is simple, just copy the relevant part from a github project, let's say the project is https://github.com/MaxCDN/php-maxcdn/, and you want a folder where some source files are only, then you need to do something like:

$ python gdownload.py "/MaxCDN/php-maxcdn/tree/master/src" /my/target/dir/
(will create target folder if doesn't exist)

It requires lxml library, can be installed with easy_install lxml
If you don't have root access (like me) you can create a .pydistutils.py file into your $HOME dir with these contents: [install] user=1 And easy_install lxml will just work (ref: https://stackoverflow.com/a/33464597/591257).

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

  1. @SpringBootApplication: checked, didn't work.
  2. spring-boot-starter-web in Pom file: checked, didn't work.
  3. Switch from IntelliJ CE to IntelliJ Ultimate, problem solved.

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

"continue" in cursor.forEach()

In my opinion the best approach to achieve this by using the filter method as it's meaningless to return in a forEach block; for an example on your snippet:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

This will narrow down your elementsCollection and just keep the filtred elements that should be processed.

Can I create links with 'target="_blank"' in Markdown?

As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.

<a href="http://example.com/" target="_blank">Hello, world!</a>

Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.

If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.

Priority queue in .Net

here's one i just wrote, maybe it's not as optimized (just uses a sorted dictionary) but simple to understand. you can insert objects of different kinds, so no generic queues.

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;

namespace PrioQueue
{
    public class PrioQueue
    {
        int total_size;
        SortedDictionary<int, Queue> storage;

        public PrioQueue ()
        {
            this.storage = new SortedDictionary<int, Queue> ();
            this.total_size = 0;
        }

        public bool IsEmpty ()
        {
            return (total_size == 0);
        }

        public object Dequeue ()
        {
            if (IsEmpty ()) {
                throw new Exception ("Please check that priorityQueue is not empty before dequeing");
            } else
                foreach (Queue q in storage.Values) {
                    // we use a sorted dictionary
                    if (q.Count > 0) {
                        total_size--;
                        return q.Dequeue ();
                    }
                }

                Debug.Assert(false,"not supposed to reach here. problem with changing total_size");

                return null; // not supposed to reach here.
        }

        // same as above, except for peek.

        public object Peek ()
        {
            if (IsEmpty ())
                throw new Exception ("Please check that priorityQueue is not empty before peeking");
            else
                foreach (Queue q in storage.Values) {
                    if (q.Count > 0)
                        return q.Peek ();
                }

                Debug.Assert(false,"not supposed to reach here. problem with changing total_size");

                return null; // not supposed to reach here.
        }

        public object Dequeue (int prio)
        {
            total_size--;
            return storage[prio].Dequeue ();
        }

        public void Enqueue (object item, int prio)
        {
            if (!storage.ContainsKey (prio)) {
                storage.Add (prio, new Queue ());
              }
            storage[prio].Enqueue (item);
            total_size++;

        }
    }
}

What are the differences between LDAP and Active Directory?

Active Directory is a super-set of the LDAP protocol. Depending on how the organization uses Active Directory, your LDAP search/set queries may or may not work.

grant remote access of MySQL database from any IP address

In website panels like cPanel you may add a single % (percentage sign) in allowed hostnames to access your MySQL database.

By adding a single % you can access your database from any IP or website even from desktop applications.

Git 'fatal: Unable to write new index file'

did you try 'git add .' . will it all the changes? (you can remove unnecessary added files by git reset HEAD )

How to Scroll Down - JQuery

If you want to scroll down to the div (id="div1"). Then you can use this code.

 $('html, body').animate({
     scrollTop: $("#div1").offset().top
 }, 1500);

Are HTTPS URLs encrypted?

Entire request and response is encrypted, including URL.

Note that when you use a HTTP Proxy, it knows the address (domain) of the target server, but doesn't know the requested path on this server (i.e. request and response are always encrypted).

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

Getting the class name from a static method in Java

So, we have a situation when we need to statically get class object or a class full/simple name without an explicit usage of MyClass.class syntax.

It can be really handy in some cases, e.g. logger instance for the upper-level functions (in this case kotlin creates a static Java class not accessible from the kotlin code).

We have a few different variants for getting this info:

  1. new Object(){}.getClass().getEnclosingClass();
    noted by Tom Hawtin - tackline

  2. getClassContext()[0].getName(); from the SecurityManager
    noted by Christoffer

  3. new Throwable().getStackTrace()[0].getClassName();
    by count ludwig

  4. Thread.currentThread().getStackTrace()[1].getClassName();
    from Keksi

  5. and finally awesome
    MethodHandles.lookup().lookupClass();
    from Rein


I've prepared a benchmark for all variants and results are:

# Run complete. Total time: 00:04:18

Benchmark                                                      Mode  Cnt      Score     Error  Units
StaticClassLookup.MethodHandles_lookup_lookupClass             avgt   30      3.630 ±   0.024  ns/op
StaticClassLookup.AnonymousObject_getClass_enclosingClass      avgt   30    282.486 ±   1.980  ns/op
StaticClassLookup.SecurityManager_classContext_1               avgt   30    680.385 ±  21.665  ns/op
StaticClassLookup.Thread_currentThread_stackTrace_1_className  avgt   30  11179.460 ± 286.293  ns/op
StaticClassLookup.Throwable_stackTrace_0_className             avgt   30  10221.209 ± 176.847  ns/op


Conclusions

  1. Best variant to use, rather clean and monstrously fast.
    Available only since Java 7 and Android API 26!
 MethodHandles.lookup().lookupClass();
  1. In case you need this functionality for Android or Java 6, you can use the second best variant. It's rather fast too, but creates an anonymous class in each place of usage :(
 new Object(){}.getClass().getEnclosingClass();
  1. If you need it in many places and don't want your bytecode to bloat due to tons of anonymous classes – SecurityManager is your friend (third best option).

    But you can't just call getClassContext() – it's protected in the SecurityManager class. You will need some helper class like this:

 // Helper class
 public final class CallerClassGetter extends SecurityManager
 {
    private static final CallerClassGetter INSTANCE = new CallerClassGetter();
    private CallerClassGetter() {}

    public static Class<?> getCallerClass() {
        return INSTANCE.getClassContext()[1];
    }
 }

 // Usage example:
 class FooBar
 {
    static final Logger LOGGER = LoggerFactory.getLogger(CallerClassGetter.getCallerClass())
 }
  1. You probably don't ever need to use last two variants based on the getStackTrace() from exception or the Thread.currentThread(). Very inefficient and can return only the class name as a String, not the Class<*> instance.


P.S.

If you want to create a logger instance for static kotlin utils (like me :), you can use this helper:

import org.slf4j.Logger
import org.slf4j.LoggerFactory

// Should be inlined to get an actual class instead of the one where this helper declared
// Will work only since Java 7 and Android API 26!
@Suppress("NOTHING_TO_INLINE")
inline fun loggerFactoryStatic(): Logger
    = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass())

Usage example:

private val LOGGER = loggerFactoryStatic()

/**
 * Returns a pseudo-random, uniformly distributed value between the
 * given least value (inclusive) and bound (exclusive).
 *
 * @param min the least value returned
 * @param max the upper bound (exclusive)
 *
 * @return the next value
 * @throws IllegalArgumentException if least greater than or equal to bound
 * @see java.util.concurrent.ThreadLocalRandom.nextDouble(double, double)
 */
fun Random.nextDouble(min: Double = .0, max: Double = 1.0): Double {
    if (min >= max) {
        if (min == max) return max
        LOGGER.warn("nextDouble: min $min > max $max")
        return min
    }
    return nextDouble() * (max - min) + min
}

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

How do I compare two DateTime objects in PHP 5.2.8?

If you want to compare dates and not time, you could use this:

$d1->format("Y-m-d") == $d2->format("Y-m-d")

How to set tbody height with overflow scroll

Another approach is to wrap your table in a scrollable element and set the header cells to stick to the top.

The advantage of this approach is that you don't have to change the display on tbody and you can leave it to the browser to calculate column width while keeping the header cell widths in line with the data cell column widths.

_x000D_
_x000D_
/* Set a fixed scrollable wrapper */_x000D_
.tableWrap {_x000D_
  height: 200px;_x000D_
  border: 2px solid black;_x000D_
  overflow: auto;_x000D_
}_x000D_
/* Set header to stick to the top of the container. */_x000D_
thead tr th {_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
/* If we use border,_x000D_
we must use table-collapse to avoid_x000D_
a slight movement of the header row */_x000D_
table {_x000D_
 border-collapse: collapse;_x000D_
}_x000D_
_x000D_
/* Because we must set sticky on th,_x000D_
 we have to apply background styles here_x000D_
 rather than on thead */_x000D_
th {_x000D_
  padding: 16px;_x000D_
  padding-left: 15px;_x000D_
  border-left: 1px dotted rgba(200, 209, 224, 0.6);_x000D_
  border-bottom: 1px solid #e8e8e8;_x000D_
  background: #ffc491;_x000D_
  text-align: left;_x000D_
  /* With border-collapse, we must use box-shadow or psuedo elements_x000D_
  for the header borders */_x000D_
  box-shadow: 0px 0px 0 2px #e8e8e8;_x000D_
}_x000D_
_x000D_
/* Basic Demo styling */_x000D_
table {_x000D_
  width: 100%;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
table td {_x000D_
  padding: 16px;_x000D_
}_x000D_
tbody tr {_x000D_
  border-bottom: 2px solid #e8e8e8;_x000D_
}_x000D_
thead {_x000D_
  font-weight: 500;_x000D_
  color: rgba(0, 0, 0, 0.85);_x000D_
}_x000D_
tbody tr:hover {_x000D_
  background: #e6f7ff;_x000D_
}
_x000D_
<div class="tableWrap">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th><span>Month</span></th>_x000D_
        <th>_x000D_
          <span>Event</span>_x000D_
        </th>_x000D_
        <th><span>Action</span></th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>January</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>February. An extra long string.</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>March</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>April</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>May</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>June</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>July</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>August</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>September</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>October</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>November</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>December</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to parse this string in Java?

If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.

This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

How to use underscore.js as a template engine?

In it's simplest form you would use it like:

var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'   

If you're going to be using a template a few times you'll want to compile it so it's faster:

var template = _.template('<li><%= name %></li>');

var html = [];
for (var key in names) {
    html += template({ name: names[i] });
}

console.log(html.join('')); //Outputs a string of <li> items

I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

var template = _.template('<li>{{ name }}</li>');

How to validate array in Laravel?

I have this array as my request data from a HTML+Vue.js data grid/table:

[0] => Array
    (
        [item_id] => 1
        [item_no] => 3123
        [size] => 3e
    )
[1] => Array
    (
        [item_id] => 2
        [item_no] => 7688
        [size] => 5b
    )

And use this to validate which works properly:

$this->validate($request, [
    '*.item_id' => 'required|integer',
    '*.item_no' => 'required|integer',
    '*.size'    => 'required|max:191',
]);

Why doesn't Java support unsigned ints?

The reason IMHO is because they are/were too lazy to implement/correct that mistake. Suggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.

Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)

when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.

A good example here would be trying to use an unsigned byte as a self rotating loop. For those of you who do not understand the last sentence, how on earth you call yourself a programmer.

DC

How do I make a semi transparent background?

div.main{
     width:100%;
     height:550px;
     background: url('https://images.unsplash.com/photo-1503135935062-
     b7d1f5a0690f?ixlib=rb-enter code here0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=cf4d0c234ecaecd14f51a2343cc89b6c&dpr=1&auto=format&fit=crop&w=376&h=564&q=60&cs=tinysrgb') no-repeat;
     background-position:center;
     background-size:cover 
}
 div.main>div{
     width:100px;
     height:320px;
     background:transparent;
     background-attachment:fixed;
     border-top:25px solid orange;
     border-left:120px solid orange;
     border-bottom:25px solid orange;
     border-right:10px solid orange;
     margin-left:150px 
}

enter image description here

Responsive iframe using Bootstrap

Option 3

To update current iframe

$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');

Download file through an ajax call php

I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.

Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.

Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:

$('iframe_dl').src="/app?download=1&filename=" + the_filename

Server slurps the file, unlinks it, and sends the stream to the client, with these headers:

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

Works like a charm.

Show tables, describe tables equivalent in redshift

You can use - desc / to see the view/table definition in Redshift. I have been using Workbench/J as a SQL client for Redshift and it gives the definition in the Messages tab adjacent to Result tab.

Disable browser's back button

This question is very similar to this one...

You need to force the cache to expire for this to work. Place the following code on your page code behind.

Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)

What is the difference between res.end() and res.send()?

res.send() will send the HTTP response. Its syntax is,

res.send([body])

The body parameter can be a Buffer object, a String, an object, or an Array. For example:

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

See this for more info.

res.end() will end the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. It is used to quickly end the response without any data. For example:

res.end();
res.status(404).end();

Read this for more info.

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

Changing cell color using apache poi

To create your cell styles see: http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

Custom colors

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();

//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

 XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell( 0);
    cell.setCellValue("custom XSSF colors");

    XSSFCellStyle style1 = wb.createCellStyle();
    style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
    style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

What is the difference between Class.getResource() and ClassLoader.getResource()?

Class.getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

So the following are basically equivalent:

foo.bar.Baz.class.getResource("xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("foo/bar/xyz.txt");

And so are these (but they're different from the above):

foo.bar.Baz.class.getResource("/data/xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("data/xyz.txt");

How to workaround 'FB is not defined'?

<script>  
    window.fbAsyncInit = function() {    
        FB.init({      
            appId      :'your-app-id',      
            xfbml      :true,      
            version    :'v2.1'
        });
    };
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if(d.getElementById(id)) {
            return;
        }     
        js = d.createElement(s); 
        js.id = id;     
        js.src ="// connect.facebook.net/en_US /sdk.js";     
        fjs.parentNode.insertBefore(js, fjs);
    }
    (document,'script','facebook-jssdk'));
</script> 

From the documentation: The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML tha

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

Order a List (C#) by many fields?

Use ThenBy:

var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)

See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx

Is there a way to break a list into columns?

If you are looking for a solution that works in IE as well, you could float the list elements to the left. However, this will result in a list that snakes around, like this:

item 1 | item 2 | item 3
item 4 | item 5

Instead of neat columns, like:

item 1 | item 4
item 2 | 
item 3 | 

The code to do that would be:

ul li {
  width:10em;
  float:left;
}

You could add a border-bottom to the lis to make the flow of the items from left to right more apparent.

How to check if a value is not null and not empty string in JS

If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:

if(data !== null && data !== '') {
   // do something
}

Notice that I changed your code to check for type equality (!==|===).

If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:

if (data) {
  // do something
}

Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).

The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.

How to force the input date format to dd/mm/yyyy?

No such thing. the input type=date will pick up whatever your system default is and show that in the GUI but will always store the value in ISO format (yyyy-mm-dd). Beside be aware that not all browsers support this so it's not a good idea to depend on this input type yet.

If this is a corporate issue, force all the computer to use local regional format (dd-mm-yyyy) and your UI will show it in this format (see wufoo link before after changing your regional settings, you need to reopen the browser).

Your best bet is still to use JavaScript based component that will allow you to customize this to whatever you wish.

How to split a single column values to multiple column values?

What you need is a split user-defined function. With that, the solution looks like

With SplitValues As
    (
    Select T.Name, Z.Position, Z.Value
        , Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
    From Table As T
        Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
    )
Select Name
    , FirstName.Value
    , Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
    Left Join SplitValues As SecondName
        On S2.Name = S1.Name
            And S2.Num = 2
    Left Join SplitValues As ThirdName
        On S2.Name = S1.Name
            And S2.Num = 3
Where FirstName.Num = 1

Here's a sample split function:

Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

S3 limit to objects in a bucket

There are no limits to the number of objects you can store in your S3 bucket. AWS claims it to have unlimited storage. However, there are some limitations -

  1. By default, customers can provision up to 100 buckets per AWS account. However, you can increase your Amazon S3 bucket limit by visiting AWS Service Limits.
  2. An object can be 0 bytes to 5TB.
  3. The largest object that can be uploaded in a single PUT is 5 gigabytes
  4. For objects larger than 100 megabytes, customers should consider using the Multipart Upload capability.

That being said if you really have a lot of objects to be stored in S3 bucket consider randomizing your object name prefix to improve performance.

When your workload is a mix of request types, introduce some randomness to key names by adding a hash string as a prefix to the key name. By introducing randomness to your key names the I/O load will be distributed across multiple index partitions. For example, you can compute an MD5 hash of the character sequence that you plan to assign as the key and add 3 or 4 characters from the hash as a prefix to the key name.

More details - https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-performance-improve/

-- As of June 2018

How to log Apache CXF Soap Request and Soap Response using Log4j?

You need to create a file named org.apache.cxf.Logger (that is: org.apache.cxf file with Logger extension) under /META-INF/cxf/ with the following contents:

org.apache.cxf.common.logging.Log4jLogger

Reference: Using Log4j Instead of java.util.logging.

Also if you replace standard:

<cxf:bus>
  <cxf:features>
    <cxf:logging/>
  </cxf:features>
</cxf:bus>

with much more verbose:

<bean id="abstractLoggingInterceptor" abstract="true">
    <property name="prettyLogging" value="true"/>
</bean>
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" parent="abstractLoggingInterceptor"/>
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" parent="abstractLoggingInterceptor"/>

<cxf:bus>
    <cxf:inInterceptors>
        <ref bean="loggingInInterceptor"/>
    </cxf:inInterceptors>
    <cxf:outInterceptors>
        <ref bean="loggingOutInterceptor"/>
    </cxf:outInterceptors>
    <cxf:outFaultInterceptors>
        <ref bean="loggingOutInterceptor"/>
    </cxf:outFaultInterceptors>
    <cxf:inFaultInterceptors>
        <ref bean="loggingInInterceptor"/>
    </cxf:inFaultInterceptors>
</cxf:bus>

Apache CXF will pretty print XML messages formatting them with proper indentation and line breaks. Very useful. More about it here.

How to remove all event handlers from an event

Sometimes we have to work with ThirdParty controls and we need to build these awkward solutions. Based in @Anoop Muraleedharan answer I created this solution with inference type and ToolStripItem support

    public static void RemoveItemEvents<T>(this T target, string eventName) 
        where T : ToolStripItem
    {            
        RemoveObjectEvents<T>(target, eventName);
    }

    public static void RemoveControlEvents<T>(this T target, string eventName)
        where T : Control
    {
        RemoveObjectEvents<T>(target, eventName);
    }

    private static void RemoveObjectEvents<T>(T target, string Event) where T : class
    {
        var typeOfT = typeof(T);
        var fieldInfo = typeOfT.BaseType.GetField(
            Event, BindingFlags.Static | BindingFlags.NonPublic);
        var provertyValue = fieldInfo.GetValue(target);
        var propertyInfo = typeOfT.GetProperty(
            "Events", BindingFlags.NonPublic | BindingFlags.Instance);
        var eventHandlerList = (EventHandlerList)propertyInfo.GetValue(target, null);
        eventHandlerList.RemoveHandler(provertyValue, eventHandlerList[provertyValue]);
    }

And you can use it like this

    var toolStripButton = new ToolStripButton();
    toolStripButton.RemoveItemEvents("EventClick");

    var button = new Button();
    button.RemoveControlEvents("EventClick");

How to calculate number of days between two given dates?

You want the datetime module.

>>> from datetime import datetime, timedelta 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

Another example:

>>> import datetime 
>>> today = datetime.date.today() 
>>> print(today)
2008-09-01 
>>> last_year = datetime.date(2007, 9, 1) 
>>> print(today - last_year)
366 days, 0:00:00 

As pointed out here

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

How do I check whether a file exists without exceptions?

This is the simplest way to check if a file exists. Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.

import os
fname = "foo.txt"
if os.path.isfile(fname):
    print("file does exist at this time")
else:
    print("no such file exists at this time")

Install / upgrade gradle on Mac OS X

Another alternative is to use sdkman. An advantage of sdkman over brew is that many versions of gradle are supported. (brew only supports the latest version and 2.14.) To install sdkman execute:

curl -s "https://get.sdkman.io" | bash

Then follow the instructions. Go here for more installation information. Once sdkman is installed use the command:

sdk install gradle

Or to install a specific version:

sdk install gradle 2.2

Or use to use a specific installed version:

sdk use gradle 2.2

To see which versions are installed and available:

sdk list gradle

For more information go here.

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

How can I get the first two digits of a number?

You can convert your number to string and use list slicing like this:

int(str(number)[:2])

Output:

>>> number = 1520
>>> int(str(number)[:2])
15

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

Can't start Eclipse - Java was started but returned exit code=13

In "Path" variable removed "C:\ProgramData\Oracle\Java\javapath" and replaced it with "C:\Program Files\Java\jdk1.8.0_212\bin"

It worked for me.

Windows could not start the Apache2 on Local Computer - problem

if appache and IIS both are running at a time then there is a posibility to hang the apache service,,,,

when i stopped all IIS websites once and then restarted apache service and it works for me....Jai...

How to tar certain file types in all subdirectories?

This will handle paths with spaces:

find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +

Printing Even and Odd using two Threads in Java

package programs.multithreading;

public class PrintOddEvenNoInSequence {

final int upto;
final PrintOddEvenNoInSequence obj;
volatile boolean oddFlag,evenFlag;
public PrintOddEvenNoInSequence(int upto){
    this.upto = upto;
    obj = this;
    oddFlag = true;
    evenFlag = false;
}
void printInSequence(){

    Thread odd = new Thread(new Runnable() {
        @Override
        public void run() {
            for(int i = 1; i <= upto; i = i + 2){
                synchronized (obj) {
                    while(!oddFlag){
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Odd:"+i);
                    oddFlag = false;
                    evenFlag = true;
                    obj.notify();
                }
            }
        }
    });

    Thread even = new Thread(new Runnable() {
        @Override
        public void run() {
            for(int i = 2; i <= upto; i = i + 2){
                synchronized (obj) {
                    while(!evenFlag){
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("Even:"+i);
                    oddFlag = true;
                    evenFlag = false;
                    obj.notify();
                }
            }
        }
    });

    odd.start();
    even.start();

}
public static void main(String[] args) {
    new PrintOddEvenNoInSequence(100).printInSequence();
}
}

Spring,Request method 'POST' not supported

In Jsp:

action="profile/proffiesional"

In Controller

@RequestMapping(value = "proffessional", method = RequestMethod.POST)

Spelling MisMatch !

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

Email Address Validation for ASP.NET

Preventing XSS is a different issue from validating input.

Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.

Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".

How do you switch pages in Xamarin.Forms?

Push a new page onto the stack, then remove the current page. This results in a switch.

item.Tapped += async (sender, e) => {
    await Navigation.PushAsync (new SecondPage ());
    Navigation.RemovePage(this);
};

You need to be in a Navigation Page first:

MainPage = NavigationPage(new FirstPage());

Switching content isn't ideal as you have just one big page and one set of page events like OnAppearing ect.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to access site through IP address when website is on a shared host?

You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul

What is the simplest method of inter-process communication between 2 C# processes?

There's also MSMQ (Microsoft Message Queueing) which can operate across networks as well as on a local computer. Although there are better ways to communicate it's worth looking into: https://msdn.microsoft.com/en-us/library/ms711472(v=vs.85).aspx

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

How to delete duplicates on a MySQL table?

Suppose you have a table employee, with the following columns:

employee (first_name, last_name, start_date)

In order to delete the rows with a duplicate first_name column:

delete
from employee using employee,
    employee e1
where employee.id > e1.id
    and employee.first_name = e1.first_name  

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

Might not be exactly what the OP was looking for, but this page is where I found myself after looking for the problem, so sharing this for everyone with similar issue :)

Stack's fit property did the trick for my needs. Otherwise Image inside (OctoImageIn my case) was padded and providing other Image.fit values did not give any effect.

Stack(
  fit: StackFit.expand, 
  children: [
    Image(
      image: provider,
      fit: BoxFit.cover,
    ),
    // other irrelevent children here
  ]
);

How to filter a dictionary according to an arbitrary condition function?

>>> points = {'a': (3, 4), 'c': (5, 5), 'b': (1, 2), 'd': (3, 3)}
>>> dict(filter(lambda x: (x[1][0], x[1][1]) < (5, 5), points.items()))

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

Bash ignoring error for a particular command

I kind of like this solution :

: `particular_script`

The command/script between the back ticks is executed and its output is fed to the command ":" (which is the equivalent of "true")

$ false
$ echo $?
1
$ : `false`
$ echo $?
0

edit: Fixed ugly typo

Where can I set environment variables that crontab will use?

Unfortunately, crontabs have a very limited environment variables scope, thus you need to export them every time the corntab runs.

An easy approach would be the following example, suppose you've your env vars in a file called env, then:

* * * * * . ./env && /path/to_your/command

this part . ./env will export them and then they're used within the same scope of your command

How to stick text to the bottom of the page?

Try:

.bottom {
    position: fixed;
    bottom: 0;
}

Toggle button using two image on different state

AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:

<ToggleButton 
    android:id="@+id/toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/check"   //check.xml
    android:background="@null"/>

check.xml:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
          android:state_checked="false"/>
    </selector>

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Reflection generic get field value

I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).

The simplified code I'm using:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();

    Class<?> thisClass = null;
    try {
        thisClass = Class.forName(this.getClass().getName());

        Field[] aClassFields = thisClass.getDeclaredFields();
        sb.append(this.getClass().getSimpleName() + " [ ");
        for(Field f : aClassFields){
            String fName = f.getName();
            sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
        }
        sb.append("]");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sb.toString();
}

I hope that it will help someone, because I also have searched.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Consideration must also be given to your individual FPM pools, if any.

I couldn't figure out why none of these answers was working for me today. This had been a set-and-forget scenario for me, where I had forgotten that listen.user and listen.group were duplicated on a per-pool basis.

If you used pools for different user accounts like I did, where each user account owns their FPM processes and sockets, setting only the default listen.owner and listen.group configuration options to 'nginx' will simply not work. And obviously, letting 'nginx' own them all is not acceptable either.

For each pool, make sure that

listen.group = nginx

Otherwise, you can leave the pool's ownership and such alone.

Why calling react setState method doesn't mutate the state immediately?

From React's documentation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
});

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

IN-clause in HQL or Java Persistence Query Language

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

Change a Rails application to production

RAILS_ENV=production rails s

OR

rails s -e production

By default environment is developement.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I solved this converting the JSP from XHTML to HTML, doing this in the begining:

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
...

What are the differences between Deferred, Promise and Future in JavaScript?

These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).

Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then. 7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

    Example from CommonJS:

    > asyncComputeTheAnswerToEverything()
        .then(addTwo)
        .then(printResult);
    44
    

     

    Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4

    Always present in popular implementations, and never given resolution abilites. 5 6 7

  • Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9

    However, at least one library uses the term generically for abstracting synchronicity and error handling, while not providing then functionality. 10 It's unclear if avoiding the term 'promise' was intentional, but probably a good choice since promises are built around 'thenables.' 2

References

  1. Wikipedia on Promises & Futures
  2. Promises/A+ spec
  3. DOM Standard on Promises
  4. DOM Standard Promises Spec WIP
  5. DOJO Toolkit Deferreds
  6. jQuery Deferreds
  7. Q
  8. FutureJS
  9. Functional Javascript section on Promises
  10. Futures in AngularJS Integration Testing

Misc potentially confusing things

Creating a static class with no instances

You could use a classmethod or staticmethod

class Paul(object):
    elems = []

    @classmethod
    def addelem(cls, e):
        cls.elems.append(e)

    @staticmethod
    def addelem2(e):
        Paul.elems.append(e)

Paul.addelem(1)
Paul.addelem2(2)

print(Paul.elems)

classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

module is certainly best though.

Where is Android Studio layout preview?

Several people seem to have the same problem. The issue is that the IDE only displays the preview if editing a layout file in the res/layout* directory of an Android project.

In particular, it won't show if editing a file in build/res/layout* since those are not source directory but output directory. In your case, you are editing a file in the build/ directory...

The Resource folder is set automatically, and can be viewed (and changed) in Project Structure > Modules > [Module name] > Android > Resources directory.

Execute SQLite script

You want to feed the create.sql into sqlite3 from the shell, not from inside SQLite itself:

$ sqlite3 auction.db < create.sql

SQLite's version of SQL doesn't understand < for files, your shell does.

html script src="" triggering redirection with button

I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.

How do I store the select column in a variable?

Assuming such a query would return a single row, you could use either

select @EmpId = Id from dbo.Employee

Or

set @EmpId = (select Id from dbo.Employee)

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

Enter export password to generate a P12 certificate

OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.

You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword to pass the password YourPassword from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.

Initial size for the ArrayList

This might help someone -

ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));

Visual Studio "Could not copy" .... during build

Follow the below steps

  1. Open Task Manager ( Ctrl + Alt + Delete )
  2. Under Performance tab select select <ProjectNameOfYours.exe>.
  3. Click on End Process.
  4. Now Build solution.

Above steps resolved error permanently :)

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

Get a list of all git commits, including the 'lost' ones

Not particularly easily- if you've lost the pointer to the tip of a branch, it's rather like finding a needle in a haystack. You can find all the commits that don't appear to be referenced any more- git fsck --unreachable will do this for you- but that will include commits that you threw away after a git commit --amend, old commits on branches that you rebased etc etc. So seeing all these commits at once is quite likely far too much information to wade through.

So the flippant answer is, don't lose track of things you're interested in. More seriously, the reflogs will hold references to all the commits you've used for the last 60 days or so by default. More importantly, they will give some context about what those commits are.

Parse JSON in JavaScript?

If you like

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

you can access the JSON elements by JsonObject with (.) dot:

JsonObject.result;
JsonObject.count;

How to stop an animation (cancel() does not work)

If you are using the animation listener, set v.setAnimationListener(null). Use the following code with all options.

v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

How do I make an HTML button not reload the page

there is no need to js or jquery. to stop page reloading just specify the button type as 'button'. if you dont specify the button type, browser will set it to 'reset' or 'submit' witch cause to page reload.

 <button type='button'>submit</button> 

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

I am using version 4.0.6 ( the current release) on Linux Mint. You need to install Mongodb Compass(mongodb GUI) to interact with your databases. Here is the link: https://docs.mongodb.com/compass/master/install/

I hope this solves your problem.

DTO pattern: Best way to copy properties between two objects

I suggest you should use one of the mappers' libraries: Mapstruct, ModelMapper, etc. With Mapstruct your mapper will look like:

@Mapper
public interface UserMapper {     
    UserMapper INSTANCE = Mappers.getMapper( UserMapper.class ); 

    UserDTO toDto(User user);
}

The real object with all getters and setters will be automatically generated from this interface. You can use it like:

UserDTO userDTO = UserMapper.INSTANCE.toDto(user);

You can also add some logic for your activeText filed using @AfterMapping annotation.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

ASP.NET MVC1 -> MVC3

string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");

ASP.NET MVC4

string path = Server.MapPath("~/App_Data/somedata.xml");


MSDN Reference:

HttpServerUtility.MapPath Method

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

Most efficient conversion of ResultSet to JSON?

If anyone plan to use this implementation, You might wanna check this out and this

This is my version of that convertion code:

public class ResultSetConverter {
public static JSONArray convert(ResultSet rs) throws SQLException,
        JSONException {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    while (rs.next()) {

        JSONObject obj = new JSONObject();

        for (int i = 1; i < numColumns + 1; i++) {
            String column_name = rsmd.getColumnName(i);

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                obj.put(column_name, rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                obj.put(column_name, rs.getLong(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
                obj.put(column_name, rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                obj.put(column_name, rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                obj.put(column_name, rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                obj.put(column_name, rs.getByte(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                obj.put(column_name, rs.getShort(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                obj.put(column_name, rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                obj.put(column_name, rs.getTime(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                obj.put(column_name, rs.getTimestamp(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
                obj.put(column_name, rs.getBinaryStream(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
                obj.put(column_name, rs.getClob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
                obj.put(column_name, rs.getURL(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
                obj.put(column_name, rs.getRef(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
                obj.put(column_name, rs.getObject(column_name));
            } else {
                obj.put(column_name, rs.getString(i));
            }
        }

        json.put(obj);
    }

    return json;
}
}

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

EL access a map value by Integer key

Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:

<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>

How to percent-encode URL parameters in Python?

It is better to use urlencode here. Not much difference for single parameter but IMHO makes the code clearer. (It looks confusing to see a function quote_plus! especially those coming from other languates)

In [21]: query='lskdfj/sdfkjdf/ksdfj skfj'

In [22]: val=34

In [23]: from urllib.parse import urlencode

In [24]: encoded = urlencode(dict(p=query,val=val))

In [25]: print(f"http://example.com?{encoded}")
http://example.com?p=lskdfj%2Fsdfkjdf%2Fksdfj+skfj&val=34

Docs

urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode

quote_plus: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

got the below error

PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to https://registry.npmjs.org/vue failed, reason: unable to get local issuer certificate

npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log

Below command solved the issue:

npm config set strict-ssl false

SQL Query to add a new column after an existing column in SQL Server 2005

It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.

A better query would be:

SELECT 
 COLUMN_NAME, 
 Case 
  When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary') 
  Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)  
  When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint') 
  Then convert(varchar(MAX), NUMERIC_PRECISION) 
  When DATA_TYPE = 'bit' 
  Then convert(varchar(MAX), 1)
  When DATA_TYPE IN ('decimal', 'float') 
  Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE)) 
  When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp') 
  Then '' 
 End As DATALEN, 
 DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
Where 
 TABLE_NAME = ''

POST Multipart Form Data using Retrofit 2.0 including image

Uploading Files using Retrofit is Quite Simple You need to build your api interface as

public interface Api {

    String BASE_URL = "http://192.168.43.124/ImageUploadApi/";


    @Multipart
    @POST("yourapipath")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}

in the above code image is the key name so if you are using php you will write $_FILES['image']['tmp_name'] to get this. And filename="myfile.jpg" is the name of your file that is being sent with the request.

Now to upload the file you need a method that will give you the absolute path from the Uri.

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Images.Media.DATA};
    CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

Now you can use the below code to upload your file.

 private void uploadFile(Uri fileUri, String desc) {

        //creating a file
        File file = new File(getRealPathFromURI(fileUri));

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api 
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method 
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call 
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

For more detailed explanation you can visit this Retrofit Upload File Tutorial.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

overflow-y : scroll;
overflow-x : hidden;

height is optional

SQL Server database backup restore on lower version

Here are my 2 cents on different options for completing this:

Third party tools: Probably the easiest way to get the job done is to create an empty database on lower version and then use third party tools to read the backup and synchronize new newly created database with the backup.

Red gate is one of the most popular but there are many others like ApexSQL Diff , ApexSQL Data Diff, Adept SQL, Idera …. All of these are premium tools but you can get the job done in trial mode ;)

Generating scripts: as others already mentioned you can always script structure and data using SSMS but you need to take into consideration the order of execution. By default object scripts are not ordered correctly and you’ll have to take care of the dependencies. This may be an issue if database is big and has a lot of objects.

Import and export wizard: This is not an ideal solution as it will not restore all objects but only data tables but you can consider it for quick and dirty fixes when it’s needed.

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

What's the fastest way to convert String to Number in JavaScript?

There are at least 5 ways to do this:

If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):

e.g.

~~x;

Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/

The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/

var values = ["123",
          undefined,
          "not a number",
          "123.45",
          "1234 error",
          "2147483648",
          "4999999999"
          ];

for (var i = 0; i < values.length; i++){
    var x = values[i];

    console.log(x);
    console.log(" Number(x) = " + Number(x));
    console.log(" parseInt(x, 10) = " + parseInt(x, 10));
    console.log(" parseFloat(x) = " + parseFloat(x));
    console.log(" +x = " + +x);
    console.log(" ~~x = " + ~~x);
}

Debug console:

123
  Number(x) = 123
  parseInt(x, 10) = 123
  parseFloat(x) = 123
  +x = 123
  ~~x = 123
undefined
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
null
  Number(x) = 0
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = 0
  ~~x = 0
"not a number"
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
123.45
  Number(x) = 123.45
  parseInt(x, 10) = 123
  parseFloat(x) = 123.45
  +x = 123.45
  ~~x = 123
1234 error
  Number(x) = NaN
  parseInt(x, 10) = 1234
  parseFloat(x) = 1234
  +x = NaN
  ~~x = 0
2147483648
  Number(x) = 2147483648
  parseInt(x, 10) = 2147483648
  parseFloat(x) = 2147483648
  +x = 2147483648
  ~~x = -2147483648
4999999999
  Number(x) = 4999999999
  parseInt(x, 10) = 4999999999
  parseFloat(x) = 4999999999
  +x = 4999999999
  ~~x = 705032703

The ~~x version results in a number in "more" cases, where others often result in undefined, but it fails for invalid input (e.g. it will return 0 if the string contains non-number characters after a valid number).

Overflow

Please note: Integer overflow and/or bit truncation can occur with ~~, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.

Some Perf tests indicate that the standard parseInt and parseFloat functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37

This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.

My theory is:

  • Lies
  • Darn lines
  • Statistics
  • JSPerf results :)

Can a JSON value contain a multiline string

Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.

Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

I haven't done web design for iOS but from what I recall seeing in the WWDC sessions and in documentation, the search bar in Mobile Safari, and navigation bars across the OS, will now automatically resize and shrink to show more of your content.

You can test this in Safari on an iPhone and notice that, when you scroll down to see more contents on a page, the navigation/search bar is hidden automatically.

Perhaps leaving the address bar/navigation bar as is, and not creating a full-screen experience, is what's best. I don't see Apple doing that anytime soon. And at most they are not automatically controlling when the address bar shows/hides.

Sure, you are losing screen real estate, specially on an iPhone 4 or 4S, but there doesn't seem to be an alternative as of Beta 4.

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

Adding options to select with javascript

You could achieve this with a simple for loop:

var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

JS Fiddle demo.

JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.


Edited in response to comment from OP:

[How] do [I] apply this to more than one element?

function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

JS Fiddle demo.

And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

JS Fiddle demo.

References:

How to get div height to auto-adjust to background size?

You can do something like that

<div style="background-image: url(http://your-image.jpg); position:relative;">
 <img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>

Async await in linq select

Existing code is working, but is blocking the thread.

.Select(async ev => await ProcessEventAsync(ev))

creates a new Task for every event, but

.Select(t => t.Result)

blocks the thread waiting for each new task to end.

In the other hand your code produce the same result but keeps asynchronous.

Just one comment on your first code. This line

var tasks = await Task.WhenAll(events...

will produce a single Task<TResult[]> so the variable should be named in singular.

Finally your last code make the same but is more succinct.

For reference: Task.Wait / Task.WhenAll

What is the proper way to format a multi-line dict in Python?

First of all, like Steven Rumbalski said, "PEP8 doesn't address this question", so it is a matter of personal preference.

I would use a similar but not identical format as your format 3. Here is mine, and why.

my_dictionary = { # Don't think dict(...) notation has more readability
    "key1": 1, # Indent by one press of TAB (i.e. 4 spaces)
    "key2": 2, # Same indentation scale as above
    "key3": 3, # Keep this final comma, so that future addition won't show up as 2-lines change in code diff
    } # My favorite: SAME indentation AS ABOVE, to emphasize this bracket is still part of the above code block!
the_next_line_of_code() # Otherwise the previous line would look like the begin of this part of code

bad_example = {
               "foo": "bar", # Don't do this. Unnecessary indentation wastes screen space
               "hello": "world" # Don't do this. Omitting the comma is not good.
} # You see? This line visually "joins" the next line when in a glance
the_next_line_of_code()

btw_this_is_a_function_with_long_name_or_with_lots_of_parameters(
    foo='hello world',  # So I put one parameter per line
    bar=123,  # And yeah, this extra comma here is harmless too;
              # I bet not many people knew/tried this.
              # Oh did I just show you how to write
              # multiple-line inline comment here?
              # Basically, same indentation forms a natural paragraph.
    ) # Indentation here. Same idea as the long dict case.
the_next_line_of_code()

# By the way, now you see how I prefer inline comment to document the very line.
# I think this inline style is more compact.
# Otherwise you will need extra blank line to split the comment and its code from others.

some_normal_code()

# hi this function is blah blah
some_code_need_extra_explanation()

some_normal_code()

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Fatal error: Call to undefined function: ldap_connect()

Add path of your PHP to Windows System Path. The path should contain php.exe.

After adding the path open a new command prompt and make sure php.exe is in path by typing

C:\>php --help

Once you see proper help message from above, enable the php_ldap.dll extension in php.ini

Also copy php_ldap.dll from php/ext directory to apache/bin folder

Restart wamp and phpinfo() will now show ldap enabled.

Reverse HashMap keys and values in Java

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

How should I do integer division in Perl?

you can:

use integer;

it is explained by Michael Ratanapintha or else use manually:

$a=3.7;
$b=2.1;

$c=int(int($a)/int($b));

notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.

Stop floating divs from wrapping

The only way I've managed to do this is by using overflow: visible; and width: 20000px; on the parent element. There is no way to do this with CSS level 1 that I'm aware of and I refused to think I'd have to go all gung-ho with CSS level 3. The example below has 18 menus that extend beyond my 1920x1200 resolution LCD, if your screen is larger just duplicate the first tier menu elements or just resize the browser. Alternatively and with slightly lower levels of browser compatibility you could use CSS3 media queries.

Here is a full copy/paste example demonstration...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML5 Menu Demonstration</title>
<style type="text/css">
* {border: 0; box-sizing: content-box; color: #f0f; font-size: 10px; margin: 0; padding: 0; transition-property: background-color, background-image, border, box-shadow, color, float, opacity, text-align, text-shadow; transition-duration: 0.5s; white-space: nowrap;}
a:link {color: #79b; text-decoration: none;}
a:visited {color: #579;}
a:focus, a:hover {color: #fff; text-decoration: underline;}
body {background-color: #444; overflow-x: hidden;}
body > header {background-color: #000; height: 64px; left: 0; position: absolute; right: 0; z-index: 2;}
body > header > nav {height: 32px; margin-left: 16px;}
body > header > nav a {font-size: 24px;}
main {border-color: transparent; border-style: solid; border-width: 64px 0 0; bottom: 0px; left: 0; overflow-x: hidden !important; overflow-y: auto; position: absolute; right: 0; top: 0; z-index: 1;}
main > * > * {background-color: #000;}
main > section {float: left; margin-top: 16px; width: 100%;}
nav[id='menu'] {overflow: visible; width: 20000px;}
nav[id='menu'] > ul {height: 32px;}
nav[id='menu'] > ul > li {float: left; width: 140px;}
nav[id='menu'] > ul > li > ul {background-color: rgba(0, 0, 0, 0.8); display: none; margin-left: -50px; width: 240px;}
nav[id='menu'] a {display: block; height: 32px; line-height: 32px; text-align: center; white-space: nowrap;}
nav[id='menu'] > ul {float: left; list-style:none;}
nav[id='menu'] ul li:hover ul {display: block;}
p, p *, span, span * {color: #fff;}
p {font-size: 20px; margin: 0 14px 0 14px; padding-bottom: 14px; text-indent: 1.5em;}
.hidden {display: none;}
.width_100 {width: 100%;}
</style>
</head>

<body>

<main>
<section style="height: 2000px;"><p>Hover the first menu at the top-left.</p></section>
</main>

<header>
<nav id="location"><a href="">Example</a><span> - </span><a href="">Blog</a><span> - </span><a href="">Browser Market Share</a></nav>
<nav id="menu">
<ul>
<li><a href="" tabindex="2">Menu 1 - Hover</a>
<ul>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
</ul>
</li>
<li><a href="" tabindex="2">Menu 2</a></li>
<li><a href="" tabindex="2">Menu 3</a></li>
<li><a href="" tabindex="2">Menu 4</a></li>
<li><a href="" tabindex="2">Menu 5</a></li>
<li><a href="" tabindex="2">Menu 6</a></li>
<li><a href="" tabindex="2">Menu 7</a></li>
<li><a href="" tabindex="2">Menu 8</a></li>
<li><a href="" tabindex="2">Menu 9</a></li>
<li><a href="" tabindex="2">Menu 10</a></li>
<li><a href="" tabindex="2">Menu 11</a></li>
<li><a href="" tabindex="2">Menu 12</a></li>
<li><a href="" tabindex="2">Menu 13</a></li>
<li><a href="" tabindex="2">Menu 14</a></li>
<li><a href="" tabindex="2">Menu 15</a></li>
<li><a href="" tabindex="2">Menu 16</a></li>
<li><a href="" tabindex="2">Menu 17</a></li>
<li><a href="" tabindex="2">Menu 18</a></li>
</ul>
</nav>
</header>

</body>
</html>

Visual Studio 2010 - recommended extensions

If you are a Vim aficionado...

VsVim - free
ViEmu - not free (also not yet released)

How to split a dos path into its components in Python

You can recursively os.path.split the string

import os
def parts(path):
    p,f = os.path.split(path)
    return parts(p) + [f] if f else [p]

Testing this against some path strings, and reassembling the path with os.path.join

>>> for path in [
...         r'd:\stuff\morestuff\furtherdown\THEFILE.txt',
...         '/path/to/file.txt',
...         'relative/path/to/file.txt',
...         r'C:\path\to\file.txt',
...         r'\\host\share\path\to\file.txt',
...     ]:
...     print parts(path), os.path.join(*parts(path))
... 
['d:\\', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt'] d:\stuff\morestuff\furtherdown\THEFILE.txt
['/', 'path', 'to', 'file.txt'] /path\to\file.txt
['', 'relative', 'path', 'to', 'file.txt'] relative\path\to\file.txt
['C:\\', 'path', 'to', 'file.txt'] C:\path\to\file.txt
['\\\\', 'host', 'share', 'path', 'to', 'file.txt'] \\host\share\path\to\file.txt

The first element of the list may need to be treated differently depending on how you want to deal with drive letters, UNC paths and absolute and relative paths. Changing the last [p] to [os.path.splitdrive(p)] forces the issue by splitting the drive letter and directory root out into a tuple.

import os
def parts(path):
    p,f = os.path.split(path)
    return parts(p) + [f] if f else [os.path.splitdrive(p)]

[('d:', '\\'), 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']
[('', '/'), 'path', 'to', 'file.txt']
[('', ''), 'relative', 'path', 'to', 'file.txt']
[('C:', '\\'), 'path', 'to', 'file.txt']
[('', '\\\\'), 'host', 'share', 'path', 'to', 'file.txt']

Edit: I have realised that this answer is very similar to that given above by user1556435. I'm leaving my answer up as the handling of the drive component of the path is different.

How to change the sender's name or e-mail address in mutt?

100% Working!

To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,

export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html

File: body_html.html

<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>

Note: Tested in RHEL, CentOS, Ubuntu.

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the class URLEncoder:

URLEncoder.encode(String s, String enc)

Where :

s - String to be translated.

enc - The name of a supported character encoding.

Standard charsets:

US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1

UTF-8 Eight-bit UCS Transformation Format

UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order

UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order

UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

Example:

import java.net.URLEncoder;

String stringEncoded = URLEncoder.encode(
    "This text must be encoded! aeiou áéíóú ñ, peace!", "UTF-8");

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

How can I profile C++ code running on Linux?

Also worth mentioning are

  1. HPCToolkit (http://hpctoolkit.org/) - Open-source, works for parallel programs and has a GUI with which to look at the results multiple ways
  2. Intel VTune (https://software.intel.com/en-us/vtune) - If you have intel compilers this is very good
  3. TAU (http://www.cs.uoregon.edu/research/tau/home.php)

I have used HPCToolkit and VTune and they are very effective at finding the long pole in the tent and do not need your code to be recompiled (except that you have to use -g -O or RelWithDebInfo type build in CMake to get meaningful output). I have heard TAU is similar in capabilities.

How can building a heap be O(n) time complexity?

Lets suppose you have N elements in a heap. Then its height would be Log(N)

Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.

Now you are having N+1 elements & height = Log(N+1)

Using induction technique it can be proved that the complexity of insertion would be ?logi.

Now using

log a + log b = log ab

This simplifies to : ?logi=log(n!)

which is actually O(NlogN)

But

we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.

This realization came to me after a detail though & experimentation on Heaps.

Sending the bearer token with axios

You can create config once and use it everywhere.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'Authorization': 'Bearer '+token}
});

instance.get('/path')
.then(response => {
    return response.data;
})

how to send multiple data with $.ajax() jquery

Change var data = 'id='+ id & 'name='+ name; as below,

use this instead.....

var data = "id="+ id + "&name=" + name;

this will going to work fine:)

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

How to change the Title of the window in Qt?

For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui files.

Initially I tried to use ui->setWindowTitle, but that doesn't exist. ui is not a QDialog or a QMainWindow.

The owner of the ui is the QDialog or QMainWindow, the .ui just describes how to lay it out. In that case, you would use:

this->setWindowTitle("New Title");

I hope this helps someone else.

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

Error while inserting date - Incorrect date value:

I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.

My error message:

Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.

Is there any way to configure multiple registries in a single npmrc file

I use Strongloop's cli tools for that; see https://strongloop.com/strongblog/switch-between-configure-public-and-private-npm-registry/ for more information

Switching between repositories is as easy as : slc registry use <name>

How to temporarily exit Vim and go back

You can also do that by :sus to fall into shell and back by fg.

Find records from one table which don't exist in another

The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.

SELECT * FROM Call WHERE 
NOT EXISTS (SELECT 'x' FROM Phone_book where 
Phone_book.phone_number = Call.phone_number)

Delete all files in directory (but not directory) - one liner solution

Java 8 Stream

This deletes only files from ABC (sub-directories are untouched):

Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);

This deletes only files from ABC (and sub-directories):

Files.walk(Paths.get("C:/test/ABC/"))
                .filter(Files::isRegularFile)
                .map(Path::toFile)
                .forEach(File::delete);

^ This version requires handling the IOException

Evaluating a mathematical expression in a string

This is a massively late reply, but I think useful for future reference. Rather than write your own math parser (although the pyparsing example above is great) you could use SymPy. I don't have a lot of experience with it, but it contains a much more powerful math engine than anyone is likely to write for a specific application and the basic expression evaluation is very easy:

>>> import sympy
>>> x, y, z = sympy.symbols('x y z')
>>> sympy.sympify("x**3 + sin(y)").evalf(subs={x:1, y:-3})
0.858879991940133

Very cool indeed! A from sympy import * brings in a lot more function support, such as trig functions, special functions, etc., but I've avoided that here to show what's coming from where.

Path to MSBuild

add vswhere branch for https://github.com/linqpadless/LinqPadless/blob/master/build.cmd, works fine in my computer, and the vswhere branch works on my mate's computer. May be, the vswhere branch should move forward as the first check.

@echo off
setlocal
if "%PROCESSOR_ARCHITECTURE%"=="x86" set PROGRAMS=%ProgramFiles%
if defined ProgramFiles(x86) set PROGRAMS=%ProgramFiles(x86)%
for %%e in (Community Professional Enterprise) do (
    if exist "%PROGRAMS%\Microsoft Visual Studio\2017\%%e\MSBuild\15.0\Bin\MSBuild.exe" (
        set "MSBUILD=%PROGRAMS%\Microsoft Visual Studio\2017\%%e\MSBuild\15.0\Bin\MSBuild.exe"
    )
)
if exist "%MSBUILD%" goto :build

for /f "usebackq tokens=1* delims=: " %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -requires Microsoft.Component.MSBuild`) do (
  if /i "%%i"=="installationPath" set InstallDir=%%j
)

if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" (
  set "MSBUILD=%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe"
)
if exist "%MSBUILD%" goto :build
set MSBUILD=
for %%i in (MSBuild.exe) do set MSBUILD=%%~dpnx$PATH:i
if not defined MSBUILD goto :nomsbuild
set MSBUILD_VERSION_MAJOR=
set MSBUILD_VERSION_MINOR=
for /f "delims=. tokens=1,2,3,4" %%m in ('msbuild /version /nologo') do (
    set MSBUILD_VERSION_MAJOR=%%m
    set MSBUILD_VERSION_MINOR=%%n
)
echo %MSBUILD_VERSION_MAJOR% %MSBUILD_VERSION_MINOR%
if not defined MSBUILD_VERSION_MAJOR goto :nomsbuild
if not defined MSBUILD_VERSION_MINOR goto :nomsbuild
if %MSBUILD_VERSION_MAJOR% lss 15    goto :nomsbuild
if %MSBUILD_VERSION_MINOR% lss 1     goto :nomsbuild
:restore
for %%i in (NuGet.exe) do set nuget=%%~dpnx$PATH:i
if "%nuget%"=="" (
    echo WARNING! NuGet executable not found in PATH so build may fail!
    echo For more on NuGet, see https://github.com/nuget/home
)
pushd "%~dp0"
popd
goto :EOF

:build
setlocal
"%MSBUILD%" -restore -maxcpucount %1 /p:Configuration=%2 /v:m %3 %4 %5 %6 %7 %8 %9
goto :EOF

:nomsbuild
echo Microsoft Build version 15.1 (or later) does not appear to be
echo installed on this machine, which is required to build the solution.
exit /b 1

How do you synchronise projects to GitHub with Android Studio?

For existing project end existing repository with files:

git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories

How can I wrap text in a label using WPF?

We need to put some kind of control that can wrap text like textblock/textbox

 <Label Width="120" Height="100" >
        <TextBlock TextWrapping="Wrap">
            this is a very long text inside a textblock and this needs to be on multiline.
        </TextBlock>
    </Label>

Pass path with spaces as parameter to bat file

Use "%~1". %~1 alone removes surrounding quotes. However since you can't know whether the input parameter %1 has quotes or not, you should ensure by "%~1" that they are added for sure. This is especially helpful when concatenating variables, e.g. convert.exe "%~1.input" "%~1.output"

Installing SetupTools on 64-bit Windows

Apparently (having faced related 64- and 32-bit issues on OS X) there is a bug in the Windows installer. I stumbled across this workaround, which might help - basically, you create your own registry value HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath and copy over the InstallPath value from HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath. See the answer below for more details.

If you do this, beware that setuptools may only install 32-bit libraries.

NOTE: the responses below offer more detail, so please read them too.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.

JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.

Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.

EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.

EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!

Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...

EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...

Windows path in Python

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"

I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.

"C:\\meshes\\as.jpg"

Default SQL Server Port

The default port 1433 is used when there is only one SQL Server named instance running on the computer.

When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.

https://docs.microsoft.com/en-us/sql/sql-server/install/configure-the-windows-firewall-to-allow-sql-server-access