Programs & Examples On #Wcf interoperability

What's the difference between TRUNCATE and DELETE in SQL

Truncate can also be Rollbacked here the exapmle

begin Tran
delete from  Employee

select * from Employee
Rollback
select * from Employee

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

my suggestion: Choose a different version. I had the same problem you have deinstalled v5.6.11, downloaded and installed v5.6.3, works fine for me.

cheers!

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

How to place a JButton at a desired location in a JFrame using Java

You should set layout first by syntax pnlButton.setLayout(), and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));. And then, take that JButton into JPanel.

How to URL encode a string in Ruby

If you want to "encode" a full URL without having to think about manually splitting it into its different parts, I found the following worked in the same way that I used to use URI.encode:

URI.parse(my_url).to_s

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

How do I get the information from a meta tag with JavaScript?

One liner here

document.querySelector("meta[property='og:image']").getAttribute("content");

Output an Image in PHP

<?php

header("Content-Type: $type");
readfile($file);

That's the short version. There's a few extra little things you can do to make things nicer, but that'll work for you.

How to change ViewPager's page?

for switch to another page, try with this code:

viewPager.postDelayed(new Runnable()
{
    @Override
    public void run()
    {
        viewPager.setCurrentItem(num, true);
    }
}, 100);

How to remove an app with active device admin enabled on Android?

For Redmi users,

Settings -> Password & security -> Privacy -> Special app access -> Device admin apps

Click the deactivate the apps

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Excel VBA Run Time Error '424' object required

Simply remove the .value from your code.

Set envFrmwrkPath = ActiveSheet.Range("D6").Value

instead of this, use:

Set envFrmwrkPath = ActiveSheet.Range("D6")

What is the first character in the sort order used by Windows Explorer?

If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:

Behavior of this function, and therefore the results it returns, can change from release to release. ...

Create a Cumulative Sum Column in MySQL

select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;

Get selected item value from Bootstrap DropDown with specific ID

Try this code

<input type="TextBox" ID="yearBox" border="0" disabled>

$('#yearSelected li').on('click', function(){
                $('#yearBox').val($(this).text());
            });



<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
          <ul class="dropdown-menu">
            <li>
              <ul class="menu" id="yearSelected">
                <li><a href="#">2014-2015</a></li>
                <li><a href="#">2015-2016</a></li>
                <li><a href="#">2016-2017</a></li>
                <li><a href="#">2017-2018</a></li>

              </ul>
            </li>
          </ul>

its work for me

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I had the same problem due to ghost processes that didn't show up when using top in bash. This prevented the JVM to spawn more threads.

For me, it resolved when listing all java processes with jps (just execute jps in your shell) and killed them separately using the kill -9 pid bash command for each ghost process.

This might help in some scenarios.

How do I get the path of a process in Unix / Linux

You can also get the path on GNU/Linux with (not thoroughly tested):

char file[32];
char buf[64];
pid_t pid = getpid();
sprintf(file, "/proc/%i/cmdline", pid);
FILE *f = fopen(file, "r");
fgets(buf, 64, f);
fclose(f);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

*strrchr(buf, '/') = '\0';
/*chdir(buf);*/

Unmarshaling nested JSON objects

Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?

No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

How do I capture response of form.submit

You need to be using AJAX. Submitting the form usually results in the browser loading a new page.

Linux: is there a read or recv from socket with timeout?

// works also after bind operation for WINDOWS

DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

How SID is different from Service name in Oracle tnsnames.ora

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

Git merge without auto commit

I prefer this way so I don't need to remember any rare parameters.

git merge branch_name

It will then say your branch is ahead by "#" commits, you can now pop these commits off and put them into the working changes with the following:

git reset @~#

For example if after the merge it is 1 commit ahead, use:

git reset @~1

Note: On Windows, quotes are needed. (As Josh noted in comments) eg:

git reset "@~1"

Redirecting to URL in Flask

I believe that this question deserves an updated. Just compare with other approaches.

Here's how you do redirection (3xx) from one url to another in Flask (0.12.2):

#!/usr/bin/env python

from flask import Flask, redirect

app = Flask(__name__)

@app.route("/")
def index():
    return redirect('/you_were_redirected')

@app.route("/you_were_redirected")
def redirected():
    return "You were redirected. Congrats :)!"

if __name__ == "__main__":
    app.run(host="0.0.0.0",port=8000,debug=True)

For other official references, here.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);

  private void SumOFEPFWages(GridView grd)
    {
        Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
        /*Sum of the total Amount of the day*/
        foreach (GridViewRow gvr in grd.Rows)
        {
            Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
            lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
        }

    }

Convert a JSON String to a HashMap

You can use Jackson API as well for this :

    final String json = "....your json...";
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(
        Map.class, String.class, Object.class);
    final Map<String, Object> data = mapper.readValue(json, type);

How to add items to array in nodejs

Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.

You can download from (https://npmjs.org/package/underscore)

$ npm install underscore

Here is small snippet to demonstrate how you can do it.

var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
    newArray = [];

_.each(calendars, function (item, index) {
    newArray.push(item);
});

console.log(newArray);

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

How to use the read command in Bash?

Other bash alternatives that do not involve a subshell:

read str <<END             # here-doc
hello
END

read str <<< "hello"       # here-string

read str < <(echo hello)   # process substitution

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

presentViewController and displaying navigation bar

Swift 3

        let vc0 : ViewController1 = ViewController1()
        let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
        self.present(vc2, animated: true, completion: nil)

How to efficiently concatenate strings in go

Expanding on cd1's answer: You might use append() instead of copy(). append() makes ever bigger advance provisions, costing a little more memory, but saving time. I added two more benchmarks at the top of yours. Run locally with

go test -bench=. -benchtime=100ms

On my thinkpad T400s it yields:

BenchmarkAppendEmpty    50000000         5.0 ns/op
BenchmarkAppendPrealloc 50000000         3.5 ns/op
BenchmarkCopy           20000000        10.2 ns/op

Fastest check if row exists in PostgreSQL

select true from tablename where condition limit 1;

I believe that this is the query that postgres uses for checking foreign keys.

In your case, you could do this in one go too:

insert into yourtable select $userid, $rightid, $count where not (select true from yourtable where userid = $userid limit 1);

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
   .AddSeconds(-DateTime.Now.Second);

Output will be like:

07/29/2015 00:00:00

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

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

You only have to add group = 1 into the ggplot or geom_line aes().

For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.

Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.

Try this:

plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
         geom_point() +
         geom_line() +
         labs(x = "Year", y = "Particulate matter emissions (tons)", 
              title = "Motor vehicle emissions in Baltimore")

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

Bootstrap 3 with remote Modal

For Bootstrap 3

The workflow I had to deal with was loading content with a url context that could change. So by default setup your modal with javascript or the href for the default context you want to show :

$('#myModal').modal({
        show: false,
        remote: 'some/context'
});

Destroying the modal wouldn't work for me because I wasn't loading from the same remote, thus I had to :

$(".some-action-class").on('click', function () {
        $('#myModal').removeData('bs.modal');
        $('#myModal').modal({remote: 'some/new/context?p=' + $(this).attr('buttonAttr') });
        $('#myModal').modal('show');
});

This of course was easily refactored into a js library and gives you a lot of flexibility with loading modals

I hope this saves someone 15 minutes of tinkering.

Sending mass email using PHP

Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.

How do I connect to mongodb with node.js (and authenticate)?

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

   var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
    assert = require('assert');

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
    if(err){
        console.log("Auth Failed");
        return;
    }
    console.log("Connected");
    db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
        docs.each(function(err, doc) {
          if(doc) {
            console.log(doc['_id']);
          }
        });
    });

    db.close();

}); 

