Can you change what a symlink points to after it is created?
It is not necessary to explicitly unlink the old symlink. You can do this:
ln -s newtarget temp
mv temp mylink
(or use the equivalent symlink and rename calls). This is better than explicitly unlinking because rename is atomic, so you can be assured that the link will always point to either the old or new target. However this will not reuse the original inode.
On some filesystems, the target of the symlink is stored in the inode itself (in place of the block list) if it is short enough; this is determined at the time it is created.
Regarding the assertion that the actual owner and group are immaterial, symlink(7) on Linux says that there is a case where it is significant:
The owner and group of an existing symbolic link can be changed using
lchown(2). The only time that the ownership of a symbolic link matters is
when the link is being removed or renamed in a directory that has the sticky
bit set (see stat(2)).
The last access and last modification timestamps of a symbolic link can be
changed using utimensat(2) or lutimes(3).
On Linux, the permissions of a symbolic link are not used in any operations;
the permissions are always 0777 (read, write, and execute for all user
categories), and can't be changed.
Determine if Python is running inside virtualenv
In windows OS you see something like this:
C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>
Parentheses mean that you are actually in the virtual environment called "virtualEnvName".
Open file dialog and select a file using WPF controls and C#
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
How to change btn color in Bootstrap
The easiest way to see which properties you need to override is to take a look at Bootstrap's source code, specifically the .button-variant
mixin defined in mixins/buttons.less. You still need to override quite a lot of properties to get rid of all of the .btn-primary
styling (e.g. :focus
, disabled
, usage in dropdowns etc).
A better way might be to:
- Create your own customized version of Bootstrap using Bootstrap's online customization tool
- Manually create your own color class, e.g.
.btn-whatever
- Use a LESS compiler and use the
.button-variant
mixin to create your own color class, e.g. .btn-whatever
JavaScript blob filename without link
I just wanted to expand on the accepted answer with support for Internet Explorer (most modern versions, anyways), and to tidy up the code using jQuery:
$(document).ready(function() {
saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});
function saveFile (name, type, data) {
if (data !== null && navigator.msSaveBlob)
return navigator.msSaveBlob(new Blob([data], { type: type }), name);
var a = $("<a style='display: none;'/>");
var url = window.URL.createObjectURL(new Blob([data], {type: type}));
a.attr("href", url);
a.attr("download", name);
$("body").append(a);
a[0].click();
window.URL.revokeObjectURL(url);
a.remove();
}
Here is an example Fiddle. Godspeed.
Renaming the current file in Vim
Vim does have a rename
function, but unfortunately it does not retain the history.
The easiest OS agnostic way to rename a file without losing the history would be:
:saveas new_file_name
:call delete(expand('#:p'))
expand('#:p')
returns the full path of the older file.
Use :bd #
if you also want to delete the older file from the buffer list.
Or create a plugin
If you want to use a quick command to rename the file, add a new file under ~/.vim/plugin with the following contents:
function! s:rename_file(new_file_path)
execute 'saveas ' . a:new_file_path
call delete(expand('#:p'))
bd #
endfunction
command! -nargs=1 -complete=file Rename call <SID>rename_file(<f-args>)
The command Rename
will help you to quickly rename a file.
What is a "callback" in C and how are they implemented?
Usually this can be done by using a function pointer, that is a special variable that points to the memory location of a function. You can then use this to call the function with specific arguments. So there will probably be a function that sets the callback function. This will accept a function pointer and then store that address somewhere where it can be used. After that when the specified event is triggered, it will call that function.
How do you create nested dict in Python?
For arbitrary levels of nestedness:
In [2]: def nested_dict():
...: return collections.defaultdict(nested_dict)
...:
In [3]: a = nested_dict()
In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})
In [5]: a['a']['b']['c'] = 1
In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
{'a': defaultdict(<function __main__.nested_dict>,
{'b': defaultdict(<function __main__.nested_dict>,
{'c': 1})})})
How to connect to a remote MySQL database with Java?
You need to pass IP/hostname of the rempote machine in the connection string.
import java.sql.*;
import javax.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String url = "jdbc:mysql://localhost:3306/mydb";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,"root"," ");
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
shell script to remove a file if it already exist
If you want to ignore the step to check if file exists or not, then you can use a fairly easy command, which will delete the file if exists and does not throw an error if it is non-existing.
rm -f xyz.csv
How to determine whether a year is a leap year?
The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:
A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0
I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:
leap = A and (not B or C)
This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.
IF Statement multiple conditions, same statement
I think agileguy has the correct answer, but I would like to add that for more difficult situations there are a couple of strategies I take to solve the problem. The first is to use a truth table. If you Google "truth table" you will run across some examples related directly to programming and computer science.
Another strategy I take is to use an anonymous function to encapsulate common logic between various conditions. Create it right before the if block, then use it where needed. This seems to create code that is more readable and maintainable.
How to use System.Net.HttpClient to post a complex type?
You should use the SendAsync
method instead, this is a generic method, that serializes the input to the service
Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );
If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent
class
var client = new HttpClient();
// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));
HttpContent content = new FormUrlEncodedContent(postData);
client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
Note: you need to make your id to a nullable int (int?
)
Creating a UITableView Programmatically
Creating a tableview using tableViewController .
import UIKit
class TableViewController: UITableViewController
{
let tableViewModel = TableViewModel()
var product: [String] = []
var price: [String] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
let priceProductDetails = tableViewModel.dataProvider()
for (key, value) in priceProductDetails
{
product.append(key)
price.append(value)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return product.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
cell.textLabel?.text = product[indexPath.row]
cell.detailTextLabel?.text = price[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
Java ArrayList of Doubles
You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:
new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));
If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:
new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));
CKEditor automatically strips classes from div
If you use Drupal AND the module called "WYSIWYG" with the CKEditor library, then the following workaround could be a solution. For me it works like a charm. I use CKEditor 4.4.5 and WYSIWYG 2.2 in Drupal 7.33. I found this workaround here: https://www.drupal.org/node/1956778.
Here it is:
I create a custom module and put the following code in the ".module" file:
<?php
/**
* Implements hook_wysiwyg_editor_settings_alter().
*/
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
if ($context['profile']->editor == 'ckeditor') {
$settings['allowedContent'] = TRUE;
}
}
?>
I hope this help other Drupal users.
How do you split and unsplit a window/view in Eclipse IDE?
This is possible with the menu items Window>Editor>Toggle Split Editor.
Current shortcut for splitting is:
Azerty keyboard:
- Ctrl + _ for split horizontally, and
- Ctrl + { for split vertically.
Qwerty US keyboard:
- Ctrl + Shift + - (accessing _) for split horizontally, and
- Ctrl + Shift + [ (accessing {) for split vertically.
MacOS - Qwerty US keyboard:
- ⌘ + Shift + - (accessing _) for split horizontally, and
- ⌘ + Shift + [ (accessing {) for split vertically.
On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:
- Alt + ASCII code + Ctrl then release Alt
Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.
Example of vertical split:
PS:
- The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
- The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
- The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.
Generating UNIQUE Random Numbers within a range
You can try next code:
function unique_randoms($min, $max, $count) {
$arr = array();
while(count($arr) < $count){
$tmp =mt_rand($min,$max);
if(!in_array($tmp, $arr)){
$arr[] = $tmp;
}
}
return $arr;
}
How to create an array containing 1...N
Improvising on the above:
var range = function (n) {
return Array(n).join().split(',').map(function(e, i) { return i; });
}
one can get the following options:
1) Array.init to value v
var arrayInitTo = function (n,v) {
return Array(n).join().split(',').map(function() { return v; });
};
2) get a reversed range:
var rangeRev = function (n) {
return Array(n).join().split(',').map(function() { return n--; });
};
How to generate serial version UID in Intellij
Easiest method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
Find non-ASCII characters in varchar columns using SQL Server
To find which field has invalid characters:
SELECT * FROM Staging.APARMRE1 FOR XML AUTO, TYPE
You can test it with this query:
SELECT top 1 'char 31: '+char(31)+' (hex 0x1F)' field
from sysobjects
FOR XML AUTO, TYPE
The result will be:
Msg 6841, Level 16, State 1, Line 3 FOR XML could not serialize the
data for node 'field' because it contains a character (0x001F) which
is not allowed in XML. To retrieve this data using FOR XML, convert it
to binary, varbinary or image data type and use the BINARY BASE64
directive.
It is very useful when you write xml files and get error of invalid characters when validate it.
how to get domain name from URL
For a certain purpose I did this quick Python function yesterday. It returns domain from URL. It's quick and doesn't need any input file listing stuff. However, I don't pretend it works in all cases, but it really does the job I needed for a simple text mining script.
Output looks like this :
http://www.google.co.uk => google.co.uk
http://24.media.tumblr.com/tumblr_m04s34rqh567ij78k_250.gif => tumblr.com
def getDomain(url):
parts = re.split("\/", url)
match = re.match("([\w\-]+\.)*([\w\-]+\.\w{2,6}$)", parts[2])
if match != None:
if re.search("\.uk", parts[2]):
match = re.match("([\w\-]+\.)*([\w\-]+\.[\w\-]+\.\w{2,6}$)", parts[2])
return match.group(2)
else: return ''
Seems to work pretty well.
However, it has to be modified to remove domain extensions on output as you wished.
Download a working local copy of a webpage
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
How can I properly handle 404 in ASP.NET MVC?
I've investigated A LOT on how to properly manage 404s in MVC (specifically MVC3), and this, IMHO is the best solution I've come up with:
In global.asax:
public class MvcApplication : HttpApplication
{
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Response.Clear();
var rd = new RouteData();
rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["controller"] = "Errors";
rd.Values["action"] = "NotFound";
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
}
ErrorsController:
public sealed class ErrorsController : Controller
{
public ActionResult NotFound()
{
ActionResult result;
object model = Request.Url.PathAndQuery;
if (!Request.IsAjaxRequest())
result = View(model);
else
result = PartialView("_NotFound", model);
return result;
}
}
(Optional)
Explanation:
AFAIK, there are 6 different cases that an ASP.NET MVC3 apps can generate 404s.
(Automatically generated by ASP.NET Framework:)
(1) An URL does not find a match in the route table.
(Automatically generated by ASP.NET MVC Framework:)
(2) An URL finds a match in the route table, but specifies a non-existent controller.
(3) An URL finds a match in the route table, but specifies a non-existant action.
(Manually generated:)
(4) An action returns an HttpNotFoundResult by using the method HttpNotFound().
(5) An action throws an HttpException with the status code 404.
(6) An actions manually modifies the Response.StatusCode property to 404.
Normally, you want to accomplish 3 objectives:
(1) Show a custom 404 error page to the user.
(2) Maintain the 404 status code on the client response (specially important for SEO).
(3) Send the response directly, without involving a 302 redirection.
There are various ways to try to accomplish this:
(1)
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customError>
</system.web>
Problems with this solution:
- Does not comply with objective (1) in cases (1), (4), (6).
- Does not comply with objective (2) automatically. It must be programmed manually.
- Does not comply with objective (3).
(2)
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
- Only works on IIS 7+.
- Does not comply with objective (1) in cases (2), (3), (5).
- Does not comply with objective (2) automatically. It must be programmed manually.
(3)
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
- Only works on IIS 7+.
- Does not comply with objective (2) automatically. It must be programmed manually.
- It obscures application level http exceptions. E.g. can't use customErrors section, System.Web.Mvc.HandleErrorAttribute, etc. It can't only show generic error pages.
(4)
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customError>
</system.web>
and
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
- Only works on IIS 7+.
- Does not comply with objective (2) automatically. It must be programmed manually.
- Does not comply with objective (3) in cases (2), (3), (5).
People that have troubled with this before even tried to create their own libraries (see http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3.html). But the previous solution seems to cover all the cases without the complexity of using an external library.
Reusing a PreparedStatement multiple times
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
CSS how to make scrollable list
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
How to write inline if statement for print?
For your case this works:
a = b or 0
Edit: How does this work?
In the question
b = True
So evaluating
b or 0
results in
True
which is assigned to a
.
If b == False?
, b or 0
would evaluate to the second operand 0
which would be assigned to a
.
js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Update (11/2018):
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
How can I get Docker Linux container information from within the container itself?
Docker sets the hostname to the container ID by default, but users can override this with --hostname
. Instead, inspect /proc
:
$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker
Here's a handy one-liner to extract the container ID:
$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
Visual Studio: Relative Assembly References Paths
I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties.
In our setup I added our common repository folder, to the ref path GUI window, like so
That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.
If the dll is found in the Solution, the builder should prioritize the local version over the published team version.
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
This method does not need to modify dtype or ravel your numpy array.
The core idea is:
1.initialize with one extra row.
2.change the list(which has one more row) to array
3.delete the extra row in the result array
e.g.
>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)
# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)
Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.
Shortcuts in Objective-C to concatenate NSStrings
This is for better logging, and logging only - based on dicius excellent multiple argument method. I define a Logger class, and call it like so:
[Logger log: @"foobar ", @" asdads ", theString, nil];
Almost good, except having to end the var args with "nil" but I suppose there's no way around that in Objective-C.
Logger.h
@interface Logger : NSObject {
}
+ (void) log: (id) first, ...;
@end
Logger.m
@implementation Logger
+ (void) log: (id) first, ...
{
// TODO: make efficient; handle arguments other than strings
// thanks to @diciu http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
NSString * result = @"";
id eachArg;
va_list alist;
if(first)
{
result = [result stringByAppendingString:first];
va_start(alist, first);
while (eachArg = va_arg(alist, id))
{
result = [result stringByAppendingString:eachArg];
}
va_end(alist);
}
NSLog(@"%@", result);
}
@end
In order to only concat strings, I'd define a Category on NSString and add a static (+) concatenate method to it that looks exactly like the log method above except it returns the string. It's on NSString because it's a string method, and it's static because you want to create a new string from 1-N strings, not call it on any one of the strings that are part of the append.
ASP.NET Setting width of DataBound column in GridView
I did a small demo for you. Demonstrating how to display long text.
In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)
The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!
<asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name (long)" DataField="Name">
<ItemStyle Width="40px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Name (short)">
<ItemTemplate>
<div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
<%# Eval("Name") %>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my demo codeBehind
public partial class gridViewLongText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region init and bind data
List<Person> list = new List<Person>();
list.Add(new Person(1, "Sam"));
list.Add(new Person(2, "Max"));
list.Add(new Person(3, "Dave"));
list.Add(new Person(4, "TabularasaVeryLongName"));
gvPersons.DataSource = list;
gvPersons.DataBind();
#endregion
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Person(int _ID, string _Name)
{
ID = _ID;
Name = _Name;
}
}
New Array from Index Range Swift
This works for me:
var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]
Your issue could be with how you're declaring your array to begin with.
EDIT:
To fix your function, you have to cast your Slice
to an array:
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = Array(numbers[0..<position])
return newNumbers
}
// test
aFunction([1, 2, 3], 2) // returns [1, 2]
Difference between innerText, innerHTML and value?
The only difference between innerText
and innerHTML
is that innerText
insert string as it is into the element, while innerHTML
run it as html content.
_x000D_
_x000D_
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
_x000D_
_x000D_
java.lang.UnsupportedClassVersionError
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
Launch Failed. Binary not found. CDT on Eclipse Helios
I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem.
Referred to this video
CSS Background Opacity
This is because the inner div has 100% of the opacity of the div it is nested in (which has 40% opacity).
In order to circumvent it, there are a few things you could do.
You could create two separate divs like so:
<div id="background"></div>
<div id="bContent"></div>
Set your desired CSS opacity and other properties for the background and use the z-index property (z-index) to style and position the bContent div. With this you can place the div overtope of the background div without having it's opacity mucked with.
Another option is to RGBa. This will allow you to nest your divs and still achieve div specific opacity.
The last option is to simply make a semi transparent .png image of the color you want in your desired image editor of choice, set the background-image property to the URL of the image and then you won't have to worry about mucking about with the CSS and losing the capability and organization of a nested div structure.
Scanner is skipping nextLine() after using next() or nextFoo()?
It does that because input.nextInt();
doesn't capture the newline. you could do like the others proposed by adding an input.nextLine();
underneath.
Alternatively you can do it C# style and parse a nextLine to an integer like so:
int number = Integer.parseInt(input.nextLine());
Doing this works just as well, and it saves you a line of code.
Why can't I have abstract static methods in C#?
Static methods are not instantiated as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.
Let me show an example.
With the following code:
public class A
{
public static void Test()
{
}
}
public class B : A
{
}
If you call B.Test, like this:
class Program
{
static void Main(string[] args)
{
B.Test();
}
}
Then the actual code inside the Main method is as follows:
.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret
As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.
If you had class types, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.
I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.
Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.
Thus, virtual/abstract static methods are not available in .NET.
What is the (function() { } )() construct in JavaScript?
Self-executing anonymous function. It's executed as soon as it is created.
One short and dummy example where this is useful is:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
So instead of creating a list each time, you create it only once (less overhead).
Convert a positive number to negative in C#
EDIT: This is wrong for positive inputs... I made mistake of forgetting that the rest of the bits in -x (2s-Complement value) are the 'opposite' of their value in +x, not the same. SO simply changing the sign bit will NOT work for positive numbers.
I'll leave this here for in for purposes...
Or the tricky way ( I think )...
int y = x | ~int.MaxValue;
cause int.MaxValue is 0111 1111 1111 1111 1111 1111 1111 1111
so
~int.MaxValue is 1000 0000 0000 0000 0000 0000 0000 0000
and therefore any int32 Or'ed with that will put a 1 in the sign bit, (making it negative), and leave all the other bits the same...
EDIT:
actually, Since the 1000 0000 0000 0000 0000 0000 0000 0000 is actually the Minvalue, this should also work:
int y = x | int.MinValue; // or, to do it to itself,
x |= int.MinValue;
How to Toggle a div's visibility by using a button click
Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.
This feature works for <button>
and <a>
.
If you use a <button>
, you must set the data-toggle
and data-target
attributes:
<button type="button" data-toggle="collapse" data-target="#collapseExample">
Toggle
</button>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
If you use a <a>
, you must use set href
and data-toggle
:
<a data-toggle="collapse" href="#collapseExample">
Toggle
</a>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
How to use local docker images with Minikube?
- setup minikube docker-env
- again build the same docker image (using minikube docker-env)
- change imagePullPolicy to Never in your deployment
actually what happens here , your Minikube can't recognise your docker daemon as it is independent service.You have to first set your minikube-docker environment use below command to check
"eval $(minikube docker-env)"
If you run below command it will show where your minikube looks for docker.
~$ minikube docker-env
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.37.192:2376"
export DOCKER_CERT_PATH="/home/ubuntu/.minikube/certs"
export MINIKUBE_ACTIVE_DOCKERD="minikube"
**# To point your shell to minikube's docker-daemon, run:**
# eval $(minikube -p minikube docker-env)
You have to again build images once you setup minikube docker-env else it will fail.
error::make_unique is not a member of ‘std’
This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14)
.
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
What is the difference between Sessions and Cookies in PHP?
The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.
Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.
Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.
HttpContext.Current.Request.Url.Host what it returns?
Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then
string currentURL = HttpContext.Current.Request.Url.Host;
will return www.someshopping.com
Note the difference between a local debugging environment and a production environment
Convert spark DataFrame column to python list
A possible solution is using the collect_list()
function from pyspark.sql.functions
. This will aggregate all column values into a pyspark array that is converted into a python list when collected:
mvv_list = df.select(collect_list("mvv")).collect()[0][0]
count_list = df.select(collect_list("count")).collect()[0][0]
bower command not found
I am using node version manager. I was getting this error message because I had switched to a different version of node. When I switched back to the version of node where I installed bower, this error went away. In my case, the command was nvm use stable
Codeigniter: does $this->db->last_query(); execute a query?
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this.
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!!
Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Take a look at this example
Cannot set some HTTP headers when using System.Net.WebRequest
Anytime you're changing the headers of an HttpWebRequest
, you need to use the appropriate properties on the object itself, if they exist. If you have a plain WebRequest
, be sure to cast it to an HttpWebRequest
first. Then Referrer
in your case can be accessed via ((HttpWebRequest)request).Referrer
, so you don't need to modify the header directly - just set the property to the right value. ContentLength
, ContentType
, UserAgent
, etc, all need to be set this way.
IMHO, this is a shortcoming on MS part...setting the headers via Headers.Add()
should automatically call the appropriate property behind the scenes, if that's what they want to do.
Is div inside list allowed?
If you look at xhtml1-strict.dtd, you'll see
<!ELEMENT li %Flow;>
<!ENTITY % Flow "(#PCDATA | %block; | form | %inline; | %misc;)*">
<!ENTITY % block
"p | %heading; | div | %lists; | %blocktext; | fieldset | table">
Thus div
, p
etc. can be inside li
(according to XHTML 1.0 Strict DTD from w3.org).
How do I test axios in Jest?
I could do that following the steps:
- Create a folder __mocks__/ (as pointed by @Januartha comment)
- Implement an
axios.js
mock file
- Use my implemented module on test
The mock will happen automatically
Example of the mock module:
module.exports = {
get: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
}),
post: jest.fn((url) => {
if (url === '/something') {
return Promise.resolve({
data: 'data'
});
}
if (url === '/something2') {
return Promise.resolve({
data: 'data2'
});
}
}),
create: jest.fn(function () {
return this;
})
};
Source file 'Properties\AssemblyInfo.cs' could not be found
This can also happen if you have a solution containing the project open in Visual Studio, then use your source control software to change to an older commit that does not contain that project. Normally, this would be obvious as all the project files would disappear as well. But, if it's a new project with very few or no files at all, it could be puzzling to see that just this one file, AssemblyInfo.cs
, is missing. And, it's more likely you'd be messing about with an AssemblyInfo.cs
when a project is new, so might miss that another file or two is also missing.
The cure is to do any of the following:
- Fetch the missing
AssemblyInfo.cs
and any other missing files from another commit, taking care to manage and save your .csproj
file so the referenced files don't vanish from the project—perhaps by adding and removing a random .cs
file to cause changes to need to be saved (since visual studio thinks the .csproj file has been saved when it hasn't).
- Close and reopen Visual Studio without saving (if the project file isn't really saved) or remove the project. Removing makes sense if you didn't actually want the project created yet, since it will be created in the later commit.
- Recreate the
AssemblyInfo.cs
file manually. Just copy another project, and change the details, especially the GUID so it matches the one from the .sln
file.
trace a particular IP and port
You can use the default traceroute
command for this purpose, then there will be nothing to install.
traceroute -T -p 9100 <IP address/hostname>
The -T
argument is required so that the TCP protocol is used instead of UDP.
In the rare case when traceroute
isn't available, you can also use ncat
.
nc -Czvw 5 <IP address/hostname> 9100
SQL Call Stored Procedure for each Row without using a cursor
This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.
Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.
-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);
-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN
-- Get data based on ID
SELECT @Data1 = Data1, @Data2 = Data2
FROM Sales.Customer
WHERE [ID] = @CustomerID ;
-- call your sproc
EXEC dbo.YOURSPROC @Data1, @Data2
-- Get next customerId
SELECT @CustomerID = MIN(CustomerID)
FROM Sales.Customer
WHERE CustomerID > @CustomerId
END
I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.
What is the reason for a red exclamation mark next to my project in Eclipse?
In my case this is incorrect/improper dependency
Markers > Problems is highlighting
spring/.gradle/cache/httpcomponents.......pom is not valid archive
I removed
compile group: 'org.apache.httpcomponents', name: 'httpcomponents-client', version: '4.5.6', ext: 'pom'
changed to
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.6'
Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle
I had the issue when I put jcenter()
before google()
in project level build.gradle. When I changed the order and put google()
before jcenter()
in build.gradle the problem disappeared
Here is my final build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
What in layman's terms is a Recursive Function using PHP
This is a very simple example of factorial with Recursion:
Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.
function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
hope this is usefull for you. :)
NUnit Unit tests not showing in Test Explorer with Test Adapter installed
Check whether you have stated
[TestFixureSetUp]
and
[Test]
in the test class
sample:
namespace ClassLibrary1
{
public class SimpleCalculator
{
public Calculator _calculator;
[TestFixtureSetUp]
public void initialize()
{
_calculator = new Calculator();
}
[Test]
public void DivideTest()
{
int a = 10;
int b = 2;
int expectedValue = a/b;
int actualValue = _calculator.Divide(a, b);
Assert.AreEqual(expectedValue, actualValue, "Functionality not working properly!");
}
}
}
Installing mysql-python on Centos
You probably did not install MySQL via yum? The version of MySQLDB in the repository is tied to the version of MySQL in the repository. The versions need to match.
Your choices are:
- Install the RPM version of MySQL.
- Compile MySQLDB to your version of
MySQL.
Why doesn't java.util.Set have get(int index)?
Set is an interface and some of its implementation classes are HashSet, TreeSet and LinkedHashSet. It uses HashMap under the hood to store values. Because HashMap does not preserve the order, it is not possible to get value by index.
You now must be thinking how Set is using HashMap since HashMap stores a key, value pair but the Set does not. valid question. when you add an element in Set, internally, it maintains a HashMap where the key is the element you want to enter in Set and the value is the dummy constant. Below is an internal implementation of add function. Hence, all the keys in the HashMap will have the same constant value.
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
How to stop flask application without using ctrl-c
If you're working on the CLI and only have one flask app/process running (or rather, you just want want to kill any flask process running on your system), you can kill it with:
kill $(pgrep -f flask)
Get day of week using NSDate
For Swift4 to get weekday from string
func getDayOfWeek(today:String)->Int {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.date(from: today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(NSCalendar.Unit.weekday, from: todayDate)
let weekDay = myComponents.weekday
return weekDay!
}
let weekday = getDayOfWeek(today: "2018-10-10")
print(weekday) // 4
How can I get the height of an element using css only
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
The CSS Route
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
The jQuery Route
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
How to parseInt in Angular.js
This are to way to bind add too numbers
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
Ajax LARAVEL 419 POST error
You may also get that error when CSRF "token" for the active user session is out of date, even if the token was specified in ajax request.
Not receiving Google OAuth refresh token
This has caused me some confusion so I thought I'd share what I've come to learn the hard way:
When you request access using the access_type=offline
and approval_prompt=force
parameters you should receive both an access token and a refresh token. The access token expires soon after you receive it and you will need to refresh it.
You correctly made the request to get a new access token and received the response that has your new access token. I was also confused by the fact that I didn't get a new refresh token. However, this is how it is meant to be since you can use the same refresh token over and over again.
I think some of the other answers assume that you wanted to get yourself a new refresh token for some reason and sugggested that you re-authorize the user but in actual fact, you don't need to since the refresh token you have will work until revoked by the user.
How to decrypt Hash Password in Laravel
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
The source was not found, but some or all event logs could not be searched
EventLog.SourceExists
enumerates through the subkeys of HKLM\SYSTEM\CurrentControlSet\services\eventlog
to see if it contains a subkey with the specified name. If the user account under which the code is running does not have read access to a subkey that it attempts to access (in your case, the Security
subkey) before finding the target source, you will see an exception like the one you have described.
The usual approach for handling such issues is to register event log sources at installation time (under an administrator account), then assume that they exist at runtime, allowing any resulting exception to be treated as unexpected if a target event log source does not actually exist at runtime.
Displaying standard DataTables in MVC
Here is the answer in Razor syntax
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
How do I close a tkinter window?
from tkinter import *
def quit(root):
root.close()
root = Tk()
root.title("Quit Window")
def quit(root):
root.close()
button = Button(root, text="Quit", command=quit.pack()
root.mainloop()
How to print number with commas as thousands separators?
babel module in python has feature to apply commas depending on the locale provided.
To install babel run the below command.
pip install babel
usage
format_currency(1234567.89, 'USD', locale='en_US')
# Output: $1,234,567.89
format_currency(1234567.89, 'USD', locale='es_CO')
# Output: US$ 1.234.567,89 (raw output US$\xa01.234.567,89)
format_currency(1234567.89, 'INR', locale='en_IN')
# Output: ?12,34,567.89
How to identify server IP address in PHP
I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.
/** IIS IP Check **/
if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }
Razor View Without Layout
Procedure 1 : Control Layouts rendering by using _ViewStart file in the root directory of the Views folder
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster") {
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
else {
cLayout = "~/Views/Shared/_Layout.cshtml";
}
Layout = cLayout;
}
Procedure 2 : Set Layout by Returning from ActionResult
One the the great feature of ASP.NET MVC is that, we can override the default layout rendering by returning the layout from the ActionResult. So, this is also a way to render different Layout in your ASP.NET MVC application. Following code sample show how it can be done.
public ActionResult Index()
{
SampleModel model = new SampleModel();
//Any Logic
return View("Index", "_WebmasterLayout", model);
}
Procedure 3 : View - wise Layout (By defining Layout within each view on the top)
ASP.NET MVC provides us such a great feature & faxibility to override the default layout rendering by defining the layout on the view. To implement this we can write our code in following manner in each View.
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
Procedure 4 : Placing _ViewStart file in each of the directories
This is a very useful way to set different Layouts for each Controller in your ASP.NET MVC application. If we want to set default Layout for each directories than we can do this by putting _ViewStart file in each of the directories with the required Layout information as shown below:
@{
Layout = "~/Views/Shared/_WebmasterLayout.cshtml";
}
How to set $_GET variable
I know this is an old thread, but I wanted to post my 2 cents...
Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..
<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>
<button type='button' onClick='ButtonPressed()'>Click me!</button>
<?PHP
if(isset($_GET['next']))
{
echo "This will display after pressing the 'Click Me' button!";
}
?>
How to get name of calling function/method in PHP?
I needed something to just list the calling classes/methods (working on a Magento project).
While debug_backtrace
provides tons of useful information, the amount of information it spewed out for the Magento installation was overwhelming (over 82,000 lines!) Since I was only concerned with the calling function and class, I worked this little solution up:
$callers = debug_backtrace();
foreach( $callers as $call ) {
echo "<br>" . $call['class'] . '->' . $call['function'];
}
How to fully delete a git repository created with init?
You can create an alias for it. I am using ZSH shell with Oh-my-Zsh and here is an handy alias:
# delete and re-init git
# usage: just type 'gdelinit' in a local repository
alias gdelinit="trash .git && git init"
I am using Trash to trash the .git
folder since using rm
is really dangerous:
trash .git
Then I am re-initializing the git repo:
git init
Dynamic SELECT TOP @var In SQL Server
Its also possible to use dynamic SQL and execute it with the exec command:
declare @sql nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)
Making a flex item float right
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
- Use
justify-content: space-between
and the order
property.
- Use
justify-content: space-between
and reverse the order of the divs.
_x000D_
_x000D_
.parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Create a unique number with javascript time
if you want a unique number after few mili seconds then use Date.now()
, if you want to use it inside a for loop
then use Date.now() and Math.random()
together
unique number inside a for loop
function getUniqueID(){
for(var i = 0; i< 5; i++)
console.log(Date.now() + ( (Math.random()*100000).toFixed()))
}
getUniqueID()
output:: all numbers are unique
15598251485988384
155982514859810330
155982514859860737
155982514859882244
155982514859883316
unique number without Math.random()
function getUniqueID(){
for(var i = 0; i< 5; i++)
console.log(Date.now())
}
getUniqueID()
output:: Numbers are repeated
1559825328327
1559825328327
1559825328327
1559825328328
1559825328328
window.location.href and window.open () methods in JavaScript
There are already answers which describes about window.location.href property and window.open() method.
I will go by Objective use:
1. To redirect the page to another
Use window.location.href. Set href property to the href of another page.
2. Open link in the new or specific window.
Use window.open(). Pass parameters as per your goal.
3. Know current address of the page
Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.
See Location Object for more information.
Javascript add leading zeroes to date
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
How to create a DataFrame from a text file in Spark
val df = spark.read.textFile("abc.txt")
case class Abc (amount:Int, types: String, id:Int) //columns and data types
val df2 = df.map(rec=>Amount(rec(0).toInt, rec(1), rec(2).toInt))
rdd2.printSchema
root
|-- amount: integer (nullable = true)
|-- types: string (nullable = true)
|-- id: integer (nullable = true)
Code for a simple JavaScript countdown timer?
_x000D_
_x000D_
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Sep 29 2007 00:00:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
now = new Date();_x000D_
seconds = (theevent - now) / 1000;_x000D_
seconds = Math.round(seconds);_x000D_
minutes = seconds / 60;_x000D_
minutes = Math.round(minutes);_x000D_
hours = minutes / 60;_x000D_
hours = Math.round(hours);_x000D_
days = hours / 24;_x000D_
days = Math.round(days);_x000D_
document.form1.days.value = days;_x000D_
document.form1.hours.value = hours;_x000D_
document.form1.minutes.value = minutes;_x000D_
document.form1.seconds.value = seconds;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
<p>Days_x000D_
<input type="text" name="days" value="0" size="3">Hours_x000D_
<input type="text" name="hours" value="0" size="4">Minutes_x000D_
<input type="text" name="minutes" value="0" size="7">Seconds_x000D_
<input type="text" name="seconds" value="0" size="7">_x000D_
</p>_x000D_
</form>
_x000D_
_x000D_
_x000D_
Checking for NULL pointer in C/C++
I use if (ptr)
, but this is completely not worth arguing about.
I like my way because it's concise, though others say == NULL
makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.
I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)
Note in C++0x, we can do if (ptr == nullptr)
, which to me does read nicer. (Again, I hate the macro. But nullptr
is nice.) I still do if (ptr)
, though, just because it's what I'm used to.
How do I see what character set a MySQL database / table / column is?
For databases:
SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;
Example output:
mysql> SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;
+----------------------------+---------+--------------------+
| database | charset | collation |
+----------------------------+---------+--------------------+
| information_schema | utf8 | utf8_general_ci |
| drupal_demo1 | utf8 | utf8_general_ci |
| drupal_demo2 | utf8 | utf8_general_ci |
| drupal_demo3 | utf8 | utf8_general_ci |
| drupal_demo4 | utf8 | utf8_general_ci |
| drupal_demo5 | latin1 | latin1_swedish_ci |
...
+----------------------------+---------+--------------------+
55 rows in set (0.00 sec)
mysql>
What is Python buffer type for?
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray
:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer
has been replaced by the better named memoryview
in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
When to use std::size_t?
When using size_t be careful with the following expression
size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
cout << containner[i-x] << " " << containner[i+x] << endl;
}
You will get false in the if expression regardless of what value you have for x.
It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.
if ((int)(i-x) > -1 or (i-x) >= 0)
Both ways should work. Here is my test run
size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;
The output: i-7=18446744073709551614 (int)(i-7)=-2
I would like other's comments.
Convert JSON string to dict using Python
If you trust the data source, you can use eval
to convert your string into a dictionary:
eval(your_json_format_string)
Example:
>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)
>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}
>>> print type(x), type(y)
<type 'str'> <type 'dict'>
>>> print y['a'], type(y['a'])
1 <type 'int'>
>>> print y['a'], type(y['b'])
1 <type 'bool'>
>>> print y['a'], type(y['c'])
1 <type 'str'>
Hashcode and Equals for Hashset
according jdk source code from javasourcecode.org, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.
getting the X/Y coordinates of a mouse click on an image with jQuery
Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.
In this case, you should also use $div.outerWidth(true) - $div.width()
and $div.outerHeight(true) - $div.height()
to calculate the amount of margin / border / etc.
Your new code might look more like:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset(); // Offset from the corner of the page.
var xMargin = ($img.outerWidth() - $img.width()) / 2;
var yMargin = ($img.outerHeight() - $img.height()) / 2;
// Note that the above calculations assume your left margin is
// equal to your right margin, top to bottom, etc. and the same
// for borders.
var x = (ev.clientX + xMargin) - offset.left;
var y = (ev.clientY + yMargin) - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
Run batch file from Java code
try following
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Process p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
}
Multiple select statements in Single query
I know this is an old stack but i will post this Multi-SQL select case
SELECT bp.bizid, bp.usrid, bp.website,
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings',
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews',
bp.phoneno, als.bizname,
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`,
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers',
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp
INNER JOIN alluser AS als ON bp.usrid=als.userid
WHERE als.usertype='Business'
How to tell if tensorflow is using gpu acceleration from inside python shell?
You can check if you are currently using the GPU by running the following code:
import tensorflow as tf
tf.test.gpu_device_name()
If the output is ''
, it means you are using CPU
only;
If the output is something like that /device:GPU:0
, it means GPU
works.
And use the following code to check which GPU
you are using:
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
Exit a while loop in VBS/VBA
I know this is old as dirt but it ranked pretty high in google.
The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks
In the example given
num = 0
While num < 10
If status = "Fail" Then
num = 10
End If
num = num + 1
Wend
After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.
Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:
num = 0
While num < 10
If folder = "System32" Then
num = 10
End If
RecursiveDeleteFunction folder
num = num + 1
Wend
Using Do While
or Do Until
allows you to stop execution of the loop using Exit Do
instead of using trickery with your loop condition to maintain the While ... Wend
syntax. I would recommend using that instead.
How often should Oracle database statistics be run?
At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)
Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.
Clear text input on click with AngularJS
If you want to clean up the whole form, you can use such approach.
This is your model into controller:
$scope.registrationForm = {
'firstName' : '',
'lastName' : ''
};
Your HTML:
<form class="form-horizontal" name="registrForm" role="form">
<input type="text" class="form-control"
name="firstName"
id="firstName"
ng-model="registrationForm.firstName"
placeholder="First name"
required> First name
<input type="text" class="form-control"
name="lastName"
id="lastName"
ng-model="registrationForm.lastName"
placeholder="Last name"
required> Last name
</form>
Then, you should clone/save your clear state by:
$scope.originForm = angular.copy($scope.registrationForm);
Your reset function will be:
$scope.resetForm = function(){
$scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form
$scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};
In such way you are able to clean up the whole your form
JavaScript - cannot set property of undefined
d = {} is an empty object right now.
And d[a] is also an empty object.
It does not have any key values. So you should initialize the key values to this.
d[a] = {
greetings:'',
data:''
}
HTML input arrays
It's just PHP, not HTML.
It parses all HTML fields with [] into an array.
So you can have
<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:
echo $_POST['food'][0]; // would output first checkbox selected
or to see all values selected:
foreach( $_POST['food'] as $value ) {
print $value;
}
Anyhow, don't think there is a specific name for it
Change hover color on a button with Bootstrap customization
or can do this...
set all btn ( class name like : .btn-
+ $theme-colors: map-merge
) styles at one time :
@each $color, $value in $theme-colors {
.btn-#{$color} {
@include button-variant($value, $value,
// modify
$hover-background: lighten($value, 7.5%),
$hover-border: lighten($value, 10%),
$active-background: lighten($value, 10%),
$active-border: lighten($value, 12.5%)
// /modify
);
}
}
// code from "node_modules/bootstrap/scss/_buttons.scss"
should add into your customization scss file.
Input text dialog Android
I will add to @Aaron's answer with an approach that gives you the opportunity to style the dialog box in a better way. Here is an adjusted example:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
m_Text = input.getText().toString();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
Here is the example layout used to create the EditText dialog:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/content_padding_normal">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:imeOptions="actionDone"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
</FrameLayout>
The final result:
Classpath resource not found when running as jar
If you want to use a file:
ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
How to Solve Max Connection Pool Error
Before you begin to curse your application you need to check this:
Is your application the only one using that instance of SQL Server.
a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run
b. If the answer is yes then you must investigate your application.
Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).
If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness
Submitting form and pass data to controller method of type FileStreamResult
You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get
. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get
to FormMethod.Post
.
As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.
Binning column with python pandas
You can use pandas.cut
:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
Or numpy.searchsorted
:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
...and then value_counts
or groupby
and aggregate size
:
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
By default cut
return categorical
.
Series
methods like Series.value_counts()
will use all categories, even if some categories are not present in the data, operations in categorical.
graphing an equation with matplotlib
This is because in line
graph(x**3+2*x-4, range(-10, 11))
x is not defined.
The easiest way is to pass the function you want to plot as a string and use eval
to evaluate it as an expression.
So your code with minimal modifications will be
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.show()
and you can call it as
graph('x**3+2*x-4', range(-10, 11))
Is it possible to simulate key press events programmatically?
A non-jquery version that works in both webkit and gecko:
_x000D_
_x000D_
var keyboardEvent = document.createEvent('KeyboardEvent');
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
keyboardEvent[initMethod](
'keydown', // event type: keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // view: should be window
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
40, // keyCode: unsigned long - the virtual key code, else 0
0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
_x000D_
_x000D_
_x000D_
Javascript dynamic array of strings
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']
Executing JavaScript after X seconds
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
Change the value in app.config file dynamically
This code works for me:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["test"].Value = "blah";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.
How do I make an html link look like a button?
Use this class. It will make your link look the same as a button when applied using the button
class on an a
tag.
or
HERE IS ANOTHER DEMO JSFIDDLE
.button {
display: inline-block;
outline: none;
cursor: pointer;
border: solid 1px #da7c0c;
background: #478dad;
text-align: center;
text-decoration: none;
font: 14px/100% Arial, Helvetica, sans-serif;
padding: .5em 2em .55em;
text-shadow: 0 1px 1px rgba(0,0,0,.3);
-webkit-border-radius: .5em;
-moz-border-radius: .5em;
border-radius: .3em;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
box-shadow: 0 1px 2px rgba(0,0,0,.2);
}
.button:hover {
background: #f47c20;
background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));
background: -moz-linear-gradient(top, #f88e11, #f06015);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f88e11', endColorstr='#f06015');
}
.button:active {
position: relative;
top: 1px;
}
How to rename a class and its corresponding file in Eclipse?
To rename file using refactoring (which also updates all occurrences of name in other scripts):
- Save changes to file before using refactoring/renaming
- In Project Explorer view, right-click file to be renamed and select Refactor | Rename -or- select it and go to
Refactor | Rename from the Menu Bar. A Rename File dialog will appear.
- Enter the file's new name.
- Check the "Update references" box and click Preview.
- You can scroll through changes using the Select Next /
Previous Change scrolling arrows.
- Press OK to rename file and update all occurrences of the script name in other scripts.
See "PHP Developer User Guide > Tasks > Using Refactoring > Renaming Files".
Using the RUN instruction in a Dockerfile with 'source' does not work
Here is an example Dockerfile leveraging several clever techniques to all you to run a full conda environment for every RUN
stanza. You can use a similar approach to execute any arbitrary prep in a script file.
Note: there is a lot of nuance when it comes to login/interactive vs nonlogin/noninteractive shells, signals, exec
, the way multiple args are handled, quoting, how CMD and ENTRYPOINT interact, and a million other things, so don't be discouraged if when hacking around with these things, stuff goes sideways. I've spent many frustrating hours digging through all manner of literature and I still don't quite get how it all clicks.
## Conda with custom entrypoint from base ubuntu image
## Build with e.g. `docker build -t monoconda .`
## Run with `docker run --rm -it monoconda bash` to drop right into
## the environment `foo` !
FROM ubuntu:18.04
## Install things we need to install more things
RUN apt-get update -qq &&\
apt-get install -qq curl wget git &&\
apt-get install -qq --no-install-recommends \
libssl-dev \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
## Install miniconda
RUN wget -nv https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh && \
/opt/conda/bin/conda clean -tipsy && \
ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh
## add conda to the path so we can execute it by name
ENV PATH=/opt/conda/bin:$PATH
## Create /entry.sh which will be our new shell entry point. This performs actions to configure the environment
## before starting a new shell (which inherits the env).
## The exec is important! This allows signals to pass
RUN (echo '#!/bin/bash' \
&& echo '__conda_setup="$(/opt/conda/bin/conda shell.bash hook 2> /dev/null)"' \
&& echo 'eval "$__conda_setup"' \
&& echo 'conda activate "${CONDA_TARGET_ENV:-base}"' \
&& echo '>&2 echo "ENTRYPOINT: CONDA_DEFAULT_ENV=${CONDA_DEFAULT_ENV}"' \
&& echo 'exec "$@"'\
) >> /entry.sh && chmod +x /entry.sh
## Tell the docker build process to use this for RUN.
## The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]
SHELL ["/entry.sh", "/bin/bash", "-c"]
## Now, every following invocation of RUN will start with the entry script
RUN conda update conda -y
## Create a dummy env
RUN conda create --name foo
## I added this variable such that I have the entry script activate a specific env
ENV CONDA_TARGET_ENV=foo
## This will get installed in the env foo since it gets activated at the start of the RUN stanza
RUN conda install pip
## Configure .bashrc to drop into a conda env and immediately activate our TARGET env
RUN conda init && echo 'conda activate "${CONDA_TARGET_ENV:-base}"' >> ~/.bashrc
ENTRYPOINT ["/entry.sh"]
How do you run a command as an administrator from the Windows command line?
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
How to install trusted CA certificate on Android device?
These steps worked for me:
- Install Dory Certificate Android app on your mobile device: https://play.google.com/store/apps/details?id=io.tempage.dorycert&hl=en_US
- Connect mobile device to laptop with USB Cable.
- Create root folder on Internal Phone memory, copy the certificate file in that folder and disconnect cable.
- Open Dory Certificate Android app, click the round [+] button and select the right Import File Certificate option.
- Select format, provide a name (I typed same as filename), browse the certificate file and click the [OK].
- Three cards will list up. I ignored the card that only had the [SIGN CSR] button and proceeded to click the [INSTALL] button on the two other cards.
- I refreshed the PWA web app I had opened no my mobile Chrome (it is hosted on a local IIS Web Server) and voala! No chrome warning message. The green lock was there. It was Working.
Alternatively, I found these options which I had no need to try myself but looked easy to follow:
Finally, it may not be relevant but, if you are looking to create and setup a self-signed certificate (with mkcert) for your PWA app (website) hosted on a local IIS Web server, I followed this page:
https://medium.com/@aweber01/locally-trusted-development-certificates-with-mkcert-and-iis-e09410d92031
Thanks and hope it helps!! :)
Reference — What does this symbol mean in PHP?
- $a && $b : TRUE if both $a and $b are TRUE.
- $a || $b : TRUE if either $a or $b is TRUE.
- $a xor $b : TRUE if either $a or $b is TRUE, but not both.
- ! $a : TRUE if $a is not TRUE.
- $a and $b : TRUE if both $a and $b are TRUE.
- $a or $b : TRUE if either $a or $b is TRUE.
- $a == $b : TRUE if $a is equal to $b after type juggling.
- $a === $b : TRUE if $a is equal to $b, and they are of the same type.
- $a != $b : TRUE if $a is not equal to $b after type juggling.
- $a <> $b : TRUE if $a is not equal to $b after type juggling.
- $a !== $b : TRUE if $a is not equal to $b, or they are not of the same type.
- $a < $b : TRUE if $a is strictly less than $b.
- $a > $b : TRUE if $a is strictly greater than $b.
- $a <= $b : TRUE if $a is less than or equal to $b.
- $a >= $b : TRUE if $a is greater than or equal to $b.
- $a <=> $b : An integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.
- $a ? $b : $c : if $a return $b else return $c (ternary operator)
- $a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires PHP>=7)
- -$a : Opposite of $a.
- $a + $b : Sum of $a and $b.
- $a - $b : Difference of $a and $b.
- $a * $b : Product of $a and $b.
- $a / $b : Quotient of $a and $b.
- $a % $b : Remainder of $a divided by $b.
- $a ** $b : Result of raising $a to the $b'th power (introduced in PHP 5.6)
- ++$a : Increments $a by one, then returns $a.
- $a++ : Returns $a, then increments $a by one.
- --$a : Decrements $a by one, then returns $a.
- $a-- : Returns $a, then decrements $a by one.
- $a & $b : Bits that are set in both $a and $b are set.
- $a | $b : Bits that are set in either $a or $b are set.
- $a ^ $b : Bits that are set in $a or $b but not both are set.
- ~ $a : Bits that are set in $a are not set, and vice versa.
- $a << $b : Shift the bits of $a $b steps to the left (each step means "multiply by two")
- $a >> $b : Shift the bits of $a $b steps to the right (each step means "divide by two")
- $a . $b : Concatenation of $a and $b.
- $a + $b : Union of $a and $b.
- $a == $b : TRUE if $a and $b have the same key/value pairs.
- $a === $b : TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
- $a != $b : TRUE if $a is not equal to $b.
- $a <> $b : TRUE if $a is not equal to $b.
- $a !== $b : TRUE if $a is not identical to $b.
- $a = $b : The value of $b is assigned to $a
- $a += $b : Same as $a = $a + $b
- $a -= $b : Same as $a = $a - $b
- *$a = $b : Same as $a = $a * $b
- $a /= $b : Same as $a = $a / $b
- $a %= $b : Same as $a = $a % $b
- **$a = $b : Same as $a = $a ** $b
- $a .= $b : Same as $a = $a . $b
- $a &= $b : Same as $a = $a & $b
- $a |= $b : Same as $a = $a | $b
- $a ^= $b : Same as $a = $a ^ $b
- $a <<= $b : Same as $a = $a << $b
- $a >>= $b : Same as $a = $a >> $b
- $a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)
Note
and
operator and or
operator have lower precedence than assignment operator =
.
This means that $a = true and false;
is equivalent to ($a = true) and false
.
In most cases you will probably want to use &&
and ||
, which behave in a way known from languages like C, Java or JavaScript.
Parameter in like clause JPQL
I don't know if I am late or out of scope but in my opinion I could do it like:
String orgName = "anyParamValue";
Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");
q.setParameter("orgName", orgName);
Mocking static methods with Mockito
The typical strategy for dodging static methods that you have no way of avoiding using, is by creating wrapped objects and using the wrapper objects instead.
The wrapper objects become facades to the real static classes, and you do not test those.
A wrapper object could be something like
public class Slf4jMdcWrapper {
public static final Slf4jMdcWrapper SINGLETON = new Slf4jMdcWrapper();
public String myApisToTheSaticMethodsInSlf4jMdcStaticUtilityClass() {
return MDC.getWhateverIWant();
}
}
Finally, your class under test can use this singleton object by, for example,
having a default constructor for real life use:
public class SomeClassUnderTest {
final Slf4jMdcWrapper myMockableObject;
/** constructor used by CDI or whatever real life use case */
public myClassUnderTestContructor() {
this.myMockableObject = Slf4jMdcWrapper.SINGLETON;
}
/** constructor used in tests*/
myClassUnderTestContructor(Slf4jMdcWrapper myMock) {
this.myMockableObject = myMock;
}
}
And here you have a class that can easily be tested, because you do not directly use a class with static methods.
If you are using CDI and can make use of the @Inject annotation then it is even easier.
Just make your Wrapper bean @ApplicationScoped, get that thing injected as a collaborator (you do not even need messy constructors for testing), and go on with the mocking.
sorting integers in order lowest to highest java
Take Inputs from User and Insertion Sort. Here is how it works:
package com.learning.constructor;
import java.util.Scanner;
public class InsertionSortArray {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter number of elements");
int n=s.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=s.nextInt();
}
System.out.print("Your Array Is: ");
//for(int i: arr){ //for printing array
for (int i = 0; i < arr.length; i++){
System.out.print(arr[i] + ",");
}
System.out.println("\n");
int[] input = arr;
insertionSort(input);
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
How to build x86 and/or x64 on Windows from command line with CMAKE?
This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.
To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.
For CMake 3.13 or newer, run the following commands:
cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release
For earlier versions of CMake, run the following commands:
mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release
CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build
followed by the build directory. The --config
option specifies the build configuration.
IPC performance: Named Pipe vs Socket
One problem with sockets is that they do not have a way to flush the buffer. There is something called the Nagle algorithm which collects all data and flushes it after 40ms. So if it is responsiveness and not bandwidth you might be better off with a pipe.
You can disable the Nagle with the socket option TCP_NODELAY but then the reading end will never receive two short messages in one single read call.
So test it, i ended up with none of this and implemented memory mapped based queues with pthread mutex and semaphore in shared memory, avoiding a lot of kernel system calls (but today they aren't very slow anymore).
printf not printing on console
Add c:\gygwin\bin
to PATH
environment variable either as a system environment variable or in your eclipse project (properties-> run/debug-> edit)
How to force ViewPager to re-instantiate its items
public class DayFlipper extends ViewPager {
private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {
@Override
public int getCount() {
return DayFlipper.DAY_HISTORY;
}
@Override
public void startUpdate(View container) {
}
@Override
public Object instantiateItem(View container, int position) {
Log.d(TAG, "instantiateItem(): " + position);
Date d = DateHelper.getBot();
for (int i = 0; i < position; i++) {
d = DateHelper.getTomorrow(d);
}
d = DateHelper.normalize(d);
CubbiesView cv = new CubbiesView(mContext);
cv.setLifeDate(d);
((ViewPager) container).addView(cv, 0);
// add map
cv.setCubbieMap(mMap);
cv.initEntries(d);
adpter = FlipperAdapter.this;
return cv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((CubbiesView) object);
}
@Override
public void finishUpdate(View container) {
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((CubbiesView) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
...
public void refresh() {
adapter().notifyDataSetChanged();
}
}
try this.
How to highlight a selected row in ngRepeat?
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
Solution:
http://jsfiddle.net/brandonmilleraz/5fr9V/
SQL Server: combining multiple rows into one row
_x000D_
_x000D_
declare @maxColumnCount int=0;
declare @Query varchar(max)='';
declare @DynamicColumnName nvarchar(MAX)='';
-- table type variable that store all values of column row no
DECLARE @TotalRows TABLE( row_count int)
INSERT INTO @TotalRows (row_count)
SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma
-- Get the MAX value from @TotalRows table
set @maxColumnCount= (select max(row_count) from @TotalRows)
-- loop to create Dynamic max/case and store it into local variable
DECLARE @cnt INT = 1;
WHILE @cnt <= @maxColumnCount
BEGIN
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''
set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''
SET @cnt = @cnt + 1;
END;
-- Create dynamic CTE and store it into local variable @query
set @Query='
with CTE_tbl as
(
SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
FROM tblExportPartProforma
)
select
InvoiceNo
'+@DynamicColumnName+'
FROM CTE_tbl
group By InvoiceNo'
-- Execute the Query
execute (@Query)
_x000D_
_x000D_
_x000D_
Tree view of a directory/folder in Windows?
I recommend WinDirStat.
I frequently use WinDirStat to create screen shots for user documentation of open folders and their contents.
It even uses the correct icons for Windows registered file types.
All I would say is missing is an option to display the files without their icons. I can live without it personally, since I am usually pasting the image into a paint program or Visio to edit it, but it would still be a useful feature.
nodejs mongodb object id to string
Try this:
user._id.toString()
A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length. You need to convert it to string to show it in console
using console.log
.
So, you have to do this:
console.log(user._id.toString());
WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?
With help from these answers, I finally got reverse proxy for Node-RED running on a Raspberry Pi with Ubuntu Mate and Apache2 working, using this Apache2 site config:
<VirtualHost *:80>
ServerName nodered.domain.com
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://localhost:1880/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule /(.*) http://localhost:1880/$1 [P,L]
</VirtualHost>
I also had to enable modules like this:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
Plot size and resolution with R markdown, knitr, pandoc, beamer
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
How to count the NaN values in a column in pandas DataFrame
Since pandas 0.14.1 my suggestion here to have a keyword argument in the value_counts method has been implemented:
import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
print df[col].value_counts(dropna=False)
2 1
1 1
NaN 1
dtype: int64
NaN 2
1 1
dtype: int64
Check whether a string contains a substring
To find out if a string contains substring you can use the index
function:
if (index($str, $substr) != -1) {
print "$str contains $substr\n";
}
It will return the position of the first occurrence of $substr
in $str
, or -1 if the substring is not found.
Difference between INNER JOIN and LEFT SEMI JOIN
Trying to depict with venn diagrams for better understanding..
Left Semi join :
A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.
Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.
Inner join : It selects rows that have matching values in both relations.
%Like% Query in spring JpaRepository
You dont actually need the @Query
annotation at all.
You can just use the following
@Repository("registerUserRepository")
public interface RegisterUserRepository extends JpaRepository<Registration,Long>{
List<Registration> findByPlaceIgnoreCaseContaining(String place);
}
Replace \n with <br />
thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
Generate a range of dates using SQL
A method quite frequently used in Oracle is something like this:
select trunc(sysdate)-rn
from
( select rownum rn
from dual
connect by level <= 365)
/
Personally, if an application has a need for a list of dates then I'd just create a table with them, or create a table with a series of integers up to something ridiculous like one million that can be used for this sort of thing.
LINQ's Distinct() on a particular property
What if I want to obtain a distinct list based on one or more properties?
Simple! You want to group them and pick a winner out of the group.
List<Person> distinctPeople = allPeople
.GroupBy(p => p.PersonId)
.Select(g => g.First())
.ToList();
If you want to define groups on multiple properties, here's how:
List<Person> distinctPeople = allPeople
.GroupBy(p => new {p.PersonId, p.FavoriteColor} )
.Select(g => g.First())
.ToList();
Python Pandas: Get index of rows which column matches certain value
I extended this question that is how to gets the row
, column
and value
of all matches value?
here is solution:
import pandas as pd
import numpy as np
def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
nda_values = df_data.values
tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]
if __name__ == '__main__':
test_datas = [['cat', 'dog', ''],
['goldfish', '', 'kitten'],
['Puppy', 'hamster', 'mouse']
]
df_data = pd.DataFrame(test_datas)
print(df_data)
result_list = search_coordinate(df_data, {'dog', 'Puppy'})
print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
[print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]
Output:
0 1 2
0 cat dog
1 goldfish kitten
2 Puppy hamster mouse
row col name
0 1 dog
2 0 Puppy