How to find the Target *.exe file of *.appref-ms
I know this question is old, but the way I found the executable file for a similar application was to first open the application, then open Windows Task Manager, and in the "Processes" list right-click on it and choose "Open File Location".
I couldn't seem to find the location in the application reference file in my case...
Run a Command Prompt command from Desktop Shortcut
I tried this, all it did was open a cmd prompt with "cmd -c (my command)"
and didn't actually run it. see below.
C:\windows\System32>cmd -c (powercfg /lastwake)
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\windows\System32>
***Update
I changed my .bat file to read "cmd /k (powercfg /lastwake)" and it worked.
You can also leave out the () and it works too.
Composer: how can I install another dependency without updating old ones?
Actually, the correct solution is:
composer require vendor/package
Taken from the CLI documentation for Composer:
The require
command adds new packages to the composer.json
file from the current directory.
php composer.phar require
After adding/changing the requirements, the modified requirements will be installed or updated.
If you do not want to choose requirements interactively, you can just pass them to the command.
php composer.phar require vendor/package:2.* vendor/package2:dev-master
While it is true that composer update
installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (>
or *
chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package
, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…
Keep things sane and stick with composer require vendor/package
for adding new dependencies!
List all sequences in a Postgres db 8.1 with SQL
This function shows the last_value of each sequence.
It outputs a 2 columns table that says the sequence name plus it's last generated value.
drop function if exists public.show_sequence_stats();
CREATE OR REPLACE FUNCTION public.show_sequence_stats()
RETURNS TABLE(tablename text, last_value bigint)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
declare r refcursor; rec record; dynamic_query varchar;
BEGIN
dynamic_query='select tablename,last_value from (';
open r for execute 'select nspname,relname from pg_class c join pg_namespace n on c.relnamespace=n.oid where relkind = ''S'' order by nspname';
fetch next from r into rec;
while found
loop
dynamic_query=dynamic_query || 'select '''|| rec.nspname || '.' || rec.relname ||''' "tablename",last_value from ' || rec.nspname || '.' || rec.relname || ' union all ';
fetch next from r into rec;
end loop;
close r;
dynamic_query=rtrim(dynamic_query,'union all') || ') x order by last_value desc;';
return query execute dynamic_query;
END;
$BODY$;
select * from show_sequence_stats();
How to convert date into this 'yyyy-MM-dd' format in angular 2
The date can be converted in typescript to this format 'yyyy-MM-dd'
by using Datepipe
import { DatePipe } from '@angular/common'
...
constructor(public datepipe: DatePipe){}
...
myFunction(){
this.date=new Date();
let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
}
and just add Datepipe in 'providers' array of app.module.ts. Like this:
import { DatePipe } from '@angular/common'
...
providers: [DatePipe]
How do I change a TCP socket to be non-blocking?
The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:
long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
printf("ioctl FIONBIO call failed\n");
}
How to upload, display and save images using node.js and express
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
How to remove jar file from local maven repository which was added with install:install-file?
Although deleting files manually works, there is an official way of removing dependencies of your project from your local (cache) repository and optionally re-resolving them from remote repositories.
The goal purge-local-repository
, on the standard Maven dependency plugin, will remove the locally installed dependencies of this project from your cache. Optionally, you may re-resolve them from the remote repositories at the same time.
This should be used as part of a project phase because it applies to the dependencies for the containing project. Also transitive dependencies will be purged (locally) as well, by default.
If you want to explicitly remove a single artifact from the cache, use purge-local-repository
with the manualInclude
parameter. For example, from the command line:
mvn dependency:purge-local-repository -DmanualInclude="groupId:artifactId, ..."
The documentation implies that this does not remove transitive dependencies by default. If you are running with a non-standard cache location, or on multiple platforms, these are more reliable than deleting files "by hand".
The full documentation is in the maven-dependency-plugin spec.
Note: Older versions of the maven dependency
plugin had a manual-purge-local-repository
goal, which is now (version 2.8) implied by the use of manualInclude
. The documentation for manualIncludes
(with an s
) should be read as well.
ASP.NET MVC 3 Razor: Include JavaScript file in the head tag
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
Check if value already exists within list of dictionaries?
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
Binary Data in JSON String. Something better than Base64
I ran into the same problem, and thought I'd share a solution: multipart/form-data.
By sending a multipart form you send first as string your JSON meta-data, and then separately send as raw binary (image(s), wavs, etc) indexed by the Content-Disposition name.
Here's a nice tutorial on how to do this in obj-c, and here is a blog article that explains how to partition the string data with the form boundary, and separate it from the binary data.
The only change you really need to do is on the server side; you will have to capture your meta-data which should reference the POST'ed binary data appropriately (by using a Content-Disposition boundary).
Granted it requires additional work on the server side, but if you are sending many images or large images, this is worth it. Combine this with gzip compression if you want.
IMHO sending base64 encoded data is a hack; the RFC multipart/form-data was created for issues such as this: sending binary data in combination with text or meta-data.
linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04
The current answer is incomplete. Installing libv4l-dev
creates a /usr/include/linux/videodev2.h
but doesn't solve the stated problem of not being able to find linux/videodev.h
. The library does ship header files for compatibility, but fails to put them where applications will look for them.
sudo apt-get install libv4l-dev
cd /usr/include/linux
sudo ln -s ../libv4l1-videodev.h videodev.h
This provides a linux/videodev.h
, and of the right version (1).
Calculating Page Load Time In JavaScript
Don't ever use the setInterval
or setTimeout
functions for time measuring! They are unreliable, and it is very likely that the JS execution scheduling during a documents parsing and displaying is delayed.
Instead, use the Date
object to create a timestamp when you page began loading, and calculate the difference to the time when the page has been fully loaded:
<doctype html>
<html>
<head>
<script type="text/javascript">
var timerStart = Date.now();
</script>
<!-- do all the stuff you need to do -->
</head>
<body>
<!-- put everything you need in here -->
<script type="text/javascript">
$(document).ready(function() {
console.log("Time until DOMready: ", Date.now()-timerStart);
});
$(window).load(function() {
console.log("Time until everything loaded: ", Date.now()-timerStart);
});
</script>
</body>
</html>
RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location
header containing the new URL to which the client has to send a brand new GET request. So basically:
- Client sends a HTTP request to
some.jsp
.
- Server sends a HTTP response back with
Location: other.jsp
header
- Client sends a HTTP request to
other.jsp
(this get reflected in browser address bar!)
- Server sends a HTTP response back with content of
other.jsp
.
You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
Exactly the above is achieved by sendRedirect("other.jsp")
. The RequestDispatcher#forward()
doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
- Client sends a HTTP request to
some.jsp
.
- Server sends a HTTP response back with content of
other.jsp
.
However, as the original HTTP request was to some.jsp
, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp
will be available in other.jsp
. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp
, hereby throwing away the original request on some.jsp
including all of its attribtues.
The RequestDispatcher
is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF
folder and use a Servlet
which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF
folder are not directly accessible by URL, but the Servlet
can access them using RequestDispatcher#forward()
.
You can for example have a JSP file in /WEB-INF/login.jsp
and a LoginServlet
which is mapped on an url-pattern
of /login
. When you invoke http://example.com/context/login
, then the servlet's doGet()
will be invoked. You can do any preprocessing stuff in there and finally forward the request like:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
When you submit a form, you normally want to use POST
:
<form action="login" method="post">
This way the servlet's doPost()
will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).
If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher
for this.
If a POST
is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
A redirect thus instructs the client to fire a new GET
request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET
pattern.
See also:
Hide/Show components in react native
If you want to hide it but keep the space occupied by the component like css's visibility: hidden
setting in the component's style opacity: 0
should do the trick.
Depending on the component other steps in disabling the functionality might be required as interaction with an invisible item is possible.
wp_nav_menu change sub-menu class name?
in the above i need a small change which i am trying to place but i am not able to do that,
your output will look like this
<ul>
<li id="menu-item-13" class="depth0 parent"><a href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
what i am looking for
<ul>
<li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
in the above one i have placed the parent class inside the parent anchor link that <li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
Difference between chr(13) and chr(10)
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
Find location of a removable SD card
You can try to use the support library function called of ContextCompat.getExternalFilesDirs() :
final File[] appsDir=ContextCompat.getExternalFilesDirs(getActivity(),null);
final ArrayList<File> extRootPaths=new ArrayList<>();
for(final File file : appsDir)
extRootPaths.add(file.getParentFile().getParentFile().getParentFile().getParentFile());
The first one is the primary external storage, and the rest are supposed to be real SD-cards paths.
The reason for the multiple ".getParentFile()" is to go up another folder, since the original path is
.../Android/data/YOUR_APP_PACKAGE_NAME/files/
EDIT: here's a more comprehensive way I've created, to get the sd-cards paths:
/**
* returns a list of all available sd cards paths, or null if not found.
*
* @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static List<String> getSdCardPaths(final Context context, final boolean includePrimaryExternalStorage)
{
final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
if(externalCacheDirs==null||externalCacheDirs.length==0)
return null;
if(externalCacheDirs.length==1)
{
if(externalCacheDirs[0]==null)
return null;
final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
if(!Environment.MEDIA_MOUNTED.equals(storageState))
return null;
if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
return null;
}
final List<String> result=new ArrayList<>();
if(includePrimaryExternalStorage||externalCacheDirs.length==1)
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
for(int i=1;i<externalCacheDirs.length;++i)
{
final File file=externalCacheDirs[i];
if(file==null)
continue;
final String storageState=EnvironmentCompat.getStorageState(file);
if(Environment.MEDIA_MOUNTED.equals(storageState))
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
}
if(result.isEmpty())
return null;
return result;
}
/** Given any file/folder inside an sd card, this will return the path of the sd card */
private static String getRootOfInnerSdCardFolder(File file)
{
if(file==null)
return null;
final long totalSpace=file.getTotalSpace();
while(true)
{
final File parentFile=file.getParentFile();
if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
return file.getAbsolutePath();
file=parentFile;
}
}
lodash: mapping array to object
Yep it is here, using _.reduce
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
_.reduce(params , function(obj,param) {
obj[param.name] = param.input
return obj;
}, {});
Using Jasmine to spy on a function without an object
If you are defining your function:
function test() {};
Then, this is equivalent to:
window.test = function() {} /* (in the browser) */
So spyOn(window, 'test')
should work.
If that is not, you should also be able to:
test = jasmine.createSpy();
If none of those are working, something else is going on with your setup.
I don't think your fakeElement
technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.
Retrieving Android API version programmatically
I generally prefer to add these codes in a function to get the Android version:
int whichAndroidVersion;
whichAndroidVersion= Build.VERSION.SDK_INT;
textView.setText("" + whichAndroidVersion); //If you don't use "" then app crashes.
For example, that code above will set the text into my textView as "29" now.
How to convert enum names to string in c
There is no simple way to achieves this directly. But P99 has macros that allow you to create such type of function automatically:
P99_DECLARE_ENUM(color, red, green, blue);
in a header file, and
P99_DEFINE_ENUM(color);
in one compilation unit (.c file) should then do the trick, in that example the function then would be called color_getname
.
Importing project into Netbeans
From Netbeans 8.1 - there is an "Import from ZIP" option.
Go to Main Menu -> File -> Import Project -> from ZIP.
Browse your .ZIP file's location via Browse button.
If you have Java project depending on external Libraries, Netbeans will highlight & ask for "Resolving problems" in project, click on resolve, provide location in your file system containing required library files .e.g JARs etc & you will be good to go.
Applying function with multiple arguments to create a new pandas column
Alternatively, you can use numpy underlying function:
>>> import numpy as np
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df['new_column'] = np.multiply(df['A'], df['B'])
>>> df
A B new_column
0 10 20 200
1 20 30 600
2 30 10 300
or vectorize arbitrary function in general case:
>>> def fx(x, y):
... return x*y
...
>>> df['new_column'] = np.vectorize(fx)(df['A'], df['B'])
>>> df
A B new_column
0 10 20 200
1 20 30 600
2 30 10 300
Python: Random numbers into a list
Fix the indentation of the print
statement
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
Hibernate: How to set NULL query-parameter value with HQL?
Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:
setParameter("orderItemId", orderItemId, new LongType())
After that, I use the following where clause in my query:
where ((:orderItemId is null) OR (orderItem.id != :orderItemId))
As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.
Hope this helps!
How do I wrap text in a pre tag?
I suggest forget the pre and just put it in a textarea.
Your indenting will remain and your code wont get word-wrapped in the middle of a path or something.
Easier to select text range in a text area too if you want to copy to clipboard.
The following is a php excerpt so if your not in php then the way you pack the html special chars will vary.
<textarea style="font-family:monospace;" onfocus="copyClipboard(this);"><?=htmlspecialchars($codeBlock);?></textarea>
For info on how to copy text to the clipboard in js see: How do I copy to the clipboard in JavaScript? .
However...
I just inspected the stackoverflow code blocks and they wrap in a <code> tag wrapped in <pre> tag with css ...
code {
background-color: #EEEEEE;
font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
}
pre {
background-color: #EEEEEE;
font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;
margin-bottom: 10px;
max-height: 600px;
overflow: auto;
padding: 5px;
width: auto;
}
Also the content of the stackoverflow code blocks is syntax highlighted using (I think) http://code.google.com/p/google-code-prettify/ .
Its a nice setup but Im just going with textareas for now.
m2e lifecycle-mapping not found
You can use this dummy plugin:
mvn archetype:generate -DgroupId=org.eclipse.m2e -DartifactId=lifecycle-mapping -Dversion=1.0.0 -DarchetypeArtifactId=maven-archetype-mojo
After generating the project install/deploy it.
Working copy locked error in tortoise svn while committing
I managed to lock myself out of a file in svn - don't know how - but when I tried (re)-getting the lock (Tortoise was showing the "Get Lock" option for the file), it complained that already had the lock. I tried deleting the file and committing the directory change - same result. I tried CleanUp (including refreshing the overlay), but that failed too.
The solution was to go into the Tortoise repo-browser, find the file and use the break lock function.
Git diff between current branch and master but not including unmerged master commits
According to Documentation
git diff Shows changes between the working tree and the index or a
tree, changes between the index and a tree, changes between two trees,
changes resulting from a merge, changes between two blob objects, or
changes between two files on disk.
In git diff
- There's a significant difference between two dots ..
and 3 dots ...
in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.
Example: Let's assume we're checking out new branch from master and pushing some code in.
G---H---I feature (Branch)
/
A---B---C---D master (Branch)
Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature
or just git diff origin/master
,output: ( H, I
against A, B, C, D
)
Three dots - If we want to show the diffs between the last common ancestor (A
), aka the check point we started our new branch ,we use git diff origin/master...feature
,output: (H, I
against A
).
I'd rather use the 3 dots in most circumstances.
When to use React "componentDidUpdate" method?
This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.
You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop.
Take a look at the example below that shows a typical usage example of this lifecycle method.
componentDidUpdate(prevProps) {
//Typical usage, don't forget to compare the props
if (this.props.userName !== prevProps.userName) {
this.fetchData(this.props.userName);
}
}
Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.
For more info, refer to the official docs:
Why doesn't git recognize that my file has been changed, therefore git add not working
Make sure not to create symlinks (ln -s source dest
) from inside of Git Bash for Windows.
It does NOT make symlinks, but does a DEEP copy of the source to the dest
I experienced same behavior as OP on a MINGW64 terminal from Git Bash for Windows (version 2.16.2) to realize that my 'edited' changes actually were in the original directory, and my git bash commands were from within a deep copy that had remained unchanged.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Python list of dictionaries search
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
def search(name):
for p in people:
if p['name'] == name:
return p
search("Pam")
Why is quicksort better than mergesort?
When I experimented with both sorting algorithms, by counting the number of recursive calls,
quicksort consistently has less recursive calls than mergesort.
It is because quicksort has pivots, and pivots are not included in the next recursive calls. That way quicksort can reach recursive base case more quicker than mergesort.
How can I remove a pytz timezone from a datetime object?
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
Using classes with the Arduino
My Webduino library is all based on a C++ class that implements a web server on top of the Arduino Ethernet shield. I defined the whole class in a .h file that any Arduino code can #include. Feel free to look at the code to see how I do it... I ended up just defining it all inline because there's no real reason to separately compile objects with the Arduino IDE.
String replacement in Objective-C
NSString
objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString
, that gives you several methods for replacing characters within a string. It's probably your best bet.
Notepad++ Regular expression find and delete a line
Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:
- If your file have linux (LF) line ending :
$\n?
- If your file have windows (CRLF) line ending :
$(\r\n)?
For instance, in your case :
.*#RedirectMatch Permanent.*$\n?
Django ManyToMany filter()
Just restating what Tomasz said.
There are many examples of FOO__in=...
style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:
users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])
# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])
The double underscore (__) syntax is used all over the place when working with querysets.
JPA - Persisting a One to Many relationship
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
Python error: "IndexError: string index out of range"
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.
Push to GitHub without a password using ssh-key
You have to use the SSH version, not HTTPS. When you clone from a repository, copy the link with the SSH version, because SSH is easy to use and solves all problems with access. You can set the access for every SSH you input into your account (like push, pull, clone, etc...)
Here is a link, which says why we need SSH and how to use it: step by step
Git Generate SSH Keys
Debug assertion failed. C++ vector subscript out of range
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
How do you add an action to a button programmatically in xcode
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
How to change the Push and Pop animations in a navigation based app
See my answer to this question for a way to do it in far fewer lines of code. This method allows you to animate a pseudo-"Push" of a new view controller any way you like, and when the animation is done it sets up the Navigation Controller just as if you had used the standard Push method. My example lets you animate either a slide-in from the left or from the right.
Code repeated here for convenience:
-(void) showVC:(UIViewController *) nextVC rightToLeft:(BOOL) rightToLeft {
[self addChildViewController:neighbor];
CGRect offscreenFrame = self.view.frame;
if(rightToLeft) {
offscreenFrame.origin.x = offscreenFrame.size.width * -1.0;
} else if(direction == MyClimbDirectionRight) {
offscreenFrame.origin.x = offscreenFrame.size.width;
}
[[neighbor view] setFrame:offscreenFrame];
[self.view addSubview:[neighbor view]];
[neighbor didMoveToParentViewController:self];
[UIView animateWithDuration:0.5 animations:^{
[[neighbor view] setFrame:self.view.frame];
} completion:^(BOOL finished){
[neighbor willMoveToParentViewController:nil];
[neighbor.view removeFromSuperview];
[neighbor removeFromParentViewController];
[[self navigationController] pushViewController:neighbor animated:NO];
NSMutableArray *newStack = [[[self navigationController] viewControllers] mutableCopy];
[newStack removeObjectAtIndex:1]; //self, just below top
[[self navigationController] setViewControllers:newStack];
}];
}
Most efficient method to groupby on an array of objects
var arr = [
{ Phase: "Phase 1", `enter code here`Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];
Create and empty object. Loop through arr and add use Phase as unique key for obj. Keep updating total of key in obj while looping through arr.
const obj = {};
arr.forEach((item) => {
obj[item.Phase] = obj[item.Phase] ? obj[item.Phase] +
parseInt(item.Value) : parseInt(item.Value);
});
Result will look like this:
{ "Phase 1": 50, "Phase 2": 130 }
Loop through obj to form and resultArr.
const resultArr = [];
for (item in obj) {
resultArr.push({ Phase: item, Value: obj[item] });
}
console.log(resultArr);
Java - Convert image to Base64
I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
public class Base64Example {
public static void main(String[] args) {
Base64Example tempObject = new Base64Example();
// convert file to regular byte array
byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");
// encoded file in Base64
byte[] encodedFile = Base64.encodeBase64(codedFile);
// print out the byte array
System.out.println(Arrays.toString(encodedFile));
// print the encoded String
System.out.println(encodedFile);
// decode file back to regular byte array
byte[] decodedByteArray = Base64.decodeBase64(encodedFile);
// save decoded byte array to a file
boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);
// print out success
System.out.println("success : " + success);
}
public byte[] convertFileToByteArray(String filePath) {
Path path = Paths.get(filePath);
byte[] codedFile = null;
try {
codedFile = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return codedFile;
}
public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {
boolean success = false;
Path path = Paths.get(filePath);
try {
Files.write(path, decodedByteArray);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
how do you increase the height of an html textbox
I'm assuming from the way you worded the question that you want to change the size after the page has rendered?
In Javascript, you can manipulate DOM CSS properties, for example:
document.getElementById('textboxid').style.height="200px";
document.getElementById('textboxid').style.fontSize="14pt";
If you simply want to specify the height and font size, use CSS or style attributes, e.g.
//in your CSS file or <style> tag
#textboxid
{
height:200px;
font-size:14pt;
}
<!--in your HTML-->
<input id="textboxid" ...>
Or
<input style="height:200px;font-size:14pt;" .....>
How do I delete all the duplicate records in a MySQL table without temp tables
An alternative way would be to create a new temporary table with same structure.
CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0
Then create the primary key in the table.
ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)
Finally copy all records from the original table while ignoring the duplicate records.
INSERT IGNORE INTO temp_table AS SELECT * FROM original_table
Now you can delete the original table and rename the new table.
DROP TABLE original_table
RENAME TABLE temp_table TO original_table
How to create JSON string in C#
Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.
//Create my object
var my_jsondata = new
{
Host = @"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string json_data = JsonConvert.SerializeObject(my_jsondata);
//Print the Json object
Console.WriteLine(json_data);
//Parse the json object
JObject json_object = JObject.Parse(json_data);
//Print the parsed Json object
Console.WriteLine((string)json_object["Host"]);
Console.WriteLine((string)json_object["UserName"]);
Console.WriteLine((string)json_object["Password"]);
Console.WriteLine((string)json_object["SourceDir"]);
Console.WriteLine((string)json_object["FileName"]);
Where is the Microsoft.IdentityModel dll
I had this problem, but fixed it by referencing the DLL from
"C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll"
Go to reference properties and set Copy Local to True for the DLL. The DLL will now be included in the azure package.
How to programmatically set cell value in DataGridView?
I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:
dataGridView1.ReadOnly = false; //Before modifying, it is required.
dataGridView1.Rows.Add(); //Inserting first row if yet there is no row, first row number is '0'
dataGridView1.Rows[0].Cells[0].Value = "Razib, this is 0,0!"; //Setting the leftmost and topmost cell's value (Not the column header row!)
dataGridView1[1, 0].Value = "This is 0,1!"; //Setting the Second cell of the first row!
Note:
- Previously I have designed the columns in design mode.
- I have set the row header visibility to false from property of the datagridview.
- The last line is important to understand:
When yoou directly giving index of datagridview, the first number is cell number, second one is row number! Remember it!
Hope this might help you.
Not able to access adb in OS X through Terminal, "command not found"
run command in terminal nano $HOME/.zshrc
Must include next lines:
export PATH=$PATH:~/Library/Android/sdk/platform-tools
export ANDROID_HOME=~/Library/Android/sdk
export PATH="$HOME/.bin:$PATH"
export PATH="~/Library/Android/sdk/platform-tools":$PATH
Press Command + X to save file in editor,Enter Yes or No and hit Enter key
Run source ~/.zshrc
Check adb in terminal, run adb
auto create database in Entity Framework Core
My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using
function that I'm not even sure how exactly it works on a lower level.
So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:
public Startup(IHostingEnvironment env)
{
using (var client = new TargetsContext())
{
client.Database.EnsureCreated();
}
}
This pretty much means that within the DbContext
that you created (in this case, mine is called TargetsContext
), you can use an instance of the DbContext
to ensure that the tables defined with in the class are created when Startup.cs is run in your application.
Find all table names with column name?
You could do this:
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;
Reference:
nodejs - How to read and output jpg image?
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
Styling input buttons for iPad and iPhone
I recently came across this problem myself.
<!--Instead of using input-->
<input type="submit"/>
<!--Use button-->
<button type="submit">
<!--You can then attach your custom CSS to the button-->
Hope that helps.
How do I get multiple subplots in matplotlib?
There are several ways to do it. The subplots
method creates the figure along with the subplots that are then stored in the ax
array. For example:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:
fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
What is SaaS, PaaS and IaaS? With examples
When you are a simple client who wants to make use of a software but you have nothing in hand then you use SaaS.
When you have a software developed by you, but you want to deploy and run on a publicly available platform then you use PaaS.
When you have the software and the platform ready but you want the hardware to run then you use IaaS.
Button that refreshes the page on click
I noticed that all the answers here use inline onClick
handlers. It's generally recommended to keep HTML and Javascript separate.
Here's an answer that adds a click event listener directly to the button. When it's clicked, it calls location.reload which causes the page to reload with the current URL.
_x000D_
_x000D_
const refreshButton = document.querySelector('.refresh-button');_x000D_
_x000D_
const refreshPage = () => {_x000D_
location.reload();_x000D_
}_x000D_
_x000D_
refreshButton.addEventListener('click', refreshPage)
_x000D_
.demo-image {_x000D_
display: block;_x000D_
}
_x000D_
<button class="refresh-button">Refresh!</button>_x000D_
<img class="demo-image" src="https://picsum.photos/200/300">
_x000D_
_x000D_
_x000D_
IIS Request Timeout on long ASP.NET operation
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
Infinite Recursion with Jackson JSON and Hibernate JPA issue
Also, using Jackson 2.0+ you can use @JsonIdentityInfo
. This worked much better for my hibernate classes than @JsonBackReference
and @JsonManagedReference
, which had problems for me and did not solve the issue. Just add something like:
@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@traineeId")
public class Trainee extends BusinessObject {
@Entity
@Table(name = "ta_bodystat", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@bodyStatId")
public class BodyStat extends BusinessObject {
and it should work.
The system cannot find the file specified in java
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad
Makefile - missing separator
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
python: iterate a specific range in a list
A more memory efficient way to iterate over a slice of a list would be to use islice()
from the itertools
module:
from itertools import islice
listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])
for item in islice(listOfStuff, 1, 3):
print item
# ['c', 'd']
# ['e', 'f']
However, this can be relatively inefficient in terms of performance if the start value of the range is a large value sinceislice
would have to iterate over the first start value-1 items before returning items.
Entity Framework. Delete all rows in table
In my code I didn't really have nice access to the Database object, so you can do it on the DbSet where you also is allowed to use any kind of sql. It will sort of end out like this:
var p = await _db.Persons.FromSql("truncate table Persons;select top 0 * from Persons").ToListAsync();
Using jQuery's ajax method to retrieve images as a blob
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
_x000D_
_x000D_
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_
or
use xhrFields to set the responseType
_x000D_
_x000D_
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_
Duplicate AssemblyVersion Attribute
I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved
// AssemblyVersion is the CLR version. Change this only when making breaking changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]
How to POST the data from a modal form of Bootstrap?
You need to handle it via ajax
submit.
Something like this:
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
A better way would be to use a django form, and then render the following snippet:
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
via the context - example : {{form}}
.
Does adding a duplicate value to a HashSet/HashMap replace the previous value
Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).
The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.
But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.
How to detect incoming calls, in an Android device?
private MyPhoneStateListener phoneStateListener = new MyPhoneStateListener();
to register
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
and to unregister
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
Android set bitmap to Imageview
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
How to use Boost in Visual Studio 2010
In addition, there is something I find very useful. Use environment variables for your boost paths. (How to set environment variables in windows, link at bottom for 7,8,10) The BOOST_ROOT variable seems to be common place anymore and is set to the root path where you unzip boost.
Then in Properties, c++, general, Additional Include Directories use $(BOOST_ROOT)
. Then if/when you move to a newer version of the boost library you can update your environment variable to point to this newer version. As more of your projects, use boost you will not have to update the 'Additional Include Directories' for all of them.
You may also create a BOOST_LIB variable and point it to where the libs are staged. So likewise for the Linker->Additional Library Directories, you won't have to update projects. I have some old stuff built with vs10 and new stuff with vs14 so built both flavors of the boost lib to the same folder. So if I move a project from vs10 to vs14 I don't have to change the boost paths.
NOTE: If you change an environment variable it will not suddenly work in an open VS project. VS loads variables on startup. So you will have to close VS and reopen it.
Is gcc's __attribute__((packed)) / #pragma pack unsafe?
(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:
0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)
Then I can declare something like
typedef struct {
uint8_t msgType;
uint16_t targetAddr; // may have to bswap
uint8_t data[12];
uint8_t checksum;
} __attribute__((packed)) myStruct;
and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.
Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.
Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)
How to copy a map?
As stated in seong's comment:
Also see http://golang.org/doc/effective_go.html#maps. The important part is really the "reference to underlying data structure". This also applies to slices.
However, none of the solutions here seem to offer a solution for a proper deep copy that also covers slices.
I've slightly altered Francesco Casula's answer to accommodate for both maps and slices.
This should cover both copying your map itself, as well as copying any child maps or slices. Both of which are affected by the same "underlying data structure" issue. It also includes a utility function for performing the same type of Deep Copy on a slice directly.
Keep in mind that the slices in the resulting map will be of type []interface{}
, so when using them, you will need to use type assertion to retrieve the value in the expected type.
Example Usage
copy := CopyableMap(originalMap).DeepCopy()
Source File (util.go
)
package utils
type CopyableMap map[string]interface{}
type CopyableSlice []interface{}
// DeepCopy will create a deep copy of this map. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (m CopyableMap) DeepCopy() map[string]interface{} {
result := map[string]interface{}{}
for k,v := range m {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result[k] = CopyableMap(mapvalue).DeepCopy()
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result[k] = CopyableSlice(slicevalue).DeepCopy()
continue
}
result[k] = v
}
return result
}
// DeepCopy will create a deep copy of this slice. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (s CopyableSlice) DeepCopy() []interface{} {
result := []interface{}{}
for _,v := range s {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result = append(result, CopyableMap(mapvalue).DeepCopy())
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result = append(result, CopyableSlice(slicevalue).DeepCopy())
continue
}
result = append(result, v)
}
return result
}
Test File (util_tests.go
)
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}
m2 := CopyableMap(m1).DeepCopy()
m1["a"] = "zzz"
delete(m1, "b")
m1["c"].([]interface{})[1] = "x"
m1["c"].([]interface{})[2].(map[string]interface{})["f"] = "h"
require.Equal(t, map[string]interface{}{
"a": "zzz",
"c": []interface{} {
"d", "x", map[string]interface{} {
"f": "h",
},
},
}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}, m2)
}
How to disable right-click context-menu in JavaScript
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
get and set in TypeScript
Based on example you show, you want to pass a data object and get a property of that object by get(). for this you need to use generic type, since data object is generic, can be any object.
export class Attributes<T> {
constructor(private data: T) {}
get = <K extends keyof T>(key: K): T[K] => {
return this.data[key];
};
set = (update: T): void => {
// this is like spread operator. it will take this.data obj and will overwrite with the update obj
// ins tsconfig.json change target to Es6 to be able to use Object.assign()
Object.assign(this.data, update);
};
getAll(): T {
return this.data;
}
}
< T > refers to generic type. let's initialize an instance
const myAttributes=new Attributes({name:"something",age:32})
myAttributes.get("name")="something"
Notice this syntax
<K extends keyof T>
in order to be able to use this we should be aware of 2 things:
1- in typestring strings can be a type.
2- all object properties in javascript essentially are strings.
when we use get(), type of argument that it is receiving is a property of object that passed to constructor and since object properties are strings and strings are allowed to be a type in typescript, we could use this <K extends keyof T>
How can I convert an RGB image into grayscale in Python?
You can always read the image file as grayscale right from the beginning using imread
from OpenCV:
img = cv2.imread('messi5.jpg', 0)
Furthermore, in case you want to read the image as RGB, do some processing and then convert to Gray Scale you could use cvtcolor
from OpenCV:
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
Get String in YYYYMMDD format from JS date object?
Use padStart:
Date.prototype.yyyymmdd = function() {
return [
this.getFullYear(),
(this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
this.getDate().toString().padStart(2, '0')
].join('-');
};
Send XML data to webservice using php curl
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
When to Redis? When to MongoDB?
I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:
Use MongoDB if you don't know yet how you're going to query your data.
MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.
Use Redis in order to speed up your existing application.
Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.
Redis does not make any assumptions based on your data.
Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.
When to use Redis?
Caching
Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.
If you have enough time to think about your DB design.
You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.
If you need really high performance.
Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.
If you don't care that much about scaling.
Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.
When to use MongoDB
Prototyping, Startups, Hackathons
MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.
When you need to change your schema quickly.
Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.
TL;DR
- Use Redis if performance is important and you are willing to spend time optimizing and organizing your data.
- Use MongoDB if you need to build a prototype without worrying too much about your DB.
Further reading:
Throwing multiple exceptions in a method of an interface in java
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
How do I get the current mouse screen coordinates in WPF?
You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT pPoint);
Point is a light struct
. It contains only X, Y fields.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Tick += new EventHandler(timer_tick);
dt.Interval = new TimeSpan(0,0,0,0, 50);
dt.Start();
}
private void timer_tick(object sender, EventArgs e)
{
POINT pnt;
GetCursorPos(out pnt);
current_x_box.Text = (pnt.X).ToString();
current_y_box.Text = (pnt.Y).ToString();
}
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks
not milliseconds
.
TimeSpan(50); //ticks
Make button width fit to the text
Remove the width and display: block
and then add display: inline-block
to the button. To have it remain centered you can either add text-align: center;
on the body
or do the same on a newly created container.
The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.
Example: http://cssdeck.com/labs/2u4kf6dv
What's the difference between a word and byte?
The terms of BYTE and WORD are relative to the size of the processor that is being referred to. The most common processors are/were 8 bit, 16 bit, 32 bit or 64 bit. These are the WORD lengths of the processor. Actually half of a WORD is a BYTE, whatever the numerical length is. Ready for this, half of a BYTE is a NIBBLE.
.rar, .zip files MIME Type
In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:
import Foundation
import MobileCoreServices
extension URL {
var mimeType: String? {
guard self.pathExtension.count != 0 else {
return nil
}
let pathExtension = self.pathExtension as CFString
if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
return nil
}
return mimeType.takeRetainedValue() as String
}
return nil
}
}
Using generic std::function objects with member functions in one class
A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument.
Because your std::function
signature specifies that your function doesn't take any arguments (<void(void)>
), you must bind the first (and the only) argument.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
If you want to bind a function with parameters, you need to specify placeholders:
using namespace std::placeholders;
std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2);
Or, if your compiler supports C++11 lambdas:
std::function<void(int,int)> f = [=](int a, int b) {
this->doSomethingArgs(a, b);
}
(I don't have a C++11 capable compiler at hand right now, so I can't check this one.)
Windows Batch Files: if else
if not %1 == "" (
must be
if not "%1" == "" (
If an argument isn't given, it's completely empty, not even ""
(which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.
How do I create a multiline Python string with inline variables?
f-strings, also called “formatted string literals,” are string literals that have an f
at the beginning; and curly braces containing expressions that will be replaced with their values.
f-strings are evaluated at runtime.
So your code can be re-written as:
string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")
And this will evaluate to:
I will go there
I will go now
great
You can learn more about it here.
Storing Images in DB - Yea or Nay?
Second the recommendation on file paths. I've worked on a couple of projects that needed to manage large-ish asset collections, and any attempts to store things directly in the DB resulted in pain and frustration long-term.
The only real "pro" I can think of regarding storing them in the DB is the potential for easy of individual image assets. If there are no file paths to use, and all images are streamed straight out of the DB, there's no danger of a user finding files they shouldn't have access to.
That seems like it would be better solved with an intermediary script pulling data from a web-inaccessible file store, though. So the DB storage isn't REALLY necessary.
What is "Linting"?
Lint was the name of a program that would go through your C code and identify problems before you compiled, linked, and ran it. It was a static checker, much like FindBugs today for Java.
Like Google, "lint" became a verb that meant static checking your source code.
How to compare DateTime in C#?
public static bool CompareDateTimes(this DateTime firstDate, DateTime secondDate)
{
return firstDate.Day == secondDate.Day && firstDate.Month == secondDate.Month && firstDate.Year == secondDate.Year;
}
How do I create ColorStateList programmatically?
Here's an example of how to create a ColorList
programmatically in Kotlin:
val colorList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_enabled), // Disabled
intArrayOf(android.R.attr.state_enabled) // Enabled
),
intArrayOf(
Color.BLACK, // The color for the Disabled state
Color.RED // The color for the Enabled state
)
)
How do I display a ratio in Excel in the format A:B?
I found this to be the easiest and the shortest, I however rounded off to zero decimal places:
="1" & ":" & ROUND((A1/B1),0)
Note the spaces before and after &
.
What this means is that "1" and ":" are seen as additional non-formula information to the overall formula. The ROUND
function rounds off A1/B1 that is the basic formula to 0 decimal places. you can try changing to 1,2,3... decimal places.
I hope I made this clear.
Import an Excel worksheet into Access using VBA
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
How to handle notification when app in background in Firebase
June 2018 Answer -
You have to make sure there is not a "notification" keyword anywhere in the message. Only include "data", and the app will be able to handle the message in onMessageReceived, even if in background or killed.
Using Cloud Functions:
const message = {
token: token_id, // obtain device token id by querying data in firebase
data: {
title: "my_custom_title",
body: "my_custom_body_message"
}
}
return admin.messaging().send(message).then(response => {
// handle response
});
Then in your onMessageReceived(), in your class extending com.google.firebase.messaging.FirebaseMessagingService :
if (data != null) {
Log.d(TAG, "data title is: " + data.get("title");
Log.d(TAG, "data body is: " + data.get("body");
}
// build notification using the body, title, and whatever else you want.
Why am I not getting a java.util.ConcurrentModificationException in this example?
This runs fine on Java 1.6
~ % javac RemoveListElementDemo.java
~ % java RemoveListElementDemo
~ % cat RemoveListElementDemo.java
import java.util.*;
public class RemoveListElementDemo {
private static final List<Integer> integerList;
static {
integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
}
public static void remove(Integer remove) {
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
public static void main(String... args) {
remove(Integer.valueOf(2));
Integer remove = Integer.valueOf(3);
for(Integer integer : integerList) {
if(integer.equals(remove)) {
integerList.remove(integer);
}
}
}
}
~ %
Using the "With Clause" SQL Server 2008
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
No more data to read from socket error
For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.
You have two ways to address this:
- upgrade to 11.2
- set oracle parameter
_optim_peek_user_binds = false
Of course underscore parameters should only be set if advised by oracle support
How do I hide the bullets on my list for the sidebar?
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
MySql Table Insert if not exist otherwise update
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Multiple bluetooth connection
Please take a look at the Android documentation.
Using the Bluetooth APIs, an Android application can perform the following:
- Scan for other Bluetooth devices
- Query the local Bluetooth adapter for paired Bluetooth devices
- Establish RFCOMM channels
- Connect to other devices through service discovery
- Transfer data to and from other devices
- Manage multiple connections
How to obtain the start time and end time of a day?
private Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.setTimeInMillis(0);
calendar.set(year, month, day, 0, 0, 0);
return calendar.getTime();
}
private Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.setTimeInMillis(0);
calendar.set(year, month, day, 23, 59, 59);
return calendar.getTime();
}
calendar.setTimeInMillis(0); gives you accuracy upto milliseconds
DB2 Date format
select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1
result: 20160510
How to get query string parameter from MVC Razor markup?
I think a more elegant solution is to use the controller and the ViewData dictionary:
//Controller:
public ActionResult Action(int IFRAME)
{
ViewData["IsIframe"] = IFRAME == 1;
return View();
}
//view
@{
string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : "";
<div id="wrap" class='@classToUse'></div>
}
Restoring database from .mdf and .ldf files of SQL Server 2008
use test
go
alter proc restore_mdf_ldf_main (@database varchar(100), @mdf varchar(100),@ldf varchar(100),@filename varchar(200))
as
begin
begin try
RESTORE DATABASE @database FROM DISK = @FileName
with norecovery,
MOVE @mdf TO 'D:\sql samples\sample.mdf',
MOVE @ldf TO 'D:\sql samples\sample.ldf'
end try
begin catch
SELECT ERROR_MESSAGE() AS ErrorMessage;
print 'Restoring of the database ' + @database + ' failed';
end catch
end
exec restore_mdf_ldf_main product,product,product_log,'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\product.bak'
Angular2: custom pipe could not be found
see this is working for me.
ActStatus.pipe.ts First this is my pipe
import {Pipe,PipeTransform} from "@angular/core";
@Pipe({
name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
transform(status:any):any{
switch (status) {
case 1:
return "UN_PUBLISH";
case 2:
return "PUBLISH";
default:
return status
}
}
}
main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.
import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";
import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---
@NgModule({
declarations:[ActStatusPipe], // <---
imports:[CommonModule],
exports:[ActStatusPipe] // <---
})
export class MainPipe{}
app.module.ts user this pipe module in any module.
@NgModule({
declarations: [...],
imports: [..., MainPipe], // <---
providers: [...],
bootstrap: [AppComponent]
})
you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.
- create pipe .
- create separate module and declare and export one or more pipe.
- user that pipe module.
How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).
MySQL Data - Best way to implement paging?
For 500 records efficiency is probably not an issue, but if you have millions of records then it can be advantageous to use a WHERE clause to select the next page:
SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20
The "234374" here is the id of the last record from the prevous page you viewed.
This will enable an index on id to be used to find the first record. If you use LIMIT offset, 20
you could find that it gets slower and slower as you page towards the end. As I said, it probably won't matter if you have only 200 records, but it can make a difference with larger result sets.
Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.
If you do wish to use LIMIT with an offset (and this is necessary if a user navigates directly to page 10000 instead of paging through pages one by one) then you could read this article about late row lookups to improve performance of LIMIT with a large offset.
How can I access a hover state in reactjs?
React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover
in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter
and onMouseLeave
. You then attach them to handlers in your component like so:
<ReactComponent
onMouseEnter={() => this.someHandler}
onMouseLeave={() => this.someOtherHandler}
/>
You'll then use some combination of state/props to pass changed state or properties down to your child React components.
Creating files in C++
/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}
After running the program the file will be created inside the bin folder in your compiler folder itself.
Initializing entire 2D array with one value
int array[ROW][COLUMN]={1};
This initialises only the first element to 1. Everything else gets a 0.
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
With a char
array you could use memset
to set every byte, but this will not generally work with an int
array (though it's fine for 0).
A general for
loop will do this quickly:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
How to create full path with node's fs.mkdirSync?
Based on mouneer's zero-dependencies answer, here's a slightly more beginner friendly Typescript
variant, as a module:
import * as fs from 'fs';
import * as path from 'path';
/**
* Recursively creates directories until `targetDir` is valid.
* @param targetDir target directory path to be created recursively.
* @param isRelative is the provided `targetDir` a relative path?
*/
export function mkdirRecursiveSync(targetDir: string, isRelative = false) {
const sep = path.sep;
const initDir = path.isAbsolute(targetDir) ? sep : '';
const baseDir = isRelative ? __dirname : '.';
targetDir.split(sep).reduce((prevDirPath, dirToCreate) => {
const curDirPathToCreate = path.resolve(baseDir, prevDirPath, dirToCreate);
try {
fs.mkdirSync(curDirPathToCreate);
} catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
// caught EEXIST error if curDirPathToCreate already existed (not a problem for us).
}
return curDirPathToCreate; // becomes prevDirPath on next call to reduce
}, initDir);
}
multiple axis in matplotlib with different scales
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
Sorting rows in a data table
Use LINQ - The beauty of C#
DataTable newDataTable = baseTable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ColumnName"))
.CopyToDataTable();
How can I open a website in my web browser using Python?
From the doc.
The webbrowser module provides a high-level interface to allow
displaying Web-based documents to users. Under most circumstances,
simply calling the open() function from this module will do the right
thing.
You have to import the module and use open()
function. This will open https://nabinkhadka.com.np in the browser.
To open in new tab:
import webbrowser
webbrowser.open('https://nabinkhadka.com.np', new = 2)
Also from the doc.
If new is 0, the url is opened in the same browser window if possible.
If new is 1, a new browser window is opened if possible. If new is 2,
a new browser page (“tab”) is opened if possible
So according to the value of new, you can either open page in same browser window or in new tab etc.
Also you can specify as which browser (chrome, firebox, etc.) to open. Use get() function for this.
Build fat static library (device + simulator) using Xcode and SDK 4+
IOS 10 Update:
I had a problem with building the fatlib with iphoneos10.0 because the regular expression in the script only expects 9.x and lower and returns 0.0 for ios 10.0
to fix this just replace
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '.\{3\}$')
with
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '[\\.0-9]\{3,4\}$')
javascript: optional first argument in function
Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:
if ( typeof content === "object" ) {
options = content;
content = null;
}
Or if you are confused with renaming, you can use the arguments array which can be more straightforward:
if ( arguments.length === 1 ) {
options = arguments[0];
content = null;
}
How can I get argv[] as int?
Basic usage
The "string to long" (strtol
) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Since we use the decimal system, base is 10. The endpointer
argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL
instead of passing a pointer, as shown.
Error checking (1)
If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0
is always the last character of a string in C:
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
Error checking (2)
As the man page mentions, you can use errno
to check that no errors occurred (in this case overflows or underflows).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
Convert to integer
So now we are stuck with this long
, but we often want to work with integers. To convert a long
into an int
, we should first check that the number is within the limited capacity of an int
. To do this, we add a second if-statement, and if it matches, we can just cast it.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
To see what happens if you don't do this check, test the code without the INT_MIN
/MAX
if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.
Full example
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
int main(int argc, char** argv) {
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
In Bash, you can test this with:
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
Using 2**31-1
, it should print the number and 0
, because 231-1 is just in range. If you pass 2**31
instead (without -1
), it will not print the number and the exit status will be 1
.
Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc
), test whether the number is in the range that you want, etc.
How to convert WebResponse.GetResponseStream return into a string?
As @Heinzi mentioned the character set of the response should be used.
var encoding = response.CharacterSet == ""
? Encoding.UTF8
: Encoding.GetEncoding(response.CharacterSet);
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream, encoding);
var responseString = reader.ReadToEnd();
}
Finding the 'type' of an input element
If you want to check the type of input within form, use the following code:
<script>
function getFind(obj) {
for (i = 0; i < obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == "INPUT") {
if (obj.childNodes[i].type == "text") {
alert("this is Text Box.")
}
if (obj.childNodes[i].type == "checkbox") {
alert("this is CheckBox.")
}
if (obj.childNodes[i].type == "radio") {
alert("this is Radio.")
}
}
if (obj.childNodes[i].tagName == "SELECT") {
alert("this is Select")
}
}
}
</script>
<script>
getFind(document.myform);
</script>
405 method not allowed Web API
I was getting the 405 on my GET call, and the problem turned out that I named the parameter in the GET server-side method Get(int formId)
, and I needed to change the route, or rename it Get(int id)
.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project
Remove
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
slf4j-log4j12
is the log4j binding for slf4j
you dont need to add another log4j dependency.
Added
Provide the log4j configuration in log4j.properties
and add it to your class path. There are sample configurations here
or you can change your binding to
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
if you are configuring slf4j due to some dependencies requiring it.
How to add minutes to my Date
This is incorrectly specified:
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm");
You're using minutes instead of month (MM)
How to Get the HTTP Post data in C#?
In the web browser, open up developer console (F12 in Chrome and IE), then open network tab and watch the request and response data. Another option - use Fiddler (http://fiddler2.com/).
When you get to see the POST request as it is being sent to your page, look into query string and headers. You will see whether your data comes in query string or as form - or maybe it is not being sent to your page at all.
UPDATE: sorry, had to look at MailGun APIs first, they do not go through your browser, requests come directly from their server. You'll have to debug and examine all members of Request.Params when you get the POST from MailGun.
Better way to set distance between flexbox items
I posted my flexbox approach
here:
One idea I rejected was to remove the padding from the outer columns with something like this:
div:nth-child(#{$col-number}n+1) { padding-left: 0; }
div:nth-child(#{$col-number}n+#{$col-number}) { padding-left: 0; }
But, like other posters here, I prefer the negative margin trick. My fiddle also has responsiveness for anyone is looking for a Sass-based solution. I basically use this approach in place of a grid.
https://jsfiddle.net/x3jvfrg1/
What are the differences between struct and class in C++?
The main difference between structure and class keyword in oops is that, no public and private member declaration present in structure.and the data member and member function can be defined as public, private as well as protected.
What does 'var that = this;' mean in JavaScript?
From Crockford
By convention, we make a private that
variable. This is used to make the
object available to the private
methods. This is a workaround for an
error in the ECMAScript Language
Specification which causes this to be
set incorrectly for inner functions.
JS Fiddle
function usesThis(name) {
this.myName = name;
function returnMe() {
return this; //scope is lost because of the inner function
}
return {
returnMe : returnMe
}
}
function usesThat(name) {
var that = this;
this.myName = name;
function returnMe() {
return that; //scope is baked in with 'that' to the "class"
}
return {
returnMe : returnMe
}
}
var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
"UsesThis thinks it's called " + usesthis.returnMe().myName);
This alerts...
UsesThat thinks it's called Dave
UsesThis thinks it's called undefined
What is an example of the simplest possible Socket.io example?
i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.
every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.
this just returns a string passed from the console UPPERCASED.
app.js
var http = require('http');
var app = http.createServer(function(req, res) {
console.log('createServer');
});
app.listen(3000);
var io = require('socket.io').listen(app);
io.on('connection', function(socket) {
io.emit('Server 2 Client Message', 'Welcome!' );
socket.on('Client 2 Server Message', function(message) {
console.log(message);
io.emit('Server 2 Client Message', message.toUpperCase() ); //upcase it
});
});
index.html:
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
<script type='text/javascript'>
var socket = io.connect(':3000');
// optionally use io('http://localhost:3000');
// but make *SURE* it matches the jScript src
socket.on ('Server 2 Client Message',
function(messageFromServer) {
console.log ('server said: ' + messageFromServer);
});
</script>
</head>
<body>
<h5>Worlds smallest Socket.io example to uppercase strings</h5>
<p>
<a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
<br />
socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
</p>
</body>
</html>
to run:
npm init; // accept defaults
npm install socket.io http --save ;
node app.js &
use something like this port test to ensure your port is open.
now browse to http://localhost/index.html and use your browser console to send messages back to the server.
at best guess, when using http.createServer, it changes the following two lines for you:
<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();
i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.
What is the usefulness of PUT and DELETE HTTP request methods?
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
Can you center a Button in RelativeLayout?
Arcadia, just try the code below. There are several ways to get the result you're looking for, this is one of the easier ways.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"/>
</RelativeLayout>
Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).
You could also use this code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"
android:layout_centerInParent="true"/>
</RelativeLayout>
What causes a TCP/IP reset (RST) flag to be sent?
A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...
One reason a device will send a RST is in response to receiving a packet for a closed socket.
It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)
How do I create a file and write to it?
Note that each of the code samples below may throw IOException
. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.
Note that each of the code samples below will overwrite the file if it already exists
Creating a text file:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file:
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+ users can use the Files
class to write to files:
Creating a text file:
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
Creating a binary file:
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?
Excel shows 24:03 as 3 minutes when you format it as time, because 24:03 is the same as 12:03 AM (in military time).
Use General Format to Add Times
Instead of trying to format as Time, use the General Format and the following formula:
=number of minutes + (number of seconds / 60)
Ex: for 24 minutes and 3 seconds:
=24+3/60
This will give you a value of 24.05.
Do this for each time period. Let's say you enter this formula in cells A1
and A2
. Then, to get the total sum of elapsed time, use this formula in cell A3
:
=INT(A1+A2)+MOD(A1+A2,1)
Convert back to minutes and seconds
If you put =24+3/60
into each cell, you will have a value of 48.1 in cell A3
.
Now you need to convert this back to minutes and seconds. Use the following formula in cell A4
:
=MOD(A3,1)*60
This takes the decimal portion and multiples it by 60. Remember, we divided by 60 in the beginning, so to convert it back to seconds we need to multiply.
You could have also done this separately, i.e. in cell A3 use this formula:
=INT(A1+A2)
and this formula in cell A4
:
=MOD(A1+A2,1)*60
Here's a screenshot showing the final formulas:
How can I delete one element from an array by value
I improved Niels's solution
class Array
def except(*values)
self - values
end
end
Now you can use
[1, 2, 3, 4].except(3, 4) # return [1, 2]
[1, 2, 3, 4].except(4) # return [1, 2, 3]
MySQL: When is Flush Privileges in MySQL really needed?
Just to give some examples. Let's say you modify the password for an user called 'alex'. You can modify this password in several ways. For instance:
mysql> update* user set password=PASSWORD('test!23') where user='alex';
mysql> flush privileges;
Here you used UPDATE. If you use INSERT, UPDATE or DELETE on grant tables directly you need use FLUSH PRIVILEGES in order to reload the grant tables.
Or you can modify the password like this:
mysql> set password for 'alex'@'localhost'= password('test!24');
Here it's not necesary to use "FLUSH PRIVILEGES;"
If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.
OnclientClick and OnClick is not working at the same time?
Your JavaScript is fine, unless you have other scripts running on this page which may corrupt everything. You may check this using Firebug.
I've now tested a bit and it really seems that ASP.net ignores disabled controls. Basically the postback is issued, but probably the framework ignores such events since it "assumes" that a disabled button cannot raise any postback and so it ignores possibly attached handlers. Now this is just my personal reasoning, one could use Reflector to check this in more depth.
As a solution you could really try to do the disabling at a later point, basically you delay the control.disabled = "disabled"
call using a JavaTimer or some other functionality. In this way 1st the postback to the server is issued before the control is being disabled by the JavaScript function. Didn't test this but it could work
Environment variable to control java.io.tmpdir?
If you look in the source code of the JDK, you can see that for unix systems the property is read at compile time from the paths.h or hard coded. For windows the function GetTempPathW
from win32 returns the tmpdir
name.
For posix systems you might expect the standard TMPDIR
to work, but that is not the case. You can confirm that TMPDIR
is not used by running TMPDIR=/mytmp java -XshowSettings
How to write a confusion matrix in Python?
This function creates confusion matrices for any number of classes.
def create_conf_matrix(expected, predicted, n_classes):
m = [[0] * n_classes for i in range(n_classes)]
for pred, exp in zip(predicted, expected):
m[pred][exp] += 1
return m
def calc_accuracy(conf_matrix):
t = sum(sum(l) for l in conf_matrix)
return sum(conf_matrix[i][i] for i in range(len(conf_matrix))) / t
In contrast to your function above, you have to extract the predicted classes before calling the function, based on your classification results, i.e. sth. like
[1 if p < .5 else 2 for p in classifications]
What is the difference between min SDK version/target SDK version vs. compile SDK version?
compileSdkVersion : The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device.
minSdkVersion : The min sdk version is the minimum version of the Android operating system required to run your application.
targetSdkVersion : The target sdk version is the version your app is targeted to run on.
Create line after text with css
using flexbox:
h2 {
display: flex;
align-items: center;
}
h2 span {
content:"";
flex: 1 1 auto;
border-top: 1px solid #000;
}
html:
<h2>Title <span></span></h2>
Effectively use async/await with ASP.NET Web API
I am not very sure whether it will make any difference in performance of my API.
Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async
" considerations in my article on async
ASP.NET.
I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.
As far as the code goes, this is not asynchronous:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
return Task.FromResult(response);
}
You'd need a truly asynchronous implementation to get the scalability benefits of async
:
public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Or (if your logic in this method really is just a pass-through):
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync
). Then let the async
trickle up, making your controller actions asynchronous as the last step.
And under no circumstances should you use Task.Run
in this scenario.
plot different color for different categorical levels using matplotlib
You can pass plt.scatter
a c
argument which will allow you to select the colors. The code below defines a colors
dictionary to map your diamond colors to the plotting colors.
import matplotlib.pyplot as plt
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
ax.scatter(df['carat'], df['price'], c=df['color'].apply(lambda x: colors[x]))
plt.show()
df['color'].apply(lambda x: colors[x])
effectively maps the colours from "diamond" to "plotting".
(Forgive me for not putting another example image up, I think 2 is enough :P)
With seaborn
You can use seaborn
which is a wrapper around matplotlib
that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions.
For this you could use seaborn.lmplot
with fit_reg=False
(which prevents it from automatically doing some regression).
The code below uses an example dataset. By selecting hue='color'
you tell seaborn to split your dataframe up based on your colours and then plot each one.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
sns.lmplot('carat', 'price', data=df, hue='color', fit_reg=False)
plt.show()
Without seaborn
using pandas.groupby
If you don't want to use seaborn then you can use pandas.groupby
to get the colors alone and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below:
fig, ax = plt.subplots()
colors = {'D':'red', 'E':'blue', 'F':'green', 'G':'black'}
grouped = df.groupby('color')
for key, group in grouped:
group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key])
plt.show()
This code assumes the same DataFrame as above and then groups it based on color
. It then iterates over these groups, plotting for each one. To select a color I've created a colors
dictionary which can map the diamond color (for instance D
) to a real color (for instance red
).
Need a good hex editor for Linux
I am a VIMer. I can do some rare Hex edits with:
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
- Supported file formats
- common object file format (COFF/XCOFF32)
- executable and linkable format (ELF)
- linear executables (LE)
- standard DO$ executables (MZ)
- new executables (NE)
- portable executables (PE32/PE64)
- java class files (CLASS)
- Mach exe/link format (MachO)
- X-Box executable (XBE)
- Flat (FLT)
- PowerPC executable format (PEF)
- Code & Data Analyser
- finds branch sources and destinations recursively
- finds procedure entries
- creates labels based on this information
- creates xref information
- allows to interactively analyse unexplored code
- allows to create/rename/delete labels
- allows to create/edit comments
- supports x86, ia64, alpha, ppc and java code
- Target systems
- DJGPP
- GNU/Linux
- FreeBSD
- OpenBSD
- Win32
How to ALTER multiple columns at once in SQL Server
We can alter multiple columns in a single query like this:
ALTER TABLE `tblcommodityOHLC`
CHANGE COLUMN `updated_on` `updated_on` DATETIME NULL DEFAULT NULL AFTER `updated_by`,
CHANGE COLUMN `delivery_datetime` `delivery_datetime` DATETIME NULL DEFAULT CURRENT_TIMESTAMP AFTER `delivery_status`;
Just give the queries as comma separated.