"The given path's format is not supported."

If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:

var localPath = (new Uri(urlStylePath)).AbsolutePath

In general, using the provided API is best practice.

How can I insert vertical blank space into an html document?

Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html

<style>
  .bottom-three {
     margin-bottom: 3cm;
  }
</style>


<p class="bottom-three">
   This is the first question?
</p>
<p class="bottom-three">
   This is the second question?
</p>

How to declare a structure in a header that is to be used by multiple files in c?

if this structure is to be used by some other file func.c how to do it?

When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.

The right way is putting it in an header file, and include this header file whenever needed.

shall we open a new header file and declare the structure there and include that header in the func.c?

This is the solution I like more, because it makes the code highly modular. I would code your struct as:

#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME

struct a
{ 
    int i;
    struct b
    {
        int j;
    }
};

#endif

I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").

And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.

If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:

struct a ;

Will be enough, and it decreases coupling.

or can we define the total structure in header file and include that in both source.c and func.c?

This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.

In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.

then how to declare that structure as extern in both the files. ?

I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.

shall we typedef it then how?

  • If you are using C++, don't.
  • If you are using C, you should.

The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:

struct MyStruct ; /* Forward declaration */

struct MyStruct
{
   /* etc. */
} ;

void doSomething(struct MyStruct * p) /* parameter */
{
   struct MyStruct a ; /* variable */
   /* etc */
}

While a typedef will enable you to write it without the struct keyword.

struct MyStructTag ; /* Forward declaration */

typedef struct MyStructTag
{
   /* etc. */
} MyStruct ;

void doSomething(MyStruct * p) /* parameter */
{
   MyStruct a ; /* variable */
   /* etc */
}

It is important you still keep a name for the struct. Writing:

typedef struct
{
   /* etc. */
} MyStruct ;

will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:

typedef struct MyStructTag
{
   /* etc. */
} MyStruct ;

Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)

Edit:

Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.

Edit 2018-06-01:

Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.

Indeed, the code above could well be written as:

typedef struct MyStruct
{
   /* etc. */
} MyStruct ;

IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:

