You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
if you are using gridview then you can show only the time with DataFormatString="{0:t}"
example:
By bind the value:-
<asp:Label ID="lblreg" runat="server" Text='<%#Eval("Registration_Time ", "{0:t}") %>'></asp:Label>
By bound filed:-
<asp:BoundField DataField=" Registration_Time" HeaderText="Brithday" SortExpression=" Registration Time " DataFormatString="{0:t}"/>
This has been answered before (although this question was first!):
"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
As URL class documentation states:
The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().
The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.
Basically:
String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());
will give you:
https://mywebsite/docs/english/site/mybook.do?request_type
Offering another potential solution to this error.
If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.
e.g.
https://example.com/api/etc
and not
https://123.4.5.6/api/etc
In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE
.
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
This will literally list (that is, print) all subdirectories. It basically is a loop kind of where you don’t need to store the items in between to a list. This is what one most likely needs, so I leave it here.
Path directory = Paths.get("D:\\directory\\to\\list");
Files.walk(directory, 1).filter(entry -> !entry.equals(directory))
.filter(Files::isDirectory).forEach(subdirectory ->
{
// do whatever you want with the subdirectories
System.out.println(subdirectory.getFileName());
});
I was cleaning up warnings and messages and see that VS does warn about it: Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
A Stacked bar chart should suffice:
Setup data as follows
Name Start End Duration (End - Start)
Fred 1/01/1981 1/06/1985 1612
Bill 1/07/1985 1/11/2000 5602
Joe 1/01/1980 1/12/2001 8005
Jim 1/03/1999 1/01/2000 306
Start
and Duration
as a stacked bar chartX-Axis minimum
to the desired start date Fill
Colour of thestart
range to no fill
Fill
of individual bars to suit(example prepared in Excel 2010)
Solve problem with two method parse common
public <T> T jsonToObject(String json, Class<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (Jsenter code hereonProcessingException e) {
e.printStackTrace();
}
return target;
}
public <T> T jsonToObject(String json, TypeReference<T> type) {
T target = null;
try {
target = objectMapper.readValue(json, type);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return target;
}
Because SQL Server performs integer division. Try this:
select 1 * 1.0 / 3
This is helpful when you pass integers as params.
select x * 1.0 / y
While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.
git branch -a --contains <commit>
This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.
If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:
git reflog show --all | grep a871742
to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:
a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite
indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.
git reflog show
is actually just an alias for git log -g --abbrev-commit --pretty=oneline
, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!
If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.
This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:
git log --merges <commit>..
to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.
If you want to be able to count on doing this, you may want to use the --no-ff
option to git merge
to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) VonC's answer to a related question helpfully elaborates on this topic.
Though I am using kotlin, the following code answered your question. This return selected item:
val item = myListView.adapter.getItem(i).toString()
The following is the whole selecteditem Listener
myListView.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
id: Long) {
val item = myListView.adapter.getItem(i).toString()
}
})
The code returns the item clicked by its index i as shown in the code
There are couple of different solutions to achieve this:
1 - Native javascript for-in loop:
const result = {};
let key;
for (key in obj1) {
if(obj1.hasOwnProperty(key)){
result[key] = obj1[key];
}
}
for (key in obj2) {
if(obj2.hasOwnProperty(key)){
result[key] = obj2[key];
}
}
2 - Object.keys()
:
const result = {};
Object.keys(obj1)
.forEach(key => result[key] = obj1[key]);
Object.keys(obj2)
.forEach(key => result[key] = obj2[key]);
3 - Object.assign()
:
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)
const result = Object.assign({}, obj1, obj2);
4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):
Defined in several sections of the specification: Array Initializer, Argument Lists
Using this new syntax you could join/merge different objects into one object like this:
const result = {
...obj1,
...obj2,
};
5 - jQuery.extend(target, obj1, obj2)
:
Merge the contents of two or more objects together into the first object.
const target = {};
$.extend(target, obj1, obj2);
6 - jQuery.extend(true, target, obj1, obj2)
:
Run a deep merge of the contents of two or more objects together into the target. Passing false
for the first argument is not supported.
const target = {};
$.extend(true, target, obj1, obj2);
7 - Lodash _.assignIn(object, [sources])
: also named as _.extend
:
const result = {};
_.assignIn(result, obj1, obj2);
8 - Lodash _.merge(object, [sources])
:
const result = _.merge(obj1, obj2);
There are a couple of important differences between lodash's merge function and Object.assign
:
1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign
only merges the first level. For instance:
_.isEqual(_.merge({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
}), {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // true
BUT:
const result = Object.assign({
x: {
y: { key1: 'value1' },
},
}, {
x: {
y: { key2: 'value2' },
},
});
_.isEqual(result, {
x: {
y: {
key1: 'value1',
key2: 'value2',
},
},
}); // false
// AND
_.isEqual(result, {
x: {
y: {
key2: 'value2',
},
},
}); // true
2- Another difference has to do with how Object.assign
and _.merge
interpret the undefined
value:
_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false
BUT:
_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true
Update 1:
When using for in
loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype
or even Object.prototype
.
To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key)
to mke sure the key is actually part of the object you are iterating over.
Update 2:
I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.
Update 3:
I added the difference between Object.assign
and _.merge
.
My suggestion, if you are still using const XXX = require('library or path./') when using module.exports to export multiple functions use an ES6 arrow function
for example:
module.exports = () => {
const getPosts = (req, res ) =>{
res.send('THIS WORKS!');
}
const getPost = async (req, res) => {
const { id } = req.params;
try {
const post = await PostMessage.findById(id);
res.status(200).json(post);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
}
then Import: const getPosts = require('../controllers/posts.js');
Hope this helps... Cheers! www.miyamotto.net
This worked for me:
.container {_x000D_
display: inline-flex;_x000D_
}_x000D_
_x000D_
.slide {_x000D_
float: left;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="slide">something1</div>_x000D_
<div class="slide">something2</div>_x000D_
<div class="slide">something3</div>_x000D_
<div class="slide">something4</div>_x000D_
</div>
_x000D_
You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus
See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
I'm using Version 12 of IntelliJ.
I solved a similar problem by creating an entirely new project and "Checking out from Version Control" Merging the two projects later was fairly easy.
Use parameters(seconds) i.e. youtube.com/v/VIDEO_ID?start=4&end=117
Live DEMO:
https://puvox.software/software/youtube_trimmer.php
Here is a script I used for recursive trimming. Replace $1 with the directory you want, of course.
BASEDIR="$1"
IFS=$'\n'
cd $BASEDIR
for f in $(find . -type f -name ' *')
do
DIR=$(dirname "$f")
DIR=${DIR:1}
cd $BASEDIR$DIR
rename 's/^ *//' *
done
No there isn't any collection that can contain primitive types when Java Collection Framework is being used.
However, there are other java collections which support primitive types, such as: Trove, Colt, Fastutil, Guava
An example of how an arraylist with ints would be when Trove Library used is the following:
TIntArrayList list= new TIntArrayList();
The performance of this list, when compared with the ArrayList of Integers from Java Collections is much better as the autoboxing/unboxing to the corresponding Integer Wrapper Class is not needed.
Got this example from cppreference. It works with:
GCC 10.1+ with flag -std=c++20
#include <ranges>
#include <iostream>
int main()
{
static constexpr auto il = {3, 1, 4, 1, 5, 9};
std::ranges::reverse_view rv {il};
for (int i : rv)
std::cout << i << ' ';
std::cout << '\n';
for(int i : il | std::views::reverse)
std::cout << i << ' ';
}
Here is my approach that you may try:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
The resulting image:
(Original answer date: Oct 7 '17 at 4:20)
Edit 1
Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-
New code:
import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5
# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# ax enables access to manipulate each of subplots
ax = []
for i in range(columns*rows):
img = np.random.randint(10, size=(h,w))
# create subplot and append to ax
ax.append( fig.add_subplot(rows, columns, i+1) )
ax[-1].set_title("ax:"+str(i)) # set title
plt.imshow(img, alpha=0.25)
# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)
plt.show() # finally, render the plot
The resulting plot:
Edit 2
In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index]
, which is more suitable for manipulation of array of many sub-plots.
import matplotlib.pyplot as plt
import numpy as np
# settings
h, w = 10, 10 # for raster image
nrows, ncols = 5, 4 # array of sub-plots
figsize = [6, 8] # figure size, inches
# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
# i runs from 0 to (nrows*ncols-1)
# axi is equivalent with ax[rowid][colid]
img = np.random.randint(10, size=(h,w))
axi.imshow(img, alpha=0.25)
# get indices of row/column
rowid = i // ncols
colid = i % ncols
# write row/col indices as axes' title for identification
axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))
# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)
plt.tight_layout(True)
plt.show()
The resulting plot:
another example:
request:
curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y
then:
request.method: GET
request.url: http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url: http://127.0.0.1:5000/alert/dingding/test
request.url_charset: utf-8
request.url_root: http://127.0.0.1:5000/
str(request.url_rule): /alert/dingding/test
request.host_url: http://127.0.0.1:5000/
request.host: 127.0.0.1:5000
request.script_root:
request.path: /alert/dingding/test
request.full_path: /alert/dingding/test?x=y
request.args: ImmutableMultiDict([('x', 'y')])
request.args.get('x'): y
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.
import useForceUpdate from 'use-force-update';
const MyButton = () => {
const forceUpdate = useForceUpdate();
const handleClick = () => {
alert('I will re-render now.');
forceUpdate();
};
return <button onClick={handleClick} />;
};
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
Adding this to your WebSecurityConfiguration class should do the trick.
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
Because I always struggle to remember, a quick summary of what each of these do:
>>> pd.Timestamp.now() # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.utcnow() # tz aware UTC
Timestamp('2019-10-07 08:30:19.428748+0000', tz='UTC')
>>> pd.Timestamp.now(tz='Europe/Brussels') # tz aware local time
Timestamp('2019-10-07 10:30:19.428748+0200', tz='Europe/Brussels')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_localize(None) # naive local time
Timestamp('2019-10-07 10:30:19.428748')
>>> pd.Timestamp.now(tz='Europe/Brussels').tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_localize(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
>>> pd.Timestamp.utcnow().tz_convert(None) # naive UTC
Timestamp('2019-10-07 08:30:19.428748')
I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...
Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.
Try using XAMPP Control panel "Admin" button instead of usual http://localhost
or http://localhost/phpmyadmin
Try direct link: http://localhost/phpmyadmin/main.php
or http://127.0.0.1/phpmyadmin/main.php
Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php
Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.
If this solution helped let me know.
This is the one that worked for my case on my current machine (git bash on windows 7):
find ./ -type f -iname "*.cs" -print0 | xargs -0 grep "content pattern"
I always forget the -print0 and -0 for paths with spaces.
EDIT: My preferred tool is now instead ripgrep: https://github.com/BurntSushi/ripgrep/releases . It's really fast and has better defaults (like recursive by default). Same example as my original answer but using ripgrep: rg -g "*.cs" "content pattern"
Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....
Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"
SELECT ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
So you need to add the extra "where in" clause:
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
Also:
For ease of reading if you want to indicate the table names you can use the following:
SELECT tbl, ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
This is with jQuery.
$('#selectFormElement').change( function() {
$('#hiddenFormElement').val('newValue');
} );
In the html
<select id="selectFormElement" name="..."> ... </select>
<input type="hidden" name="..." id="hiddenFormElement" />
I know this thread is old now but I am answering it to keep things a bit updated.
With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit
parameter also accepts a begin
parameter.
Usage: {{ limitTo_expression | limitTo : limit : begin}}
So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
You are looking for a simple code, like this:
List<string> tagList = new List<string>(new[]
{
"A"
,"B"
,"C"
,"D"
,"E"
});
For myself, I'd start with dumping both databases and diffing the dumps, but if you want automatically generated merge scripts, you're going to want to get a real tool.
A simple Google search turned up the following tools:
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
Heads up, if clearing the settings doesn't fix your issue you may need to uninstall the extensions as well.
I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:
EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):
def label_bars(ax, bars, text_format, **kwargs):
"""
Attaches a label on every bar of a regular or horizontal bar chart
"""
ys = [bar.get_y() for bar in bars]
y_is_constant = all(y == ys[0] for y in ys) # -> regular bar chart, since all all bars start on the same y level (0)
if y_is_constant:
_label_bar(ax, bars, text_format, **kwargs)
else:
_label_barh(ax, bars, text_format, **kwargs)
def _label_bar(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
"""
max_y_value = ax.get_ylim()[1]
inside_distance = max_y_value * 0.05
outside_distance = max_y_value * 0.01
for bar in bars:
text = text_format.format(bar.get_height())
text_x = bar.get_x() + bar.get_width() / 2
is_inside = bar.get_height() >= max_y_value * 0.15
if is_inside:
color = "white"
text_y = bar.get_height() - inside_distance
else:
color = "black"
text_y = bar.get_height() + outside_distance
ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)
def _label_barh(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
Note: label always outside. otherwise it's too hard to control as numbers can be very long
"""
max_x_value = ax.get_xlim()[1]
distance = max_x_value * 0.0025
for bar in bars:
text = text_format.format(bar.get_width())
text_x = bar.get_width() + distance
text_y = bar.get_y() + bar.get_height() / 2
ax.text(text_x, text_y, text, va='center', **kwargs)
Now you can use them for regular bar plots:
fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)
or for horizontal bar plots:
fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
I've been thinking of Monads in a different way, lately. I've been thinking of them as abstracting out execution order in a mathematical way, which makes new kinds of polymorphism possible.
If you're using an imperative language, and you write some expressions in order, the code ALWAYS runs exactly in that order.
And in the simple case, when you use a monad, it feels the same -- you define a list of expressions that happen in order. Except that, depending on which monad you use, your code might run in order (like in IO monad), in parallel over several items at once (like in the List monad), it might halt partway through (like in the Maybe monad), it might pause partway through to be resumed later (like in a Resumption monad), it might rewind and start from the beginning (like in a Transaction monad), or it might rewind partway to try other options (like in a Logic monad).
And because monads are polymorphic, it's possible to run the same code in different monads, depending on your needs.
Plus, in some cases, it's possible to combine monads together (with monad transformers) to get multiple features at the same time.
This works for me:
@Entity(tableName = "note_table")
data class Note(
@ColumnInfo(name="title") var title: String,
@ColumnInfo(name="description") var description: String = "",
@ColumnInfo(name="priority") var priority: Int,
@PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
)
Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.
You can Use this for Curl:
function fakeip()
{
return long2ip( mt_rand(0, 65537) * mt_rand(0, 65535) );
}
function getdata($url,$args=false)
{
global $session;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".fakeip(),"X-Client-IP: ".fakeip(),"Client-IP: ".fakeip(),"HTTP_X_FORWARDED_FOR: ".fakeip(),"X-Forwarded-For: ".fakeip()));
if($args)
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$args);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:8888");
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
Then To Read Json:
$result=getdata("https://example.com");
Then :
///Deocde Json
$data = json_decode($result,true);
///Count
$total=count($data);
$Str='<h1>Total : '.$total.'';
echo $Str;
//You Can Also Make In Table:
foreach ($data as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
}
You Can Also Use This:
echo '<p>Name : '.$data['result']['name'].'</p>
<img src="'.$data['result']['pic'].'"><br>';
Hope this helped.
You could also use the className
property of the element's DOM object:
var $hello = $('#hello');
$('#hello').attr('class', $hello.get(0).className.replace(/\bcolor-\S+/g, ''));
Here is Oliver Steele's image of how it all fits together:
Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)
Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.
It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.
You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.
So go with what your data structures book said!
Edit:
Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.
This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)
I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.
select a.latitude from (SELECT lat AS latitude FROM poi_table) a where latitude < 500
Or better
window.location.assign("relative or absolute address");
that tends to work best across all browsers and mobile
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful.
There are still bugs in mine, but if anyone wants it, here it is.
So in short, if you are looking for a speed gain, then MySQLi; if you want ease of use, then PDO.
.NET 4.0 and above:
using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);
I found many answers but not one is simple... I hope this will help you...
try{
Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
startActivity(intent);
} finally {
finish();
}
so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.
Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values
Backup over ssh with password using temporary .pgpass credentials and push to S3:
#!/usr/bin/env bash
cd "$(dirname "$0")"
DB_HOST="*******.*********.us-west-2.rds.amazonaws.com"
DB_USER="*******"
SSH_HOST="[email protected]_domain.com"
BUCKET_PATH="bucket_name/backup"
if [ $# -ne 2 ]; then
echo "Error: 2 arguments required"
echo "Usage:"
echo " my-backup-script.sh <DB-name> <password>"
echo " <DB-name> = The name of the DB to backup"
echo " <password> = The DB password, which is also used for GPG encryption of the backup file"
echo "Example:"
echo " my-backup-script.sh my_db my_password"
exit 1
fi
DATABASE=$1
PASSWORD=$2
echo "set remote PG password .."
echo "$DB_HOST:5432:$DATABASE:$DB_USER:$PASSWORD" | ssh "$SSH_HOST" "cat > ~/.pgpass; chmod 0600 ~/.pgpass"
echo "backup over SSH and gzip the backup .."
ssh "$SSH_HOST" "pg_dump -U $DB_USER -h $DB_HOST -C --column-inserts $DATABASE" | gzip > ./tmp.gz
echo "unset remote PG password .."
echo "*********" | ssh "$SSH_HOST" "cat > ~/.pgpass"
echo "encrypt the backup .."
gpg --batch --passphrase "$PASSWORD" --cipher-algo AES256 --compression-algo BZIP2 -co "$DATABASE.sql.gz.gpg" ./tmp.gz
# Backing up to AWS obviously requires having your credentials to be set locally
# EC2 instances can use instance permissions to push files to S3
DATETIME=`date "+%Y%m%d-%H%M%S"`
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/"$DATETIME".sql.gz.gpg
# s3 is cheap, so don't worry about a little temporary duplication here
# "latest" is always good to have because it makes it easier for dev-ops to use
aws s3 cp ./"$DATABASE.sql.gz.gpg" s3://"$BUCKET_PATH"/"$DATABASE"/db/latest.sql.gz.gpg
echo "local clean-up .."
rm ./tmp.gz
rm "$DATABASE.sql.gz.gpg"
echo "-----------------------"
echo "To decrypt and extract:"
echo "-----------------------"
echo "gpg -d ./$DATABASE.sql.gz.gpg | gunzip > tmp.sql"
echo
Just substitute the first couple of config lines with whatever you need - obviously. For those not interested in the S3 backup part, take it out - obviously.
This script deletes the credentials in .pgpass
afterward because in some environments, the default SSH user can sudo without a password, for example an EC2 instance with the ubuntu
user, so using .pgpass
with a different host account in order to secure those credential, might be pointless.
In the current version of select2
you just need to add the attribute data-placeholder="A NICE PLACEHOLDER"
. select2
will automatically assign the placeholder.
Please note: adding an empty <option></option>
inside the select is still mandatory.
<input type="file" id="image_control" (change)="validateFile($event)" accept="image/gif, image/jpeg, image/png" />
validateFile(event: any): void {
const self = this;
if (event.target.files.length === 1) {
event.srcElement.value = null;
}
}
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:
public enum BrowserEmulationVersion
{
Default = 0,
Version7 = 7000,
Version8 = 8000,
Version8Standards = 8888,
Version9 = 9000,
Version9Standards = 9999,
Version10 = 10000,
Version10Standards = 10001,
Version11 = 11000,
Version11Edge = 11001
}
public static class WBEmulator
{
private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";
public static int GetInternetExplorerMajorVersion()
{
int result;
result = 0;
try
{
RegistryKey key;
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);
if (key != null)
{
object value;
value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);
if (value != null)
{
string version;
int separator;
version = value.ToString();
separator = version.IndexOf('.');
if (separator != -1)
{
int.TryParse(version.Substring(0, separator), out result);
}
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
public static BrowserEmulationVersion GetBrowserEmulationVersion()
{
BrowserEmulationVersion result;
result = BrowserEmulationVersion.Default;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
object value;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
value = key.GetValue(programName, null);
if (value != null)
{
result = (BrowserEmulationVersion)Convert.ToInt32(value);
}
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
{
bool result;
result = false;
try
{
RegistryKey key;
key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
if (key != null)
{
string programName;
programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
if (browserEmulationVersion != BrowserEmulationVersion.Default)
{
// if it's a valid value, update or create the value
key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
}
else
{
// otherwise, remove the existing value
key.DeleteValue(programName, false);
}
result = true;
}
}
catch (SecurityException)
{
// The user does not have the permissions required to read from the registry key.
}
catch (UnauthorizedAccessException)
{
// The user does not have the necessary registry rights.
}
return result;
}
public static bool SetBrowserEmulationVersion()
{
int ieVersion;
BrowserEmulationVersion emulationCode;
ieVersion = GetInternetExplorerMajorVersion();
if (ieVersion >= 11)
{
emulationCode = BrowserEmulationVersion.Version11;
}
else
{
switch (ieVersion)
{
case 10:
emulationCode = BrowserEmulationVersion.Version10;
break;
case 9:
emulationCode = BrowserEmulationVersion.Version9;
break;
case 8:
emulationCode = BrowserEmulationVersion.Version8;
break;
default:
emulationCode = BrowserEmulationVersion.Version7;
break;
}
}
return SetBrowserEmulationVersion(emulationCode);
}
public static bool IsBrowserEmulationSet()
{
return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
}
}
You just need to create a class and put this code in it, then run the following code when the program starts:
if (!WBEmulator.IsBrowserEmulationSet())
{
WBEmulator.SetBrowserEmulationVersion();
}
VB.NET:
Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks
Public Enum BrowserEmulationVersion
[Default] = 0
Version7 = 7000
Version8 = 8000
Version8Standards = 8888
Version9 = 9000
Version9Standards = 9999
Version10 = 10000
Version10Standards = 10001
Version11 = 11000
Version11Edge = 11001
End Enum
Public Class WBEmulator
Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
Public Shared Function GetInternetExplorerMajorVersion() As Integer
Dim result As Integer
result = 0
Try
Dim key As RegistryKey
key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
If key IsNot Nothing Then
Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))
Dim Version As String
Dim separator As Integer
Version = value.ToString()
separator = Version.IndexOf(".")
If separator <> -1 Then
Integer.TryParse(Version.Substring(0, separator), result)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetInternetExplorerMajorVersion = result
End Function
Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"
Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion
Dim result As BrowserEmulationVersion
result = BrowserEmulationVersion.Default
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String
Dim value As Object
programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
value = key.GetValue(programName, Nothing)
If value IsNot Nothing Then
result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
End If
End If
Catch ex As SecurityException
'The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
'The user does Not have the necessary registry rights.
Catch
End Try
GetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean
Dim result As Boolean = False
Try
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
If key IsNot Nothing Then
Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
If BEVersion <> BrowserEmulationVersion.Default Then
'if it's a valid value, update or create the value
key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
Else
'otherwise, remove the existing value
key.DeleteValue(programName, False)
End If
result = True
End If
Catch ex As SecurityException
' The user does Not have the permissions required to read from the registry key.
Catch ex As UnauthorizedAccessException
' The user does Not have the necessary registry rights.
End Try
SetBrowserEmulationVersion = result
End Function
Public Shared Function SetBrowserEmulationVersion() As Boolean
Dim ieVersion As Integer
Dim emulationCode As BrowserEmulationVersion
ieVersion = GetInternetExplorerMajorVersion()
If ieVersion >= 11 Then
emulationCode = BrowserEmulationVersion.Version11
Else
Select Case ieVersion
Case 10
emulationCode = BrowserEmulationVersion.Version10
Case 9
emulationCode = BrowserEmulationVersion.Version9
Case 8
emulationCode = BrowserEmulationVersion.Version8
Case Else
emulationCode = BrowserEmulationVersion.Version7
End Select
End If
SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
End Function
Public Shared Function IsBrowserEmulationSet() As Boolean
IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
End Function
End Class
You may use it like:
If Not WBEmulator.IsBrowserEmulationSet() Then
WBEmulator.SetBrowserEmulationVersion()
End If
If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution
var Iframe = React.createClass({
render: function() {
return(
<div>
<iframe src={this.props.src} height={this.props.height} width={this.props.width}/>
</div>
)
}
});
ReactDOM.render(
<Iframe src="http://plnkr.co/" height="500" width="500"/>,
document.getElementById('example')
);
here live demo is available Demo
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
in the below method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (([array count]*65) > [UIScreen mainScreen].bounds.size.height - 66)
{
Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [array count]*65));
}
else
{
Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 66);
}
return [array count];
}
here 65 is the height of the cell and 66 is the height of the navigation bar in UIViewController.
By default .
(any character) does not match newline characters.
This means you can simply match zero or more of any character then append the end tag.
Find: <li><a href="#">.*
Replace: $0</a>
Consider the following example to solve your problem:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys, time, signal
def termination_handler (signum,frame):
global running
global pidfile
print 'You have requested to terminate the application...'
sys.stdout.flush()
running = 0
os.unlink(pidfile)
running = 1
signal.signal(signal.SIGINT,termination_handler)
pid = str(os.getpid())
pidfile = '/tmp/'+os.path.basename(__file__).split('.')[0]+'.pid'
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
else:
file(pidfile, 'w').write(pid)
# Do some actual work here
while running:
time.sleep(10)
I suggest this script because it can be executed one time only.
Android's permission system is one of the biggest security concern all along since those permissions are asked for at install time. Once installed, the application will be able to access all of things granted without any user's acknowledgement what exactly application does with the permission.
Android 6.0 Marshmallow introduces one of the largest changes to the permissions model with the addition of runtime permissions, a new permission model that replaces the existing install time permissions model when you target API 23 and the app is running on an Android 6.0+ device
Courtesy goes to Requesting Permissions at Run Time .
Example
Declare this as Global
private static final int PERMISSION_REQUEST_CODE = 1;
Add this in your onCreate()
section
After setContentView(R.layout.your_xml);
if (Build.VERSION.SDK_INT >= 23)
{
if (checkPermission())
{
// Code for above or equal 23 API Oriented Device
// Your Permission granted already .Do next code
} else {
requestPermission(); // Code for permission
}
}
else
{
// Code for Below 23 API Oriented Device
// Do next code
}
Now adding checkPermission() and requestPermission()
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(Your_Activity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Your_Activity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
This interface is the contract for receiving the results for permission requests.
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
eg1:
director:Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class
operate:checkout ???
eg2:
1.impl class add @service
like this:
@Service
public class CityServiceImpl implements CityService{
@Autowired
private CityDao cityDao;
like this
2.dao file class add @Repository
@Repository
public interface CityDao {
This will also work on iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
Use D. See docs for further information.
You need to do type assertion for converting your interface{} to int value.
iAreaId := val.(int)
iAreaId, ok := val.(int)
More information is available.
Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print
directly, or use logging
instead.
print >>sys.stderr, 'Goodbye, cruel world!'
Don't use document.write, here is workaround:
var script = document.createElement('script');
script.src = "....";
document.head.appendChild(script);
To convert this bytesarray directly to json, you could first convert the bytesarray to a string with decode(), utf-8 is standard. Change the quotation markers.. The last step is to remove the " from the dumped string, to change the json object from string to list.
dumps(s.decode()).replace("'", '"')[1:-1]
If your goal is to have
str = "Hello\nWorld";
and output what it contains in string literal form, you can use JSON.stringify
:
console.log(JSON.stringify(str)); // ""Hello\nWorld""
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
console.log
adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).
JSON.stringify
takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("
), the word Hello
, a backslash (\
), the letter n
, the word World
, and the closing quote ("
). The linefeed in the string is escaped in the output as a \
and an n
because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.
I was looking for an answer to this question and later I developed a method! :) A fair warning, it's rounding up the value.
private float limitDigits(float number) {
return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}
One simple way can be the use of assign()
function that is pre-defined in vector
class.
e.g.
array[5]={1,2,3,4,5};
vector<int> v;
v.assign(array, array+5); // 5 is size of array.
Do you have _timestamp enabled in your doc mapping?
{
"doctype": {
"_timestamp": {
"enabled": "true",
"store": "yes"
},
"properties": {
...
}
}
}
You can check your mapping here:
http://localhost:9200/_all/_mapping
If so I think this might work to get most recent:
{
"query": {
"match_all": {}
},
"size": 1,
"sort": [
{
"_timestamp": {
"order": "desc"
}
}
]
}
You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go
The "break" command does not work within an "if" statement.
If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.
"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).
If you want to revert the element to the source position if it's not dropped inside a #droppable
element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable
, then just restore the parent of #draggable
to this original element.
So, replace this:
}).each(function() {
var top = $(this).position().top;
var left = $(this).position().left;
$(this).data('orgTop', top);
$(this).data('orgLeft', left);
});
with this:
}).each(function() {
$(this).data('originalParent', $(this).parent())
});
Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.
drop
is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup
event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable
element, is revert
, and you're doing it right now, so, just delete the drop
callback.
When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert
with a fragment of code that: restores the parent element to the original div, and resets the originalPosition
from the draggable
internals. The originalPosition
proeprty is setted at the time of _mouseStart
, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}
, making the animation go to the origin point of the element:
revert: function(dropped) {
var dropped = dropped && dropped[0].id == "droppable";
if(!dropped) {
$(this).data("draggable").originalPosition = {top:0, left:0}
$(this).appendTo($(this).data('originalParent'))
}
return !dropped;
}
And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/
Take into consideration that, if in any jQuery's UI update, the behavior of revert
or originalPosition
changes, you'll need to update your code in order to make it work. Keep in mind that.
If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body
an droppable element with greedy
option defined as false
. You'll have to make sure that your body
elements take the full screen.
Good luck!
You need to set the NTAuthenticationProviders to NTLM
MSDN Article: https://msdn.microsoft.com/en-us/library/ee248703(VS.90).aspx
IIS Command-line (http://msdn.microsoft.com/en-us/library/ms525006(v=vs.90).aspx):
cscript adsutil.vbs set w3svc/WebSiteValueData/root/NTAuthenticationProviders "NTLM"
My DataGridView is also bound to a DataSource and myDataGridView.Columns.Clear()
worked fine but myDataGridView.Rows.Clear()
did NOT. Just an FYI for those who have tried .Rows
.
var value = "" + 5 + 6;
alert(value);
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
NO, you can't do it other way than so.
Would a dataframe of NA
s work?
something like:
data.frame(matrix(NA, nrow = 2, ncol = 3))
if you need to be more specific about the data type then may prefer: NA_integer_
, NA_real_
, NA_complex_
, or NA_character_
instead of just NA
which is logical
Something else that may be more specific that the NAs
is:
data.frame(matrix(vector(mode = 'numeric',length = 6), nrow = 2, ncol = 3))
where the mode can be of any type. See ?vector
another way can be adding the process to thethread queue pool
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=cpus) as executor:
for i in range(10):
a = executor.submit(arg1, arg2,....)
Personally I would use something like mplayer with the audio pass though option eg -oac copy
For windows system
Open putty
then login in server
If you want to see screen in Console then you have to write command
Screen -ls
if you have to access the screen then you have to use below command
screen -x screen id
Write PWD
in command line to check at which folder you are currently
We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this
<add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
Changing that from ./ to either (local) or localhost fixed the problem.
<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
textBox1.Text = "Line1" + Environment.NewLine + "Line2";
Also the markup needs to include TextMode="MultiLine" (otherwise it shows text as one line)
<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>
Single line result:
base64 -w 0 DSC_0251.JPG
For HTML
:
echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
As file:
base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64
In variable:
IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"
In variable for HTML
:
IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
Get you readable data back:
base64 -d DSC_0251.base64 > DSC_0251.JPG
View -> Show Symbol -> uncheck Show All characters
Here an alternative using SUBSTRING
SELECT
SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
FROM
[Fields]
The above answer doesn't support observable interpolation (and cost me a lot of time trying to debug). The jsFiddle link in @BrandonTilley comment was the answer that worked for me, which I'll re-post here for preservation:
app.directive('backImg', function(){
return function(scope, element, attrs){
attrs.$observe('backImg', function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
});
Example using controller and template
Controller :
$scope.someID = ...;
/*
The advantage of using directive will also work inside an ng-repeat :
someID can be inside an array of ID's
*/
$scope.arrayOfIDs = [0,1,2,3];
Template :
Use in template like so :
<div back-img="img/service-sliders/{{someID}}/1.jpg"></div>
or like so :
<div ng-repeat="someID in arrayOfIDs" back-img="img/service-sliders/{{someID}}/1.jpg"></div>
#header2
{
display: table-cell;
vertical-align: bottom;
background-color:Red;
}
<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
<p>this is a test</p>
</div>
</div>
Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...
Here is an example where a TextView is displayed on top of an ImageView:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
</FrameLayout>
You need to set a few extra flags so that curl sends the data as JSON.
$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url
-H
: custom header, next argument is expected to be header-X
: custom HTTP verb, next argument is expected to be verb-d
: sends the next argument as data in an HTTP POST requestThere are some different way to do that
sass --watch --style=compressed main.scss main.css
or
sass --watch a.scss:a.css --style compressed
or
By Using visual studio code extension live sass compiler
You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.
<script>
var to_check=$(this).val();
var cur_string=$("#0").text();
var to_chk = "that";
var cur_str= "that";
if(to_chk.localeCompare(cur_str) == 0){
alert("both are equal");
$("#0").attr("class","correct");
} else {
alert("both are not equal");
$("#0").attr("class","incorrect");
}
</script>
Now you can use insertOne method and in promise's result.insertedId
Change $_POST to $_FILES and make sure your enctype is "multipart/form-data"
Is your input field actually in a form?
<form method="POST" action="update.php">
<input type="hidden" name="filename" value="test" />
</form>
Somewhat easy to make add or remove HTML5 validation to fieldsets.
$('form').each(function(){
// CLEAR OUT ALL THE HTML5 REQUIRED ATTRS
$(this).find('.required').attr('required', false);
// ADD THEM BACK TO THE CURRENT FIELDSET
// I'M JUST USING A CLASS TO IDENTIFY REQUIRED FIELDS
$(this).find('fieldset.current .required').attr('required', true);
$(this).submit(function(){
var current = $(this).find('fieldset.current')
var next = $(current).next()
// MOVE THE CURRENT MARKER
$(current).removeClass('current');
$(next).addClass('current');
// ADD THE REQUIRED TAGS TO THE NEXT PART
// NO NEED TO REMOVE THE OLD ONES
// SINCE THEY SHOULD BE FILLED OUT CORRECTLY
$(next).find('.required').attr('required', true);
});
});
Try this method:
public static Dictionary<string, string> ParseIniDataWithSections(string[] iniData)
{
var dict = new Dictionary<string, string>();
var rows = iniData.Where(t =>
!String.IsNullOrEmpty(t.Trim()) && !t.StartsWith(";") && (t.Contains('[') || t.Contains('=')));
if (rows == null || rows.Count() == 0) return dict;
string section = "";
foreach (string row in rows)
{
string rw = row.TrimStart();
if (rw.StartsWith("["))
section = rw.TrimStart('[').TrimEnd(']');
else
{
int index = rw.IndexOf('=');
dict[section + "-" + rw.Substring(0, index).Trim()] = rw.Substring(index+1).Trim().Trim('"');
}
}
return dict;
}
It creates the dictionary where the key is "-". You can load it like this:
var dict = ParseIniDataWithSections(File.ReadAllLines(fileName));
Instead using border
use box-shadow
:
box-shadow:
2px 0 0 0 #888,
0 2px 0 0 #888,
2px 2px 0 0 #888, /* Just to fix the corner */
2px 0 0 0 #888 inset,
0 2px 0 0 #888 inset;
Since you're running Ubuntu, your system crontab is located at /etc/crontab
.
As the root user (or using sudo), you can simply edit this file and specify the user that should run this command. Here is the format of entries in the system crontab and how you should enter your command:
# m h dom mon dow user command
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1
Of course the permissions for your php script and your log file should be set so that the www-data
user has access to them.
jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */})
then your code will be run every time the window is resized.
So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.
// This function positions the footer based on window size
function positionFooter(){
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
else {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
$(document).ready(function () {
positionFooter();//run when page first loads
});
$(window).resize(function () {
positionFooter();//run on every window resize
});
See: Cross-browser window resize event - JavaScript / jQuery
This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter
in a handy way.
I tried to find an elegant way to inject MessageConverter
into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.
I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.
This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor
. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.
public class MessageProcessor { // Any name you like
// List of HttpMessageConverter
private List<HttpMessageConverter<?>> messageConverters;
// under org.springframework.web.servlet.mvc.method.annotation
private RequestResponseBodyMethodProcessor processor;
/**
* Below class name are copied from the framework.
* (And yes, they are hard-coded, too)
*/
private static final boolean jaxb2Present =
ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());
private static final boolean gsonPresent =
ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());
public MessageProcessor() {
this.messageConverters = new ArrayList<HttpMessageConverter<?>>();
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter());
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
}
/**
* This method will convert the response body to the desire format.
*/
public void handle(Object returnValue, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
}
/**
* @return list of message converters
*/
public List<HttpMessageConverter<?>> getMessageConverters() {
return messageConverters;
}
}
As in many tutorials, this class is essential to implement custom error handling.
public class CustomEntryPoint implements AuthenticationEntryPoint {
// The class from Step 1
private MessageProcessor processor;
public CustomEntryPoint() {
// It is up to you to decide when to instantiate
processor = new MessageProcessor();
}
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
// This object is just like the model class,
// the processor will convert it to appropriate format in response body
CustomExceptionObject returnValue = new CustomExceptionObject();
try {
processor.handle(returnValue, request, response);
} catch (Exception e) {
throw new ServletException();
}
}
}
As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
}
}
Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.
I tried about three different ways of intercepting the construction of the Ajax object:
xhrFields
, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste. progress
function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise). ajax
with my own. The only potential shortcoming is you can no longer use your own xhr()
setting. You can allow for that by checking to see whether options.xhr
is a function.I actually call my promise.progress
function xhrProgress
so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.
(function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
{
var $originalAjax = jQuery.ajax;
jQuery.ajax = function( url, options )
{
if( typeof( url ) === 'object' )
{options = url;url = undefined;}
options = options || {};
// Instantiate our own.
var xmlHttpReq = $.ajaxSettings.xhr();
// Make it use our own.
options.xhr = function()
{return( xmlHttpReq );};
var $newDeferred = $.Deferred();
var $oldPromise = $originalAjax( url, options )
.done( function done_wrapper( response, text_status, jqXHR )
{return( $newDeferred.resolveWith( this, arguments ));})
.fail( function fail_wrapper( jqXHR, text_status, error )
{return( $newDeferred.rejectWith( this, arguments ));})
.progress( function progress_wrapper()
{
window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
return( $newDeferred.notifyWith( this, arguments ));
});
var $newPromise = $newDeferred.promise();
// Extend our own.
$newPromise.progress = function( handler )
{
xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
{
//window.console.debug( "download_progress", evt );
handler.apply( this, [evt]);
}, false );
xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
{
//window.console.debug( "upload_progress", evt );
handler.apply( this, [evt]);
}, false );
return( this );
};
return( $newPromise );
};
})( window, jQuery );
$name = $_POST['name'];
$email = $_POST['email'];
$reciver = '/* Reciver Email address */';
if (filter_var($reciver, FILTER_VALIDATE_EMAIL)) {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' . $email. "\r\n"; // Sender's Email
//$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
$template = '<div style="padding:50px; color:white;">Hello ,<br/>'
. '<br/><br/>'
. 'Name:' .$name.'<br/>'
. 'Email:' .$email.'<br/>'
. '<br/>'
. '</div>';
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail($reciver, $subject, $sendmessage, $headers);
echo "Your Query has been received, We will contact you soon.";
} else {
echo "<span>* invalid email *</span>";
}
Yes you can. Assume a process foo
is running...
ps -elf | grep foo look for the PID number gdb -a {PID number}
After digging a bit through the perlre docs a bit, I'll present my best suggestion so far that seems to work pretty good. Perl 5.10 added the \R character class as a generalized linebreak:
$line =~ s/\R//g;
It's the same as:
(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])
I'll keep this question open a while yet, just to see if there's more nifty ways waiting to be suggested.
I had the same issue on a Test Project that had reference to an MVC 5 project. This happened after I merged with an MVC 5 project. I fixed it by installing Visual studio 2012 updates as explained here in Andre's response.
check your image cmd
using the command docker inspect image_name
. The output might be like this:
"Cmd": [
"/bin/bash",
"-c",
"#(nop) ",
"CMD [\"/bin/bash\"]"
],
So use the command docker exec -it container_id /bin/bash
. If your cmd
output is different like this:
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"/bin/sh\"]"
],
Use /bin/sh
instead of /bin/bash
in the command above.
For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task
class and TaskStatus
enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.
In the context of methods marked as async
, the resulting Task
is not a Task
representing the execution of the method, but a Task
for the continuation of the method.
This is only able to make use of a few possible states:
I understand that Running
could appear to have been a better default than WaitingForActivation
, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await
-ing something else). The other option may have been to add a new value to TaskStatus
, however this could have been a breaking change for existing applications and libraries.
All of this is very different to when making use of Task.Run
which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus
enumeration.
If you wish to keep track of the status of an async method, take a look at the IProgress(T)
interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T)
interface.
make clean
generally only cleans built files in the directory containing the source code itself, and rarely touches any installed software.
Makefiles generally don't contain a target for uninstallation -- you usually have to do that yourself, by removing the files from the directory into which they were installed. For example, if you built a program and installed it (using make install
) into /usr/local
, you'd want to look through /usr/local/bin
, /usr/local/libexec
, /usr/local/share/man
, etc., and remove the unwanted files. Sometimes a Makefile includes an uninstall
target, but not always.
Of course, typically on a Linux system you install software using a package manager, which is capable of uninstalling software "automagically".
I've created this query:
SELECT
db.name AS [Database Name],
mf.name AS [Logical Name],
mf.type_desc AS [File Type],
mf.physical_name AS [Path],
CAST(
(mf.Size * 8
) / 1024.0 AS DECIMAL(18, 1)) AS [Initial Size (MB)],
'By '+IIF(
mf.is_percent_growth = 1, CAST(mf.growth AS VARCHAR(10))+'%', CONVERT(VARCHAR(30), CAST(
(mf.growth * 8
) / 1024.0 AS DECIMAL(18, 1)))+' MB') AS [Autogrowth],
IIF(mf.max_size = 0, 'No growth is allowed', IIF(mf.max_size = -1, 'Unlimited', CAST(
(
CAST(mf.max_size AS BIGINT) * 8
) / 1024 AS VARCHAR(30))+' MB')) AS [MaximumSize]
FROM
sys.master_files AS mf
INNER JOIN sys.databases AS db ON
db.database_id = mf.database_id
NaN
means "Not a number." It's a special floating point value that means that the result of an operation was not defined or not representable as a real number.
See here for more explanation of this value.
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
Run this code, it will fetch data from file and display in console
function fileread(filename)
{
var contents= fs.readFileSync(filename);
return contents;
}
var fs =require("fs"); // file system
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
For me, the 1215 error occurred when I was importing a dumpfile created by mysqldump
, which creates the tables alphabetically, which in my case, caused foreign keys to reference tables created later in the file. (Props to this page for pointing it out: https://www.percona.com/blog/2017/04/06/dealing-mysql-error-code-1215-cannot-add-foreign-key-constraint/)
Since mysqldump orders tables alphabetically and I did not want to change the names of tables, I followed the instructions in the answer by JeremyWeir on this page, which states to put set FOREIGN_KEY_CHECKS = 0;
at the top of the dump file and put SET FOREIGN_KEY_CHECKS = 1;
at the bottom of the dump file.
That solution worked for me.
To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.
long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)
Try to use JSONP
in your Ajax call. It will bypass the Same Origin Policy.
http://learn.jquery.com/ajax/working-with-jsonp/
Try example
$.ajax({
url: "https://api.dailymotion.com/video/x28j5hv?fields=title",
dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}
});
Based on the above stuff:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)
fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)
plot = fig.add_subplot(1, 1, 1)
plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)
for label in (plot.get_xticklabels() + plot.get_yticklabels()):
label.set_fontproperties(font)
To remove all spaces in every column, you can use
data[] <- lapply(data, gsub, pattern = " ", replacement = "", fixed = TRUE)
or to constrict this to just the second and third columns (i.e. every column except the first),
data[-1] <- lapply(data[-1], gsub, pattern = " ", replacement = "", fixed = TRUE)
As said before, your function is calculating a straight line distance to the destination point. If you want the driving distance/route, you can use Google Maps Distance Matrix Service:
getDrivingDistanceBetweenTwoLatLong(origin, destination) {
return new Observable(subscriber => {
let service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(origin.lat, origin.long)],
destinations: [new google.maps.LatLng(destination.lat, destination.long)],
travelMode: 'DRIVING'
}, (response, status) => {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:', status);
subscriber.error({error: status, status: status});
} else {
console.log(response);
try {
let valueInMeters = response.rows[0].elements[0].distance.value;
let valueInKms = valueInMeters / 1000;
subscriber.next(valueInKms);
subscriber.complete();
}
catch(error) {
subscriber.error({error: error, status: status});
}
}
});
});
}
Oh man, solutions in all above answers provided so far didn't work for me. I had a similar problem just now. I managed to solve it with wrapping with the quote. See the screenshot. Whoo.
Original:
var products = [{_x000D_
"name": "Pizza",_x000D_
"price": "10",_x000D_
"quantity": "7"_x000D_
}, {_x000D_
"name": "Cerveja",_x000D_
"price": "12",_x000D_
"quantity": "5"_x000D_
}, {_x000D_
"name": "Hamburguer",_x000D_
"price": "10",_x000D_
"quantity": "2"_x000D_
}, {_x000D_
"name": "Fraldas",_x000D_
"price": "6",_x000D_
"quantity": "2"_x000D_
}];_x000D_
console.log(products);_x000D_
var b = JSON.parse(products); //unexpected token o
_x000D_
Depending on your rights, you need sudo at beginning.
To resolve this, make sure you installed the hosting bundle.
If you have some column in SELECT clause , how will it select it if there is several rows ? so yes , every column in SELECT clause should be in GROUP BY clause also , you can use aggregate functions in SELECT ...
you can have column in GROUP BY clause which is not in SELECT clause , but not otherwise
For short: No
Explanation:
According to the official docs: https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15
If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.
The mutable
keyword is a way to pierce the const
veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way except when and how it is marked mutable
.
With your const
reference or pointer you are constrained to:
const
. The mutable
exception makes it so you can now write or set data members that are marked mutable
. That's the only externally visible difference.
Internally those const
methods that are visible to you can also write to data members that are marked mutable
. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that mutable
doesn't destroy the const
concept and is only used in useful special cases. The mutable
keyword helps because it clearly marks data members that are subject to these special cases.
In practice you can use const
obsessively throughout your codebase (you essentially want to "infect" your codebase with the const
"disease"). In this world pointers and references are const
with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up "referential transparency".
Without the mutable
keyword you will eventually be forced to use const_cast
to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately const_cast
is significantly more destructive than mutable
because it forces the API client to destroy the const
protection of the objects (s)he is using. Additionally it causes widespread const
destruction: const_cast
ing a const pointer or reference allows unfettered write and method calling access to visible members. In contrast mutable
requires the API designer to exercise fine grained control over the const
exceptions, and usually these exceptions are hidden in const
methods operating on private data.
(N.B. I refer to to data and method visibility a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed here.)
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
Above points are correct and I want to add some more important points about Static keyword.
Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).
so you will get a doubt that what is the use of this right???
example: static int a=10;(1 program)
just now I told if you use static keyword for variables or for method it will store in permanent memory right.
so I declared same variable with keyword static in other program with different value.
example: static int a=20;(2 program)
the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.
In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.
overall i can say that,if we use static keyword
1.we can save memory
2.we can avoid duplicates
3.No need of creating object in-order to access static variable with the help of class name you can access it.
Need for using --dryRun when using custom directory
You can pass your custom directory path along with ng
command.
ng g c myfolder\mycomponent
But there are chances that you miss spell the path and either new folder gets created or target directory changes. For this reason dryRun
is very helpful. It displays an output of how the changes is going to be affected.
After verifying the result you can run the same command without -d
to make the changes.
--dryRun=true|false
When true, runs through and reports activity without writing out results.
Default: false
Aliases: -d
Official Doc :- https://angular.io/cli/generate
Sorry if this is too verbose or too late, but this was the only way I could find to get the job done. The most complicating factor was the fact that java does not have pass by reference functions, so the get---Extra methods need a default to return and cannot modify a boolean value to tell whether or not the default value is being returned by chance, or because the results were not favorable. For this purpose, it would have been nicer to have the method raise an exception than to have it return a default.
I found my information here: Android Intent Documentation.
//substitute your own intent here
Intent intent = new Intent();
intent.putExtra("first", "hello");
intent.putExtra("second", 1);
intent.putExtra("third", true);
intent.putExtra("fourth", 1.01);
// convert the set to a string array
String[] anArray = {};
Set<String> extras1 = (Set<String>) intent.getExtras().keySet();
String[] extras = (String[]) extras1.toArray(anArray);
// an arraylist to hold all of the strings
// rather than putting strings in here, you could display them
ArrayList<String> endResult = new ArrayList<String>();
for (int i=0; i<extras.length; i++) {
//try using as a String
String aString = intent.getStringExtra(extras[i]);
// is a string, because the default return value for a non-string is null
if (aString != null) {
endResult.add(extras[i] + " : " + aString);
}
// not a string
else {
// try the next data type, int
int anInt = intent.getIntExtra(extras[i], 0);
// is the default value signifying that either it is not an int or that it happens to be 0
if (anInt == 0) {
// is an int value that happens to be 0, the same as the default value
if (intent.getIntExtra(extras[i], 1) != 1) {
endResult.add(extras[i] + " : " + Integer.toString(anInt));
}
// not an int value
// try double (also works for float)
else {
double aDouble = intent.getDoubleExtra(extras[i], 0.0);
// is the same as the default value, but does not necessarily mean that it is not double
if (aDouble == 0.0) {
// just happens that it was 0.0 and is a double
if (intent.getDoubleExtra(extras[i], 1.0) != 1.0) {
endResult.add(extras[i] + " : " + Double.toString(aDouble));
}
// keep looking...
else {
// lastly check for boolean
boolean aBool = intent.getBooleanExtra(extras[i], false);
// same as default, but not necessarily not a bool (still could be a bool)
if (aBool == false) {
// it is a bool!
if (intent.getBooleanExtra(extras[i], true) != true) {
endResult.add(extras[i] + " : " + Boolean.toString(aBool));
}
else {
//well, the road ends here unless you want to add some more data types
}
}
// it is a bool
else {
endResult.add(extras[i] + " : " + Boolean.toString(aBool));
}
}
}
// is a double
else {
endResult.add(extras[i] + " : " + Double.toString(aDouble));
}
}
}
// is an int value
else {
endResult.add(extras[i] + " : " + Integer.toString(anInt));
}
}
}
// to display at the end
for (int i=0; i<endResult.size(); i++) {
Toast.makeText(this, endResult.get(i), Toast.LENGTH_SHORT).show();
}
Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.
f = open('data.txt','r')
string = ""
while 1:
line = f.readline()
if not line:break
string += line
f.close()
print(string)
Specify all fields but your ID field.
INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)
SELECT FIELD2, NULL, ..., FIELD529, FIELD1
FROM MyTable
WHERE FIELD1 = @Id;
You should be using below
return Observable.throw(error || 'Internal Server error');
Import the throw
operator using the below line
import 'rxjs/add/observable/throw';
Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe
, part of the Voyager
card catalog by "Ex Libris" and I'm getting the error as well:
catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png
I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:
Run-Time Error 380
(try updating)sfc /scannow
Run as Administrator
)From what others are saying (like David M) I think it could be related to the MSVBM60.DLL
library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).
Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.
screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png
screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png
Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.
Here is a complete program how to recursively list folder's contents:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#define NORMAL_COLOR "\x1B[0m"
#define GREEN "\x1B[32m"
#define BLUE "\x1B[34m"
/* let us make a recursive function to print the content of a given folder */
void show_dir_content(char * path)
{
DIR * d = opendir(path); // open the path
if(d==NULL) return; // if was not able return
struct dirent * dir; // for the directory entries
while ((dir = readdir(d)) != NULL) // if we were able to read somehting from the directory
{
if(dir-> d_type != DT_DIR) // if the type is not directory just print it with blue
printf("%s%s\n",BLUE, dir->d_name);
else
if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
{
printf("%s%s\n",GREEN, dir->d_name); // print its name in green
char d_path[255]; // here I am using sprintf which is safer than strcat
sprintf(d_path, "%s/%s", path, dir->d_name);
show_dir_content(d_path); // recall with the new path
}
}
closedir(d); // finally close the directory
}
int main(int argc, char **argv)
{
printf("%s\n", NORMAL_COLOR);
show_dir_content(argv[1]);
printf("%s\n", NORMAL_COLOR);
return(0);
}
You can use the Class XmlAttribute.
Eg:
XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";
node.Attributes.Append(attr);
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
It sounds like you'd be happer with a single table. The five having the same schema, and sometimes needing to be presented as if they came from one table point to putting it all in one table.
Add a new column which can be used to distinguish among the five languages (I'm assuming it's language that is different among the tables since you said it was for localization). Don't worry about having 4.5 million records. Any real database can handle that size no problem. Add the correct indexes, and you'll have no trouble dealing with them as a single table.
Also, if you want to overwrite messages in the same line, for instance in a countdown, you could add '\r' at the end of the string.
process.stdout.write("Downloading " + data.length + " bytes\r");
There is also a vectorized implementation, which allows to use 4 numpy arrays instead of scalar values for coordinates:
def distance(s_lat, s_lng, e_lat, e_lng):
# approximate radius of earth in km
R = 6373.0
s_lat = s_lat*np.pi/180.0
s_lng = np.deg2rad(s_lng)
e_lat = np.deg2rad(e_lat)
e_lng = np.deg2rad(e_lng)
d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2
return 2 * R * np.arcsin(np.sqrt(d))
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
In my case ASP.NET not registered on server. try to execute this in command prompt:
Windows 32bit
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Windows 64bit
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
string.replaceAll() doesn't correctly work with locale different from predefined. At least in jdk7u10.
This example creates a word dictionary from textfile with windows cyrillic charset CP1251
public static void main (String[] args) {
String fileName = "Tolstoy_VoinaMir.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.forName("CP1251"));
Set<String> words = new TreeSet<>();
for (String s: lines ) {
for (String w : s.split("\\s+")) {
w = w.replaceAll("\\p{Punct}","");
words.add(w);
}
}
for (String w: words) {
System.out.println(w);
}
} catch (Exception e) {
e.printStackTrace();
}
As far as I can tell, you can't debug a live event from google docs, so you have to do it from the debugger, which is pointless since the event argument passed to my onEdit() function will always be undefined if I run it from the Script Editor.
True - so define the event argument yourself for debugging. See How can I test a trigger function in GAS?
I was trying to use the Logger.log method to log some data whenever the onEdit function gets called, but this too seems like it only works when run from the Script Editor. When I run it from the Script Editor, I can view the logs by going to View->Logs...
True again, but there is help. Peter Hermann's BetterLog library will redirect all logs to a spreadsheet, enabling logging even from code that is not attached to an instance of the editor / debugger.
If you're coding in a spreadsheet-contained script, for example, you can add just this one line to the top of your script file, and all logs will go to a "Logs" sheet in the spreadsheet. No other code necessary, just use Logger.log()
as you usually would:
Logger = BetterLog.useSpreadsheet();
You're getting errors 'table liam does not exist' because the table's name is Liam
which is not the same as liam
. MySQL table names are case sensitive.
Just to add a note, since I can't comment without 50+ rep...
If you have FIPS enabled on the server, it doesn't allow you to create users. Because IIS v8 (and lower I would imagine) does not use FIPS encryption algorithms. It would be great if it supported it , because obviously a user account in windows is insecure compared to a virtual user mapped to an isolated folder. Too bad.
I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).
Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:
Benchmark Mode Samples Score Error Units
SO28319064.forEach avgt 100 187.310 ± 1.768 ms/op
SO28319064.map avgt 100 189.180 ± 1.692 ms/op
SO28319064.mapWithParallelStream avgt 100 55,577 ± 0,782 ms/op
You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.
Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:
myFinalList = myListToParse.stream()
.filter(Objects::nonNull)
.map(this::doSomething)
.collect(toList());
Remove conn.commit from Register.java
In your jsp change action to :<form name="registrationform" action="Register" method="post">
The typical way is with scanf
:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf
returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf
family (sscanf
, fscanf
and so on).
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
"Date.now() - 86400000" won't work on the Daylight Saving end day (which has 25 hours that day)
Another option is to use Closure:
var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));
Do as follows:
Project -> Properties -> java compiler ->
For Java:
X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}
Try cleaning the project and rebuild, if doesn't work try disabling the Instant Run from Settings>Build>Instant Run in case you are running someone else's code.
You might want to consider using console.log
with the built-in "arguments" object:
console.log(arguments); // would have shown you [0] null, [1] yourResult
This will always output all of your arguments, no matter how many arguments you have.
Create a file called config
inside ~/.ssh
. Inside the file you can add:
Host *
User buck
Or add
Host example
HostName example.net
User buck
The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net
; ssh example
will be enough.
git revert -m
allows to un-merge still keeping the history of both merge and un-do operation. Might be good for documenting probably.
I had this error, was able to overcome it by using :
patch -p1 < example.patch
I took it from here: https://www.drupal.org/node/1129120
One additional implementation, which uses Newtonsoft.Json binary JSON and does not require marking everything with the [Serializable] attribute. Only one drawback is that an object has to be wrapped in anonymous class, so byte array obtained with binary serialization can be different from this one.
public static byte[] ConvertToBytes(object obj)
{
using (var ms = new MemoryStream())
{
using (var writer = new BsonWriter(ms))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, new { Value = obj });
return ms.ToArray();
}
}
}
Anonymous class is used because BSON should start with a class or array. I have not tried to deserialize byte[] back to object and not sure if it works, but have tested the speed of conversion to byte[] and it completely satisfies my needs.
Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:
var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'
var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];
if this is a windows box, the simplest thing to do is to stop the servers, add skip-grant-tables to the mysql configuration file, and restart the server.
once you've fixed your permission problems, repeat the above but remove the skip-grant-tables option.
if you don't know where your configuration file is, then log in to mysql send SHOW VARIABLES LIKE '%config%'
and one of the rows returned will tell you where your configuration file is.
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.
Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.
1) Start of by setting your height as 100vh.
2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.
3) Just offset the extra padding-top with a negative margin-top
div
{
/*height: calc(100vh - 75vw);*/
height: 100vh;
margin-top: -75vw;
padding-top: 75vw;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: pink;
}
Here's a dplyr
option:
library(dplyr)
# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))
# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))
As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.
However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.
float
has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.
double
has 53 significant binary digits, which is approximately 15 decimal digits.
Another answer of mine has further explanation if you're interested.
You just need to have an existing file, open the context menu on your folder , and then choose Add
=> Existing item...
If you have the file already placed within your project structure, but it is not yet included, you can do so by making them visible in the solution explorer
If you assign it to a class it should work:
<script>
function changeClass(){
document.getElementById('myButton').className = 'formatForButton';
}
</script>
<style>
.formatForButton {
background-color:pink;
}
</style>
<body>
<input id='myButton' type=button class=none value='Change Color to pink' onclick='changeClass()'>
</body>
May i add to Stormenet example some KISS (Keep It Simple & Stupid):
If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :
treeView1.Nodes.Add("ParentKey","Parent Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");
Another Ex. two parent's first have two child's second one child:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");
Take if farther - sub child of child 2:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");
As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!
Put this XML to show only the wheel:
<ProgressBar
android:indeterminate="true"
android:id="@+id/marker_progress"
style="?android:attr/progressBarStyle"
android:layout_height="50dp" />
there's nothing wrong with using CHAR like that..
I think your problem is that you have a space in your tablename. It should be: charteredflight
or chartered_flight
..
LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2
My Solutions:
$("body").scrollspy({ target: ".target", offset: fix_header_height });
$(".target").click(function() {
$("body").animate(
{
scrollTop: $($(this).attr("href")).offset().top - fix_header_height
},
500
);
return;
});
MessageBox.Show(
"your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk //For Info Asterisk
MessageBoxIcon.Exclamation //For triangle Warning
)
To uninstalling existing MongoDB packages. I think this link will helpful.
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
The last number (here 1) can be change to change window style (not only buttons!):
## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue
## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle
For example,
ctypes.windll.user32.MessageBoxW(0, "That's an error", "Warning!", 16)
will give this:
Try
data _null_;
monyy = '05May2013';
date = input(substr(strip(monyy),1,9),date9.);
put date=date9.;
run;
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
I had same error, I think the problem is that the error text is confusing, because its giving a false key name.
In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".
My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.
I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").
Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)
Hope this helps!
Am I oversimplifying this?
$location = "http://rss.news.yahoo.com/rss/topstories";
print file_get_contents($location);
Some places (like digg.com) won't allow you to access their site without having a user-agent, in which case you would need to set that with ini_set() prior to running the file_get_contents().
To find the exact center of the map you'll need to translate the lat/lon coordinates into pixel coordinates and then find the pixel center and convert that back into lat/lon coordinates.
You might not notice or mind the drift depending how far north or south of the equator you are. You can see the drift by doing map.setCenter(map.getBounds().getCenter()) inside of a setInterval, the drift will slowly disappear as it approaches the equator.
You can use the following to translate between lat/lon and pixel coordinates. The pixel coordinates are based on a plane of the entire world fully zoomed in, but you can then find the center of that and switch it back into lat/lon.
var HALF_WORLD_CIRCUMFERENCE = 268435456; // in pixels at zoom level 21
var WORLD_RADIUS = HALF_WORLD_CIRCUMFERENCE / Math.PI;
function _latToY ( lat ) {
var sinLat = Math.sin( _toRadians( lat ) );
return HALF_WORLD_CIRCUMFERENCE - WORLD_RADIUS * Math.log( ( 1 + sinLat ) / ( 1 - sinLat ) ) / 2;
}
function _lonToX ( lon ) {
return HALF_WORLD_CIRCUMFERENCE + WORLD_RADIUS * _toRadians( lon );
}
function _xToLon ( x ) {
return _toDegrees( ( x - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS );
}
function _yToLat ( y ) {
return _toDegrees( Math.PI / 2 - 2 * Math.atan( Math.exp( ( y - HALF_WORLD_CIRCUMFERENCE ) / WORLD_RADIUS ) ) );
}
function _toRadians ( degrees ) {
return degrees * Math.PI / 180;
}
function _toDegrees ( radians ) {
return radians * 180 / Math.PI;
}
You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
return A ^ B;
}
But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;
<body onLoad="self.focus();document.formname.name.focus()" >
formname is <form action="xxx.php" method="POST" name="formname" >
and name is <input type="text" tabindex="1" name="name" />
it works for me, checked using IE and mozilla.
autofocus, somehow didn't work for me.
The member function QComboBox::currentData has been added since this question was asked, see this commit
I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:
// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
alert(timeDifferenceInDays);
You can skip some steps in the code, I have written it so to make it easy to understand.
You'll find a running example here: http://jsfiddle.net/matKX/