// C++ explicit declaration by the user
struct MyStruct
{
   /* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;

Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.

Basic HTTP and Bearer Token Authentication

I had a similar problem - authenticate device and user at device. I used a Cookie header alongside an Authorization: Bearer... header. One header authenticated the device, the other authenticated the user. I used a Cookie header because these are commonly used for authentication.

How to automate drag & drop functionality using Selenium WebDriver Java

There is a page documenting Advanced User Interactions; which has a lot of great examples on how to generate a sequence of actions, you can find it here

// Configure the action
Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .click(someOtherElement)
   .keyUp(Keys.CONTROL);

// Then get the action:
Action selectMultiple = builder.build();

// And execute it:
selectMultiple.perform();   

or

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(someElement)
   .moveToElement(otherElement)
   .release(otherElement)
   .build();

dragAndDrop.perform();

Maximum and Minimum values for ints

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for 'sys' you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Using Windows Authentication

To connect to the database server is recommended to use Windows Authentication, commonly known as integrated security. To specify the Windows authentication, you can use any of the following two key-value pairs with the data provider. NET Framework for SQL Server:

 Integrated Security = true;
 Integrated Security = SSPI;

However, only the second works with the data provider .NET Framework OleDb. If you set Integrated Security = true for ConnectionString an exception is thrown.

To specify the Windows authentication in the data provider. NET Framework for ODBC, you should use the following key-value pair.

Trusted_Connection = yes;

Source: MSDN: Working with Connection Strings

How to redirect stdout to both file and console with scripting?

Use logging module to debug and follow your app

Here is how I managed to log to file and to console / stdout

import logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    filename='logs_file',
                    filemode='w')
# Until here logs only to file: 'logs_file'

# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')

read it from source: https://docs.python.org/2/howto/logging-cookbook.html

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Swift Error: Editor placeholder in source file

Error is straight forward and its because of wrong placeholders you have used in function call. Inside init you are not passing any parameters to your function. It should be this way

destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values

Or you can just initialise with default method

destination = Node()

UPDATE

Add empty initialiser in your Node class

init() {

}

How to import a csv file into MySQL workbench?

In case you have smaller data set, a way to achieve it by GUI is:

  1. Open a query window
  2. SELECT * FROM [table_name]
  3. Select Import from the menu bar
  4. Press Apply on the bottom right below the Result Grid

enter image description here

Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY

how to check if object already exists in a list

Edit: I had first said:


What's inelegant about the dictionary solution. It seems perfectly elegant to me, esp since you only need to set the comparator in creation of the dictionary.


Of course though, it is inelegant to use something as a key when it's also the value.

Therefore I would use a HashSet. If later operations required indexing, I'd create a list from it when the Adding was done, otherwise, just use the hashset.

Change windows hostname from command line

Use below command to change computer hostname remotely , Require system reboot after change..

psexec.exe -h -e \\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

I think that the usage of @Html.LabelForModel() should be explained in more detail.

The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.

You could refer to the following code:

Code in model:

using System.ComponentModel;

[DisplayName("MyModel")]
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

Code in view:

@Html.LabelForModel()
<div class="form-group">

    @Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })

    <div class="col-md-10">
        @Html.EditorFor(model => model.Test)
        @Html.ValidationMessageFor(model => model.Test)
    </div>
</div>

The output screenshot:

enter image description here

Reference to answer on the asp.net forum

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

How do I convert a datetime to date?

Use the date() method:

datetime.datetime.now().date()

SQL Server: Query fast, but slow from procedure

I've got another idea. What if you create this table-based function:

CREATE FUNCTION tbfSelectFromView
(   
    -- Add the parameters for the function here
    @SessionGUID UNIQUEIDENTIFIER
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT *
    FROM Report_Opener
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
)
GO

And then selected from it using the following statement (even putting this in your SP):

SELECT *
FROM tbfSelectFromView(@SessionGUID)

It looks like what's happening (which everybody has already commented on) is that SQL Server just makes an assumption somewhere that's wrong, and maybe this will force it to correct the assumption. I hate to add the extra step, but I'm not sure what else might be causing it.

How to create Password Field in Model Django

You should create a ModelForm (docs), which has a field that uses the PasswordInput widget from the forms library.

It would look like this:

models.py

from django import models
class User(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=50)

forms.py (not views.py)

from django import forms
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        widgets = {
        'password': forms.PasswordInput(),
    }

For more about using forms in a view, see this section of the docs.

Android: How to Programmatically set the size of a Layout

Java

This should work:

// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);

If you want to convert dip to pixels, use this:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());

Kotlin

Bootstrap modal appearing under background

Like Davide Lorigliola, I fixed it by cranking up the z-index:

.modal-backdrop { z-index: -999999; }

jquery: get id from class selector

Doh.. If I get you right, it should be as simple as:

_x000D_
_x000D_
$('.test').click(function() {_x000D_
  console.log(this.id);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<a href="#" class="test" id="test_1">Some text</a>_x000D_
<a href="#" class="test" id="test_2">Some text</a>_x000D_
<a href="#" class="test" id="test_3">Some text</a>
_x000D_
_x000D_
_x000D_

You can just access the id property over the underlaying dom node, within the event handler.

How to redirect to Login page when Session is expired in Java web application?

You could use a Filter and do the following test:

HttpSession session = request.getSession(false);// don't create if it doesn't exist
if(session != null && !session.isNew()) {
    chain.doFilter(request, response);
} else {
    response.sendRedirect("/login.jsp");
}

The above code is untested.

This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. Be paranoid!

Java: Identifier expected

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then "run" the class from your IDE

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Working with $scope.$emit and $scope.$on

You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.

app.controller('firstCtrl', function($scope, $rootScope) {        
        function firstCtrl($scope) {
        {
            $rootScope.$emit('someEvent', [1,2,3]);
        }
}

app.controller('secondCtrl', function($scope, $rootScope) {
        function secondCtrl($scope)
        {
            $rootScope.$on('someEvent', function(event, data) { console.log(data); });
        }
}

Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:

$('.link').tooltip()

Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:

$('[rel=tooltip]').tooltip() 

And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

$('#example').tooltip({
    selector: "a[rel=tooltip]"
})

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

ImportError: No module named 'pygame'

try this in your command prompt: python -m pip intsall pygame

Print a div content using Jquery

Take a Look at this Plugin

Makes your code as easy as -> $('SelectorToPrint').printElement();

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

The SELECT ... INTO needs to be in the select from the CTE.

;WITH Calendar
     AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
       EventStartDate,
       EventEndDate,
       PlannedDate                   AS [EventDates],
       Cast(PlannedDate AS DATETIME) AS DT,
       Cast(EventStartTime AS TIME)  AS ST,
       Cast(EventEndTime AS TIME)    AS ET,
       EventTitle,
       EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/        
FROM   Calendar
WHERE  ( PlannedDate >= Getdate() )
       AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
        OR EventEnumDays IS NULL
ORDER  BY EventID,
          PlannedDate
OPTION (maxrecursion 0) 

What USB driver should we use for the Nexus 5?

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there wasn't any yellow exclamation mark within Device Manager. So for me, the drivers were OK. But the device was not listed within my Eclipse DDMS. After a little bit of searching, it was just an option to change in the device settings. By default, the Nexus 5 USB computer connection is in MTP mode (Media Device).

What you have to do is:

  • Unplug the device from the computer
  • Go to Settings -> Storage.
  • In the ActionBar, click the option menu and choose "USB computer connection".
  • Check "Camera (PTP)" connection.
  • Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  • Finally, you should see it now in the DDMS and voilà.

I hope this will help!

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

What methods of ‘clearfix’ can I use?

Given the huge amount of replies I was not gonna post. However, this method may help someone, as it did help me.

Stay way from floats whenever possible

It's worth to mention, I avoid floats like Ebola. There are many reasons and I am not alone; Read Rikudo answer about what is a clearfix and you'll see what I mean. In his own words: ...the use of floated elements for layout is getting more and more discouraged with the use of better alternatives...

There are other good (and sometimes better) options out there other than floats. As technology advances and improves, flexbox (and other methods) are going to be widely adopted and floats will become just a bad memory. Maybe a CSS4?


Float misbehavior and failed clears

First off, sometimes, you may think that you are safe from floats until your lifesaver is punctured and your html flow starts to sink:

In the codepen http://codepen.io/omarjuvera/pen/jEXBya below, the practice of clearing a float with <div classs="clear"></div> (or other element) is common but frown upon and anti-semantic.

<div class="floated">1st</div>
<div class="floated">2nd</div>
<div class="floated">3nd</div>
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>

CSS

div {
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}

div.floated {
    float: left;
}

.clear {
    clear: both;
}
section {
    border: 1px solid #f0f;
}

However, just when you thought your float is sail worthy...boom! As the screen size becomes smaller and smaller you see weird behaviors in like the graphic below (Same http://codepen.io/omarjuvera/pen/jEXBya):

float bug sample 1

Why should you care? Roughly, about 80% (or more) of the devices used are mobile devices with small screens. Desktop computers/laptops are no longer king.


It does not end there

This is not the only problem with floats. There are many, but in this example, some may say all you have to do is to place your floats in a container. But as you can see in the codepen and graphic, that is not the case. It apparently made things worst:

HTML

<div id="container" class="">
  <div class="floated">1st</div>
  <div class="floated">2nd</div>
  <div class="floated">3nd</div>
</div> <!-- /#conteiner -->
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>

CSS

#container {
  min-height: 100px; /* To prevent it from collapsing */
  border: 1px solid #0f0;
}
.floated {
    float: left;
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}

.clear {
    clear: both;
}
section {
    border: 1px solid #f0f;
}

As for the result?

It's the *** same! float bug sample 2

Least you know, you'll start a CSS party, inviting all kinds of selectors and properties to the party; making a bigger mess of your CSS than what you started with. Just to fix your float.


CSS Clearfix to the rescue

This simple and very adaptable piece of CSS is a beauty and a "savior":

.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

That's it! It really works without breaking semantics and did I mention it works?:

From the same sample...HTML

<div class="clearfix">
    <div class="floated">1st</div>
    <div class="floated">2nd</div>
    <div class="floated">3nd</div>
</div>
<section>Below</section>

CSS

div.floated {
    float: left;
    border: 1px solid #f00;
    width: 200px;
    height: 100px;
}
section {
        border: 4px solid #00f;
}


.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

Now we no longer need <div classs="clear"></div> <!-- Acts as a wall --> and keep the semantic police happy. This is not the only benefit. This clearfix is responsive to any screen size without the use of @media in it's simplest form. In other words, it will keep your float container in check and preventing floodings. Lastly, it provides support for old browsers all in one small karate chop =)

Here's the clearfix again

.clearfix:before, .clearfix:after { 
    content: "";
    display: table;
    clear: both;
    zoom: 1; /* ie 6/7 */
}

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

Initialising a multidimensional array in Java

I'll add that if you want to read the dimensions, you can do this:

int[][][] a = new int[4][3][2];

System.out.println(a.length);  // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2

You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

How to check if a Ruby object is a Boolean

I find this to be concise and self-documenting:

[true, false].include? foo

If using Rails or ActiveSupport, you can even do a direct query using in?

foo.in? [true, false]

Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

How to round down to nearest integer in MySQL?

Both Query is used for round down the nearest integer in MySQL

  1. SELECT FLOOR(445.6) ;
  2. SELECT NULL(222.456);

PHP - concatenate or directly insert variables in string

Between those two syntaxes, you should really choose the one you prefer :-)

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

The result will be the same; and even if there are performance implications, those won't matter 1.


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist. - note that it will only work if you use "" not '' for your string.

That day, you'll need to use {}:

echo "Welcome {$name}s!"

No need to fallback to concatenations.


Also note that your first syntax:

echo "Welcome ".$name."!";

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(But, as I said earlier, this doesn't matter much...)


1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

How to update a menu item shown in the ActionBar?

To refresh menu from Fragment simply call:

getActivity().invalidateOptionsMenu();

Excel CSV - Number cell format

I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen).

I did like the ="001" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data).

How do I run pip on python for windows?

I have a Mac, but luckily this should work the same way:

pip is a command-line thing. You don't run it in python.

For example, on my Mac, I just say:

$pip install somelib

pretty easy!

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

SQL: How do I SELECT only the rows with a unique value on certain column?

Try this:

select 
         contract,
        max (activity) 
from
         mytable 
group by
         contract 
having
         count (activity) = 1

How do I convert this list of dictionaries to a csv file?

Because @User and @BiXiC asked for help with UTF-8 here a variation of the solution by @Matthew. (I'm not allowed to comment, so I'm answering.)

import unicodecsv as csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

apache ProxyPass: how to preserve original IP address

This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/

The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.

Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1

(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf

Shrink a YouTube video to responsive width

With credits to previous answer https://stackoverflow.com/a/36549068/7149454

Boostrap compatible, adust your container width (300px in this example) and you're good to go:

<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>

Dynamic constant assignment

In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:

class MyClass
  MYCONSTANT = "blah"

  def mymethod
    MYCONSTANT
  end
end

class MyClass
  def mymethod
    my_constant = "blah"
  end
end

Rendering React Components from Array of Objects

I have an answer that might be a bit less confusing for newbies like myself. You can just use map within the components render method.

render () {
   return (
       <div>
           {stations.map(station => <div key={station}> {station} </div>)} 
       </div>
   );
}

How do you debug MySQL stored procedures?

The first and stable debugger for MySQL is in dbForge Studio for MySQL

How should I log while using multiprocessing in Python?

One of the alternatives is to write the mutliprocessing logging to a known file and register an atexit handler to join on those processes read it back on stderr; however, you won't get a real-time flow to the output messages on stderr that way.

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

how to get right offset of an element? - jQuery

Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:

var offset = $('#whatever').offset();

offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));

How to redirect output of an already running process

You can also do it using reredirect (https://github.com/jerome-pouiller/reredirect/).

The command bellow redirects the outputs (standard and error) of the process PID to FILE:

reredirect -m FILE PID

The README of reredirect also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.

The tool also provides relink, a script allowing to redirect the outputs to the current terminal:

relink PID
relink PID | grep usefull_content

(reredirect seems to have same features than Dupx described in another answer but, it does not depend on Gdb).

How to add local .jar file dependency to build.gradle file?

Shorter version:

dependencies {
    implementation fileTree('lib')
}

Format JavaScript date as yyyy-mm-dd

formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020

Display Image On Text Link Hover CSS Only

It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.

CSS :

.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }

HTML :

<div class="hover_img">
     <a href="#">Show Image<span><img src="images/01.png" alt="image" height="100" /></span></a>
</div>

Insert data into a view (SQL Server)

Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.

How to search in array of object in mongodb

Use $elemMatch to find the array of particular object

db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

Generate MD5 hash string with T-SQL

None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql

select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...

Changing the highlight color when selecting text in an HTML text input

I realise this is an old question but for anyone who does come across it this can be done using contenteditable as shown in this JSFiddle.

Kudos to Alex who mentioned this in the comments (I didn't see that until now!)

How can I read a large text file line by line using Java?

I documented and tested 10 different ways to read a file in Java and then ran them against each other by making them read in test files from 1KB to 1GB. Here are the fastest 3 file reading methods for reading a 1GB test file.

Note that when running the performance tests I didn't output anything to the console since that would really slow down the test. I just wanted to test the raw reading speed.

1) java.nio.file.Files.readAllBytes()

Tested in Java 7, 8, 9. This was overall the fastest method. Reading a 1GB file was consistently just under 1 second.

import java.io..File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-1GB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}

2) java.nio.file.Files.lines()

This was tested successfully in Java 8 and 9 but it won't work in Java 7 because of the lack of support for lambda expressions. It took about 3.5 seconds to read in a 1GB file which put it in second place as far as reading larger files.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;

public class ReadFile_Files_Lines {
  public static void main(String[] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-1GB.txt";
    File file = new File(fileName);

    try (Stream linesStream = Files.lines(file.toPath())) {
      linesStream.forEach(line -> {
        System.out.println(line);
      });
    }
  }
}

3) BufferedReader

Tested to work in Java 7, 8, 9. This took about 4.5 seconds to read in a 1GB test file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile_BufferedReader_ReadLine {
  public static void main(String [] args) throws IOException {
    String fileName = "c:\\temp\\sample-1GB.txt";
    FileReader fileReader = new FileReader(fileName);

    try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
      String line;
      while((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
      }
    }
  }

You can find the complete rankings for all 10 file reading methods here.

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

For windows 10 you need to path C:\Program Files\Java\jre1.8.0_161\bin

restart command and open

Rails DB Migration - How To Drop a Table?

Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end

How to exit if a command failed?

Provided my_command is canonically designed, ie returns 0 when succeeds, then && is exactly the opposite of what you want. You want ||.

Also note that ( does not seem right to me in bash, but I cannot try from where I am. Tell me.

my_command || {
    echo 'my_command failed' ;
    exit 1; 
}

Add text at the end of each line

If you'd like to add text at the end of each line in-place (in the same file), you can use -i parameter, for example:

sed -i'.bak' 's/$/:80/' foo.txt

However -i option is non-standard Unix extension and may not be available on all operating systems.

So you can consider using ex (which is equivalent to vi -e/vim -e):

ex +"%s/$/:80/g" -cwq foo.txt

which will add :80 to each line, but sometimes it can append it to blank lines.

So better method is to check if the line actually contain any number, and then append it, for example:

ex  +"g/[0-9]/s/$/:80/g" -cwq foo.txt

If the file has more complex format, consider using proper regex, instead of [0-9].

C++ - unable to start correctly (0xc0150002)

I met such problem. Visual Studio 2008 clearly said: problem was caused by libtiff.dll. It cannot be loaded for some reasom, caused by its manifest (as a matter of fact, this dll has no manifest at all). I fixed it, when I had removed libtiff.dll from my project (but simultaneously I lost ability to open compressed TIFFs!). I recompiled aforementioned dll, but problem still remains. Interesting, that at my own machine I have no such error. Three others comps refused to load my prog. Attention!!! Here http://www.error-repair-tools.com/ppc/error.php?t=0xc0150002 one wise boy wrote, that this error was caused by problem with registry and offers repair tool. I have a solid guess, that this "repair tool" will install some malicious soft at your comp.

PHP header(Location: ...): Force URL change in address bar

Do not use any white space. I had the same issue. Then I removed white space like:

header("location:index.php"); or header('location:index.php');

Then it worked.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

After spending hours on this issue found solution here

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
@NgModule({
    imports: [
         FormsModule,
         ReactiveFormsModule      
    ]
})

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

How To Change DataType of a DataColumn in a DataTable?

Once a DataTable has been filled, you can't change the type of a column.

Your best option in this scenario is to add an Int32 column to the DataTable before filling it:

dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);

Then you can clone the data from your original table to the new table:

DataTable dataTableClone = dataTable.Clone();

Here's a post with more details.

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Getting the object's property name

for direct access a object property by position... generally usefull for property [0]... so it holds info about the further... or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.

Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]

Skip download if files exist in wget?

The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.

Using the -c flag when the local file is of greater or equal size to the server version will avoid re-downloading.

UINavigationBar Hide back Button Text

You can implement UINavigationControllerDelegate like this:

Older Swift

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
    viewController.navigationItem.backBarButtonItem = item
}

Swift 4.x

class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }

    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
        viewController.navigationItem.backBarButtonItem = item
    }
}

backBarButtonItem is nil by default and it affects next pushed controller, so you just set it for all controllers

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

On Duplicate Key Update same as insert

Just in case you are able to utilize a scripting language to prepare your SQL queries, you could reuse field=value pairs by using SET instead of (a,b,c) VALUES(a,b,c).

An example with PHP:

$pairs = "a=$a,b=$b,c=$c";
$query = "INSERT INTO $table SET $pairs ON DUPLICATE KEY UPDATE $pairs";

Example table:

CREATE TABLE IF NOT EXISTS `tester` (
  `a` int(11) NOT NULL,
  `b` varchar(50) NOT NULL,
  `c` text NOT NULL,
  UNIQUE KEY `a` (`a`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Why is "cursor:pointer" effect in CSS not working

cursor:pointer doesn't work when you're using Chrome's mobile emulator.

enter image description here

How to add an extra row to a pandas dataframe

A different approach that I found ugly compared to the classic dict+append, but that works:

df = df.T

df[0] = ['1/1/2013', 'Smith','test',123]

df = df.T

df
Out[6]: 
       Date   Name Action   ID
0  1/1/2013  Smith   test  123

Turning off hibernate logging console output

For those who don't want elegant solutions, just a quick and dirty way to stop those messages, here is a solution that worked for me (I use Hibernate 4.3.6 and Eclipse and no answers provided above (or found on the internet) worked; neither log4j config files nor setting the logging level programatically)

public static void main(String[] args) {
    //magical - do not touch
    @SuppressWarnings("unused")
    org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.WARNING); //or whatever level you need

    ...
}

I used it in a tutorial program downloaded from this site

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The server at x3.chatforyoursite.com needs to output the following header:

Access-Control-Allow-Origin: http://www.example.com

Where http://www.example.com is your website address. You should check your settings on chatforyoursite.com to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

$(this).attr("id") not working

Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

function showHideOther(obj){ 
    var sel = obj.options[obj.selectedIndex].value;
    var ID = obj.id;

    if (sel == 'other') { 
        $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}

CORS header 'Access-Control-Allow-Origin' missing

Server side put this on top of .php:

 header('Access-Control-Allow-Origin: *');  

You can set specific domain restriction access:

header('Access-Control-Allow-Origin: https://www.example.com')

Failed to serialize the response in Web API with Json

Just put following lines in global.asax:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Import

using System.Data.Entity;

How to make a simple collection view with Swift

UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.

`React/RCTBridgeModule.h` file not found

For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade on the command line.

Changing the URL in react-router v4 without using Redirect or Link

This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

<GridTile
  key={video_id}
  title={video_title}
  containerElement={<Link to={`/player/${video_id}`}/>}
 >

ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

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

This is how I did it without scripting:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

Same, but with parameter and confirmation dialog:

@using (Html.BeginForm("Action", "Controller", 
        new { paramName = paramValue }, 
        FormMethod.Get, 
        new { onsubmit = "return confirm('Are you sure?');" }))
{
    <button type="submit" 
            class="btn btn-default" 
            title="Action description">Button Label</button>
}

asp.net Button OnClick event not firing

Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.

However, you can expose session variables for JavaScript in several ways:

  • a hidden input field storing the variable as its value and reading it through the DOM API
  • an HTML5 data attribute which you can read through the DOM
  • storing it as a cookie and accessing it through JavaScript
  • injecting it directly in the JS code, if you have it inline

In JSP you'd have something like:

<input type="hidden" name="pONumb" value="${sessionScope.pONumb} />

or:

<div id="product" data-prodnumber="${sessionScope.pONumb}" />

Then in JS:

// you can find a more efficient way to select the input you want
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
for (i = 0; i < len; i++) {
    if (inputs[i].name == "pONumb") {
        pONumb = inputs[i].value;
        break;
    }
}

or:

var product = document.getElementById("product"), pONumb;
pONumb = product.getAttribute("data-prodnumber");

The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.

<script>
    var pONumb = ${sessionScope.pONumb};
    [...]
</script>

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How can I get the current user directory?

Try:

System.Environment.GetEnvironmentVariable("USERPROFILE");

Edit:

If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder enumeration:

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

How to configure logging to syslog in Python?

I found the syslog module to make it quite easy to get the basic logging behavior you describe:

import syslog
syslog.syslog("This is a test message")
syslog.syslog(syslog.LOG_INFO, "Test message at INFO priority")

There are other things you could do, too, but even just the first two lines of that will get you what you've asked for as I understand it.

How to select last child element in jQuery?

If you want to select the last child and need to be specific on the element type you can use the selector last-of-type

Here is an example:

$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");

<div id="example">
            <p>This is paragraph 1</p>
            <p>This is paragraph 2</p>
            <span>This is paragraph 3</span>
            <span>This is paragraph 4</span>
            <p>This is paragraph 5</p>
        </div>

In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.

Convert digits into words with JavaScript

Converting the input string into a number rather than keeping it as a string, limits the solution to the maximum allowed float / integer value on that machine/browser. My script below handles currency up to 1 Trillion dollars - 1 cent :-). I can be extended to handle up to 999 Trillions by adding 3 or 4 lines of code.

var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
            "Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
            "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]; 

var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
            "Eighty","Ninety"]; 


function words999(n999)   {    // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
// 

    var words = ''; var Hn = 0; var n99 = 0;

    Hn = Math.floor(n999 / 100);                  // # of hundreds in it

    if (Hn > 0)   {                               // if at least one 100

      words = words99(Hn) + " Hundred";           // one call for hundreds
    }

    n99 = n999 - (Hn * 100);                      // subtract the hundreds.

    words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.

    return words;
}                            // function words999( n999 )

function words99(n99)   {    // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
// 

    var words = ''; var Dn = 0; var Un = 0;

    Dn = Math.floor(n99 / 10);           // # of tens

    Un = n99 % 10;                       // units

    if (Dn > 0 || Un > 0) {

      if (Dn < 2) {

        words += ones[Dn * 10 + Un];     // words for a # < 20

      } else {

        words += tens[Dn];

        if (Un > 0) words += "-" + ones[Un];
      }
    }                               // if ( Dn > 0 || Un > 0 )

    return words;
}                                   // function words99( n99 )

function getAmtInWords(id1, id2) {  // use numeric value of id1 to populate text in id2 
//
// Read numeric amount field and convert into word amount
// 

    var t1 = document.getElementById(id1).value;

    var t2 = t1.trim();

    amtStr = t2.replace(/,/g,'');        // $123,456,789.12 = 123456789.12

    dotPos = amtStr.indexOf('.');        // position of dot before cents, -ve if it doesn't exist.

    if (dotPos > 0) {

      dollars = amtStr.slice(0,dotPos);  // 1234.56 = 1234
      cents   = amtStr.slice(dotPos+1);  // 1234.56 = .56

    } else if (dotPos == 0) {

      dollars = '0';
      cents   = amtStr.slice(dotPos+1);  // 1234.56 = .56

    } else {

      dollars = amtStr.slice(0);         // 1234 = 1234
      cents   = '0'; 
    }

    t1      = '000000000000' + dollars;  // to extend to trillion, use 15 zeros
    dollars =  t1.slice(-12);            // and -15 here.

    billions  = Number(dollars.substr(0,3));
    millions  = Number(dollars.substr(3,3));
    thousands = Number(dollars.substr(6,3));
    hundreds  = Number(dollars.substr(9,3));

    t1 = words999(billions);    bW = t1.trim();   // Billions  in words

    t1 = words999(millions);    mW = t1.trim();   // Millions  in words

    t1 = words999(thousands);   tW = t1.trim();   // Thousands in words

    t1 = words999(hundreds);    hW = t1.trim();   // Hundreds  in words

    t1 = words99(cents);        cW = t1.trim();   // Cents     in words

    var totAmt = '';

    if (bW != '')   totAmt += ((totAmt != '') ? ' '  : '') + bW + ' Billion';
    if (mW != '')   totAmt += ((totAmt != '') ? ' '  : '') + mW + ' Million';
    if (tW != '')   totAmt += ((totAmt != '') ? ' '  : '') + tW + ' Thousand';
    if (hW != '')   totAmt += ((totAmt != '') ? ' '  : '') + hW + ' Dollars';

    if (cW != '')   totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';

//  alert('totAmt = ' + totAmt);    // display words in a alert

    t1 = document.getElementById(id2).value;

    t2 = t1.trim();

    if (t2 == '')  document.getElementById(id2).value = totAmt;

    return false;
}                        // function getAmtInWords( id1, id2 )

// ======================== [ End Code ] ====================================

How do I instantiate a JAXBElement<String> object?

Other alternative:

JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
                                                String.class, "Your message");

Then:

System.out.println(element.getValue()); // Result: Your message

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

Make sure you have your Spring bean definitions correct. Sometimes, the application works fine, it just displays an error in the IDE, check your project ‘iml’ file if you have a Spring facet defined.

JavaScript get clipboard data on paste event (Cross browser)

For cleaning the pasted text and replacing the currently selected text with the pasted text the matter is pretty trivial:

<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>

JS:

function handlepaste(el, e) {
  document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
  e.preventDefault();
}

Finding element in XDocument?

The problem is that Elements only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants method:

var query = from c in xmlFile.Descendants("Band")

type checking in javascript

You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:

Strict compare of different types: 123 (number) === "123" (string)

How can I edit a .jar file?

A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.

Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.

You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.

Convert number to month name in PHP

I figured everyone looking for this answer was probably just trying to avoid writing out the whole if/else statements, so I wrote it out for you so you can copy/paste. The only caveat with this function is that it goes on the actual number of the month, not a 0-indexed number, so January = 1, not 0.

function getMonthString($m){
    if($m==1){
        return "January";
    }else if($m==2){
        return "February";
    }else if($m==3){
        return "March";
    }else if($m==4){
        return "April";
    }else if($m==5){
        return "May";
    }else if($m==6){
        return "June";
    }else if($m==7){
        return "July";
    }else if($m==8){
        return "August";
    }else if($m==9){
        return "September";
    }else if($m==10){
        return "October";
    }else if($m==11){
        return "November";
    }else if($m==12){
        return "December";
    }
}

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

How to create a Calendar table for 100 years in Sql

As this is only tagged sql (which does not indicate any specific DBMS), here is a solution for Postgres:

select d::date 
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):

create table calendar 
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);

How to uninstall Anaconda completely from macOS

The following line doesn't work?

rm -rf ~/anaconda3 

You should know where your anaconda3(or anaconda1, anaconda2) is installed. So write

which anaconda

output

output: somewhere

Now use that somewhere and run:

rm -rf somewhere 

Creating a list of pairs in java

Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

Start HTML5 video at a particular position when loading?

Using a #t=10,20 fragment worked for me.

python: order a list of numbers without built-in sort, min, max function

Here's a more readable example of an in-place Insertion sort algorithm.

a = [3, 1, 5, 2, 4]

for i in a[1:]:
    j = a.index(i)
    while j > 0 and a[j-1] > a[j]:
        a[j], a[j-1] = a[j-1], a[j]
        j = j - 1

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

filename.whl is not supported wheel on this platform

I was trying to verify the installation of TensorFlow as specified here on a newly created virtual environment on Python 3.6. On running:

pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"

I get the error and/or warning:

tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl is not a supported wheel on this platform.

Since I had previously upgraded from pip to pip3, I simply replaced pip with pip3 as in:

pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"

and it worked like a charm!

Creating random numbers with no duplicates

Another approach which allows you to specify how many numbers you want with size and the min and max values of the returned numbers

public static int getRandomInt(int min, int max) {
    Random random = new Random();

    return random.nextInt((max - min) + 1) + min;
}

public static ArrayList<Integer> getRandomNonRepeatingIntegers(int size, int min,
        int max) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();

    while (numbers.size() < size) {
        int random = getRandomInt(min, max);

        if (!numbers.contains(random)) {
            numbers.add(random);
        }
    }

    return numbers;
}

To use it returning 7 numbers between 0 and 25.

    ArrayList<Integer> list = getRandomNonRepeatingIntegers(7, 0, 25);
    for (int i = 0; i < list.size(); i++) {
        System.out.println("" + list.get(i));
    }

How to pass boolean values to a PowerShell script from a command prompt

I had something similar when passing a script to a function with invoke-command. I ran the command in single quotes instead of double quotes, because it then becomes a string literal. 'Set-Mailbox $sourceUser -LitigationHoldEnabled $false -ElcProcessingDisabled $true';

Can Console.Clear be used to only clear a line instead of whole console?

I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}

Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.

Cannot set content-type to 'application/json' in jQuery.ajax

If you use this:

contentType: "application/json"

AJAX won't sent GET or POST params to the server.... dont know why.

It took me hours to lear it today.

Just Use:

$.ajax(
  { url : 'http://blabla.com/wsGetReport.php',
    data : myFormData, type : 'POST', dataType : 'json', 
    // contentType: "application/json", 
    success : function(wsQuery) { }
  }
)

How can I get last characters of a string

One way would be using slice, like follow:

var id="ctl03_Tabs1";
var temp=id.slice(-5);

so the value of temp would be "Tabs1".

Inserting a value into all possible locations in a list

Simplest is use list[i:i]

    a = [1,2, 3, 4]
    a[2:2] = [10]

Print a to check insertion

    print a
    [1, 2, 10, 3, 4]

Java - Change int to ascii

In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)

Meaning the first answer was correct actually char ch = (char) yourInt;

if in yourint=49 (or 0x31), ch will be '1'

Deprecated: mysql_connect()

<?php 
$link = mysqli_connect('localhost','root',''); 
if (!$link) { 
    die('Could not connect to MySQL: ' . mysqli_error()); 
} 
echo 'Connection OK'; mysqli_close($link); 
?>

This will solve your problem.

What's the best/easiest GUI Library for Ruby?

Using the ironRuby interperter you have the full .net platform, meaning you can code Winforms and WPF(I have only tried Winforms). It is potentially cross platform since the mono platform exist

Using floats with sprintf() in embedded C

Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the printf()-style functions.

Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:

char str[100];
float adc_read = 678.0123;

char *tmpSign = (adc_read < 0) ? "-" : "";
float tmpVal = (adc_read < 0) ? -adc_read : adc_read;

int tmpInt1 = tmpVal;                  // Get the integer (678).
float tmpFrac = tmpVal - tmpInt1;      // Get fraction (0.0123).
int tmpInt2 = trunc(tmpFrac * 10000);  // Turn into integer (123).

// Print as parts, note that you need 0-padding for fractional bit.

sprintf (str, "adc_read = %s%d.%04d\n", tmpSign, tmpInt1, tmpInt2);

You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented).

However, there are ways to handle this by further processing the fractional part, shifting it by four decimal digits each time (and using/subtracting the integer part) until you have the precision you desire.


Update:

One final point you mentioned that you were using avr-gcc in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use %f in your printf() statements here.

As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.

However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.

In case that link ever disappears, what you have to do is ensure that your gcc command has "-Wl,-u,vfprintf -lprintf_flt -lm". This translates to:

  • force vfprintf to be initially undefined (so that the linker has to resolve it).
  • specify the floating point printf() library for searching.
  • specify the math library for searching.

How to perform element-wise multiplication of two lists?

Yet another answer:

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

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

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

outputs [10, 22, 36, 52]

Page redirect after certain time PHP

If you are redirecting with PHP, then you would simply use the sleep() command to sleep for however many seconds before redirecting.

But, I think what you are referring to is the meta refresh tag:

http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

Check whether number is even or odd

    /**
     * Check if a number is even or not using modulus operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    /**
     * Check if a number is even or not using & operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEvenFaster(int number) {
        return (number & 1) == 0;
    }

source

Install specific branch from github using Npm

The Doc of the npm defines that only tag/version can be specified after repo_url.

Here is the Doc: https://docs.npmjs.com/cli/install

using OR and NOT in solr query

Just to add another unexpected case, here is query that wasn't returning expected results:

*:* AND ( ( field_a:foo AND field_b:bar ) OR !field_b:bar )

field_b in my case is something I perform faceting on, and needed to target the query term "foo" only on that type (bar)

I had to insert another *:* after the or condition to get this to work, like so:

*:* AND ( ( field_a:foo AND field_b:bar ) OR ( *:* AND !field_b:bar ) )

edit: this is in solr 6.6.3

How to convert hex string to Java string?

You can go from String (hex) to byte array to String as UTF-8(?). Make sure your hex string does not have leading spaces and stuff.

public static byte[] hexStringToByteArray(String hex) {
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                + Character.digit(hex.charAt(i + 1), 16));
    }
    return data;
}

Usage:

String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...

Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!

Git credential helper - update password

Working solution for Windows:

Control Panel > User Accounts > Credential Manager > Generic Credentials

enter image description here

How to loop through elements of forms with JavaScript?

<form id="yourFormName" >
<input type="text" value="" id="val1">
<input type="text" value="" id="val2">
<input type="text" value="" id="val3">
<button type="button" onclick="yourFunction()"> Check </button>
</form>
<script type="text/javascript">
function yourFunction()
{
  var elements = document.querySelectorAll("#yourFormName input[type=text]")
  console.log(elements);
  for (var i = 0; i<elements.length; i++ )
  {
    var check = document.getElementById(elements[i].id).value);
    console.log(check);
    // write your logic here
  }
}
</script>

Is there a way to take a screenshot using Java and save it to some sort of image?

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();  
GraphicsDevice[] screens = ge.getScreenDevices();       
Rectangle allScreenBounds = new Rectangle();  
for (GraphicsDevice screen : screens) {  
       Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();        
       allScreenBounds.width += screenBounds.width;  
       allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
       allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
       allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
      } 
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
    file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );

bufferedImage will contain a full screenshot, this was tested with three monitors

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

How to select a CRAN mirror in R

I'm a fan of:

chooseCRANmirror()

Which will print the list of mirrors in the output (no worrying a popup window since you are running it from the terminal) and then you enter the number you want.

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

How to add onload event to a div element

I really like the YUI3 library for this sort of thing.

<div id="mydiv"> ... </div>

<script>
YUI().use('node-base', function(Y) {
  Y.on("available", someFunction, '#mydiv')
})

See: http://developer.yahoo.com/yui/3/event/#onavailable

How to combine 2 plots (ggplot) into one plot?

Dummy data (you should supply this for us)

visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))

combine:

visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour

Now do:

 ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) + 
   geom_point() + geom_smooth()

and adjust colours etc to taste.

enter image description here

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

Whoa there!

There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

import java.io.StringReader;
import org.xml.sax.InputSource;
…
        return builder.parse(new InputSource(new StringReader(xml)));

It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

Docker: Copying files from Docker container to host

Mount a volume, copy the artifacts, adjust owner id and group id:

mkdir artifacts
docker run -i --rm -v ${PWD}/artifacts:/mnt/artifacts centos:6 /bin/bash << COMMANDS
ls -la > /mnt/artifacts/ls.txt
echo Changing owner from \$(id -u):\$(id -g) to $(id -u):$(id -g)
chown -R $(id -u):$(id -g) /mnt/artifacts
COMMANDS

EDIT: Note that some of the commands like $(id -u) are backslashed and will therefore be processed within the container, while the ones that are not backslashed will be processed by the shell being run in the host machine BEFORE the commands are sent to the container.

Multiple distinct pages in one HTML file

It is, in theory, possible using data: scheme URIs and frames, but that is rather a long way from practical.

You can fake it by hiding some content with JS and then revealing it when something is clicked (in the style of tabtastic).

How to get text of an element in Selenium WebDriver, without including child element text?

You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use this to force IE to hide that annoying browser compatibility button in the address bar:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

How to get a file directory path from file path?

HERE=$(cd $(dirname $BASH_SOURCE) && pwd)

where you get the full path with new_path=$(dirname ${BASH_SOURCE[0]}). You change current directory with cd new_path and then run pwd to get the full path to the current directory.

What is the difference between fastcgi and fpm?

FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.

Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).

Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.

How to convert URL parameters to a JavaScript object?

ES6 one liner. Clean and simple.

Object.fromEntries(new URLSearchParams(location.search));

For your specific case, it would be:

_x000D_
_x000D_
console.log(_x000D_
  Object.fromEntries(new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5'))_x000D_
);
_x000D_
_x000D_
_x000D_

Close iOS Keyboard by touching anywhere using Swift

  import UIKit

  class ItemViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var nameTextField: UITextField!

    override func viewDidLoad() {
           super.viewDidLoad()
           self.nameTextField.delegate = self
     }

    // Called when 'return' key pressed. return NO to ignore.

    func textFieldShouldReturn(textField: UITextField) -> Bool {

            textField.resignFirstResponder()
             return true
     }

 // Called when the user click on the view (outside the UITextField).

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)    {
      self.view.endEditing(true)
  }
}

Ranges of floating point datatype in C?

As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.

However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.

  • float has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.

  • double has 53 significant binary digits, which is approximately 15 decimal digits.

Another answer of mine has further explanation if you're interested.

How do I efficiently iterate over each entry in a Java Map?

I like to concat a counter, then save the final value of the counter;

int counter = 0;
HashMap<String, String> m = new HashMap<String, String>();
for(int i = 0;i<items.length;i++)
{
m.put("firstname"+i, items.get(i).getFirstName());
counter = i;
}

m.put("recordCount",String.valueOf(counter));

Then when you want to retrieve:

int recordCount = Integer.parseInf(m.get("recordCount"));
for(int i =0 ;i<recordCount;i++)
{
System.out.println("First Name :" + m.get("firstname"+i));
}

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

How to create JSON string in JavaScript?

The way i do it is:

   var obj = new Object();
   obj.name = "Raj";
   obj.age  = 32;
   obj.married = false;
   var jsonString= JSON.stringify(obj);

I guess this way can reduce chances for errors.