I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.
class NormalizeData:
def __init__(self, element):
self.element = element
def execute(self):
if isinstance(self.element, dict):
self.__iterate()
else:
return
def __iterate(self):
for key in self.element:
if isinstance(self.element[key], <ClassName>):
self.element[key] = str(self.element[key])
node = NormalizeData(self.element[key])
node.execute()
Go to Project Settings > Artifacts. Select the artifact which has the problem. There is an option "Include in project build". This needs to be checked(enabled). For older versions of IntelliJ this option is "Make on build".
The second time you're referring to div2, you're not using the # id selector.
There's no element named div2.
I use the following (Uses Consolas size 11 on Windows, Menlo Regular size 14 on Mac OS X and Inconsolata size 12 everywhere else):
if has("gui_running")
if has("gui_gtk2")
set guifont=Inconsolata\ 12
elseif has("gui_macvim")
set guifont=Menlo\ Regular:h14
elseif has("gui_win32")
set guifont=Consolas:h11:cANSI
endif
endif
Edit: And while you're at it, you could take a look at Coding Horror's Programming Fonts blog post.
Edit²: Added MacVim.
Use while loop like this:
while IFS= read -r line || [ -n "$line" ]; do
echo "$line"
done <file
Or using grep
with while loop:
while IFS= read -r line; do
echo "$line"
done < <(grep "" file)
Using grep .
instead of grep ""
will skip the empty lines.
Note:
Using IFS=
keeps any line indentation intact.
File without a newline at the end isn't a standard unix text file.
I solved this issue finally, it was because of some systems like skype and system processes take that port 80, you can make check using netstat -ao for port 80
Kindly find the following steps
After installing your Apache HTTP go to the bin folder using cmd
Install it as a service using httpd.exe -k install even when you see the error never mind
Now make sure the service is installed (even if not started) according to your os
Restart the system, then you will find the Apache service will be the first one to take the 80 port,
Congratulations the issue is solved.
As Sohnee says, using System.Net.HttpWebRequest
and set the Timeout
property instead of using System.Net.WebClient
.
You can't however set an infinite timeout value (it's not supported and attempting to do so will throw an ArgumentOutOfRangeException
).
I'd recommend first performing a HEAD HTTP request and examining the Content-Length
header value returned to determine the number of bytes in the file you're downloading and then setting the timeout value accordingly for subsequent GET
request or simply specifying a very long timeout value that you would never expect to exceed.
Maybe you could use String#split
To answer your comment:
I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:
String input = "boo.and.foo";
String[] result = input.split(".");
This will return an array containing:
{ "boo", "and", "foo" }
So you will know that the last index in the array is the extension and all others are the base.
Other than those on the top, you can use JavaScript to fetch the details from the server. html file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="test">
</div>
<script type="text/javascript">
let url="http://localhost:8001/test";
fetch(url).then(response => response.json())
.then( (result) => {
console.log('success:', result)
let div=document.getElementById('test');
div.innerHTML=`title: ${result.title}<br/>message: ${result.message}`;
})
.catch(error => console.log('error:', error));
</script>
</body>
</html>
server.js
app.get('/test',(req,res)=>{
//res.sendFile(__dirname +"/views/test.html",);
res.json({title:"api",message:"root"});
})
app.get('/render',(req,res)=>{
res.sendFile(__dirname +"/views/test.html");
})
The best answer i found on the stack-overflow on the said subject, it's not my answer. Found it somewhere for nearly same question...source source of answer
you can get the index via grep
and colnames
:
grep("B", colnames(df))
[1] 2
or use
grep("^B$", colnames(df))
[1] 2
to only get the columns called "B" without those who contain a B e.g. "ABC".
As Jon Lin commented, ls -al
will always output (for .
and ..
). You want ls -Al
to avoid these two directories.
You could for example put the output of the command into a shell variable:
v=$(ls -Al)
An older, non-nestable, notation is
v=`ls -Al`
but I prefer the nestable notation $(
... )
The you can test if that variable is non empty
if [ -n "$v" ]; then
echo there are files
else
echo no files
fi
And you could combine both as if [ -n "$(ls -Al)" ]; then
Sometimes, ls
may be some shell alias. You might prefer to use $(/bin/ls -Al)
. See ls(1) and hier(7) and environ(7) and your ~/.bashrc
(if your shell is GNU bash; my interactive shell is zsh, defined in /etc/passwd
- see passwd(5) and chsh(1)).
Not talk about performance, for custom font you can have a recursive method loop through all the views and set typeface if it's a TextView:
public class Font {
public static void setAllTextView(ViewGroup parent) {
for (int i = parent.getChildCount() - 1; i >= 0; i--) {
final View child = parent.getChildAt(i);
if (child instanceof ViewGroup) {
setAllTextView((ViewGroup) child);
} else if (child instanceof TextView) {
((TextView) child).setTypeface(getFont());
}
}
}
public static Typeface getFont() {
return Typeface.createFromAsset(YourApplicationContext.getInstance().getAssets(), "fonts/whateverfont.ttf");
}
}
In all your activity, pass current ViewGroup to it after setContentView and it's done:
ViewGroup group = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
Font.setAllTextView(group);
For fragment you can do something similar.
Usually, deleting the current emulator that doesn't work anymore and creating it again will solve the issue. I've had it 5 minutes ago and that's how I solved it.
Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {
$('table').each(function() {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to CSV");
$button.insertAfter($table);
$button.click(function() {
CSV.begin('table').download('Export.csv').go();
});
});
})
</script>
</head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
</body>
</html>
There are different ways to do that.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],
'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })
def getMonth(s): return s.split("-")[1] def getDay(s): return s.split("-")[0] def getYear(s): return s.split("-")[2] def getYearMonth(s): return s.split("-")[1]+"-"+s.split("-")[2]
year
, month
, day
and 'yearMonth
'. In your case, you need one of both. You can group using two columns 'year','month'
or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x)) df['month']= df['Date'].apply(lambda x: getMonth(x)) df['day']= df['Date'].apply(lambda x: getDay(x)) df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
3 20-Jan-14 25 15 14 Jan 20 Jan-14
4 21-Feb-14 60 80 14 Feb 21 Feb-14
In this case, we are grouping by two columns:
for key,g in df.groupby(['year','month']): print key,g
Output:
('13', 'Jun') Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
('13', 'Aug') Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
('14', 'Jan') Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
('14', 'Feb') Date abc xyz year month day YearMonth
In this case, we are grouping by one column:
for key,g in df.groupby(['YearMonth']): print key,g
Output:
Jun-13 Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
Aug-13 Date abc xyz year month day YearMonth
2 15-Aug-13 40 -5 13 Aug 15 Aug-13
Jan-14 Date abc xyz year month day YearMonth
3 20-Jan-14 25 15 14 Jan 20 Jan-14
Feb-14 Date abc xyz year month day YearMonth
4 21-Feb-14 60 80 14 Feb 21 Feb-14
get_group
print df.groupby(['YearMonth']).get_group('Jun-13')
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
get_group
. This hack would help to filter values and get the grouped values.This also would give the same result.
print df[df['YearMonth']=='Jun-13']
Output:
Date abc xyz year month day YearMonth
0 01-Jun-13 100 200 13 Jun 01 Jun-13
1 03-Jun-13 -20 50 13 Jun 03 Jun-13
You can select list of abc
or xyz
values during Jun-13
print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values
Output:
[100 -20] #abc values
[200 50] #xyz values
You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.
for x in set(df.YearMonth):
print df[df['YearMonth']==x].abc.values
print df[df['YearMonth']==x].xyz.values
I recommend also to check this answer as well.
You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.
set_error_handler(
function ($severity, $message, $file, $line) {
throw new ErrorException($message, $severity, $severity, $file, $line);
}
);
try {
file_get_contents('www.google.com');
}
catch (Exception $e) {
echo $e->getMessage();
}
restore_error_handler();
Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.
You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE
ALTER TABLE foo NOCHECK CONSTRAINT ALL
or
ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column
Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.
This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.
How does @Autowired
work internally?
Example:
class EnglishGreeting {
private Greeting greeting;
//setter and getter
}
class Greeting {
private String message;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting">
<property name="greeting" ref="greeting"/>
</bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If you are using @Autowired
then:
class EnglishGreeting {
@Autowired //so automatically based on the name it will identify the bean and inject.
private Greeting greeting;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If still have some doubt then go through below live demo
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
On my mac, running MAMP I have a few locations that would be the likely php.ini, so I edited the memory_limit to different values in the 2 suspected files, to test which one effected the actual MAMP PHP INFO page details. By doing that I was able to determine that this was the correct php.ini: /Applications/MAMP/bin/php/php7.2.10/conf/php.ini
What I use for IsNotNullOrEmptyOrWhiteSpace
in T-SQL is:
SELECT [column_name] FROM [table_name]
WHERE LEN(RTRIM(ISNULL([column_name], ''))) > 0
This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365
By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.
I've tested on my onw server and it works!:
var lost_addresses = [];
geocode_count = 0;
resNumber = 0;
map = new GMaps({
div: '#gmap_marker',
lat: 43.921493,
lng: 12.337646,
});
function loadMarkerTimeout(timeout) {
setTimeout(loadMarker, timeout)
}
function loadMarker() {
map.setZoom(6);
$.ajax({
url: [Insert here your URL] ,
type:'POST',
data: {
"action": "loadMarker"
},
success:function(result){
/***************************
* Assuming your ajax call
* return something like:
* array(
* 'status' => 'success',
* 'results'=> $resultsArray
* );
**************************/
var res=JSON.parse(result);
if(res.status == 'success') {
resNumber = res.results.length;
//Call the geoCoder function
getGeoCodeFor(map, res.results);
}
}//success
});//ajax
};//loadMarker()
$().ready(function(e) {
loadMarker();
});
//Geocoder function
function getGeoCodeFor(maps, addresses) {
$.each(addresses, function(i,e){
GMaps.geocode({
address: e.address,
callback: function(results, status) {
geocode_count++;
if (status == 'OK') {
//if the element is alreay in the array, remove it
lost_addresses = jQuery.grep(lost_addresses, function(value) {
return value != e;
});
latlng = results[0].geometry.location;
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
title: 'MyNewMarker',
});//addMarker
} else if (status == 'ZERO_RESULTS') {
//alert('Sorry, no results found');
} else if(status == 'OVER_QUERY_LIMIT') {
//if the element is not in the losts_addresses array, add it!
if( jQuery.inArray(e,lost_addresses) == -1) {
lost_addresses.push(e);
}
}
if(geocode_count == addresses.length) {
//set counter == 0 so it wont's stop next round
geocode_count = 0;
setTimeout(function() {
getGeoCodeFor(maps, lost_addresses);
}, 2500);
}
}//callback
});//GeoCode
});//each
};//getGeoCodeFor()
Example:
map = new GMaps({_x000D_
div: '#gmap_marker',_x000D_
lat: 43.921493,_x000D_
lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = { _x000D_
"status":"success",_x000D_
"results":[ _x000D_
{ _x000D_
"customerId":1,_x000D_
"address":"Via Italia 43, Milano (MI)",_x000D_
"customerName":"MyAwesomeCustomer1"_x000D_
},_x000D_
{ _x000D_
"customerId":2,_x000D_
"address":"Via Roma 10, Roma (RM)",_x000D_
"customerName":"MyAwesomeCustomer2"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
function loadMarkerTimeout(timeout) {_x000D_
setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
map.setZoom(6);_x000D_
_x000D_
$.ajax({_x000D_
url: '/echo/html/',_x000D_
type: "POST",_x000D_
data: jsonData,_x000D_
cache: false,_x000D_
success:function(result){_x000D_
_x000D_
var res=JSON.parse(result);_x000D_
if(res.status == 'success') {_x000D_
resNumber = res.results.length;_x000D_
//Call the geoCoder function_x000D_
getGeoCodeFor(map, res.results);_x000D_
}_x000D_
}//success_x000D_
});//ajax_x000D_
_x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
$.each(addresses, function(i,e){ _x000D_
GMaps.geocode({_x000D_
address: e.address,_x000D_
callback: function(results, status) {_x000D_
geocode_count++; _x000D_
_x000D_
console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
_x000D_
if (status == 'OK') { _x000D_
_x000D_
//if the element is alreay in the array, remove it_x000D_
lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
return value != e;_x000D_
});_x000D_
_x000D_
_x000D_
latlng = results[0].geometry.location;_x000D_
map.addMarker({_x000D_
lat: latlng.lat(),_x000D_
lng: latlng.lng(),_x000D_
title: e.customerName,_x000D_
});//addMarker_x000D_
} else if (status == 'ZERO_RESULTS') {_x000D_
//alert('Sorry, no results found');_x000D_
} else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
//if the element is not in the losts_addresses array, add it! _x000D_
if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
lost_addresses.push(e);_x000D_
}_x000D_
_x000D_
} _x000D_
_x000D_
if(geocode_count == addresses.length) {_x000D_
//set counter == 0 so it wont's stop next round_x000D_
geocode_count = 0;_x000D_
_x000D_
setTimeout(function() {_x000D_
getGeoCodeFor(maps, lost_addresses);_x000D_
}, 2500);_x000D_
}_x000D_
}//callback_x000D_
});//GeoCode_x000D_
});//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
min-height:250px;_x000D_
height:100%;_x000D_
width:100%;_x000D_
position: relative; _x000D_
overflow: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
Two solutions that spring to mind:
order by case id when 123 then 1 when 456 then 2 else null end asc
order by instr(','||id||',',',123,456,') asc
(instr()
is from Oracle; maybe you have locate()
or charindex()
or something like that)
A percentage value in a height
property has a little complication, and the width
and height
properties actually behave differently to each other. Let me take you on a tour through the specs.
height
property:Let's have a look at what CSS Snapshot 2010 spec says about height
:
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element.
OK, let's take that apart step by step:
The percentage is calculated with respect to the height of the generated box's containing block.
What's a containing block? It's a bit complicated, but for a normal element in the default static
position, it's:
the nearest block container ancestor box
or in English, its parent box. (It's well worth knowing what it would be for fixed
and absolute
positions as well, but I'm ignoring that to keep this answer short.)
So take these two examples:
<div id="a" style="width: 100px; height: 200px; background-color: orange">_x000D_
<div id="aa" style="width: 100px; height: 50%; background-color: blue"></div>_x000D_
</div>
_x000D_
<div id="b" style="width: 100px; background-color: orange">_x000D_
<div id="bb" style="width: 100px; height: 50%; background-color: blue"></div>_x000D_
</div>
_x000D_
In this example, the containing block of #aa
is #a
, and so on for #b
and #bb
. So far, so good.
The next sentence of the spec for height
is the complication I mentioned in the introduction to this answer:
If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.
Aha! Whether the height of the containing block has been specified explicitly matters!
height:200px
is 100px in the case of #aa
height:auto
is auto
, which is 0px in the case of #bb
since there is no content for auto
to expand toAs the spec says, it also matters whether the containing block has been absolutely positioned or not, but let's move on to width
.
width
property:So does it work the same way for width
? Let's take a look at the spec:
The percentage is calculated with respect to the width of the generated box's containing block.
Take a look at these familiar examples, tweaked from the previous to vary width
instead of height
:
<div id="c" style="width: 200px; height: 100px; background-color: orange">_x000D_
<div id="cc" style="width: 50%; height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
<div id="d" style=" height: 100px; background-color: orange">_x000D_
<div id="dd" style="width: 50%; height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
width:200px
is 100px in the case of #cc
width:auto
is 50% of whatever width:auto
ends up being, unlike height
, there is no special rule that treats this case differently.Now, here's the tricky bit: auto
means different things, depending partly on whether its been specified for width
or height
! For height
, it just meant the height needed to fit the contents*, but for width
, auto
is actually more complicated. You can see from the code snippet that's in this case it ended up being the width of the viewport.
What does the spec say about the auto value for width?
The width depends on the values of other properties. See the sections below.
Wahey, that's not helpful. To save you the trouble, I've found you the relevant section to our use-case, titled "calculating widths and margins", subtitled "block-level, non-replaced elements in normal flow":
The following constraints must hold among the used values of the other properties:
'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
OK, so width
plus the relevant margin, border and padding borders must all add up to the width of the containing block (not descendents the way height
works). Just one more spec sentence:
If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.
Aha! So in this case, 50% of width:auto
is 50% of the viewport. Hopefully everything finally makes sense now!
Footnotes
* At least, as far it matters in this case. spec All right, everything only kind of makes sense now.
You can import .sql file using the standard input like this:
mysql -u <user> -p<password> <dbname> < file.sql
Note: There shouldn't space between <-p>
and <password>
Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html
Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>
) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p
asks you to input password by standard input.
If you know the network interface (eth0, wlan, tun0 etc):
ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2
Try to code below,
String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
for(int y = 0; y < 3; y++)
{
shades[i][y] = value;
}
}
In my case, if I remove the the contentType
, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify()
to the data as mentioned in the update of this answer.
function checkIfDuplicateExists(w){
return new Set(w).size !== w.length
}
console.log(
checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);
console.log(
checkIfDuplicateExists(["a", "b", "c"]))
//false
1: HTML
<tbody>
{% for ticket in tickets %}
<tr>
<td class="ticket_id">{{ticket.id}}</td>
<td class="ticket_eam">{{ticket.eam}}</td>
<td class="ticket_subject">{{ticket.subject}}</td>
<td>{{ticket.zone}}</td>
<td>{{ticket.plaza}}</td>
<td>{{ticket.lane}}</td>
<td>{{ticket.uptime}}</td>
<td>{{ticket.downtime}}</td>
<td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
</tr>
{% endfor %}
</tbody>
The {% url 'ticket_details' %} is the function name in your views
2: Views.py
def ticket_details(request, ticket_id):
print(ticket_id)
return render(request, ticket.html)
ticket_id is the parameter you will get from the ticket_id=ticket.id
3: URL.py
urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]
/?P - where ticket_id is the name of the group and pattern is some pattern to match.
In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).
Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.
Just to expand on my answer a neater way of doing this multiple times would probably be:
PopulateByteArray(UserCode, 0x20);
which calls:
public static void PopulateByteArray(byte[] byteArray, byte value)
{
for (int i = 0; i < byteArray.Length; i++)
{
byteArray[i] = value;
}
}
This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)
In my case, in order to hide the keyboard when pressing the "send button", I used the accepted answer but changed context to getApplication and added getWindow().
InputMethodManager inputManager = (InputMethodManager) getApplication().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-"
for a red line, or by explicitely stating the color
argument.
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
See also the plot command's documentation.
In case you already have a line with a certain color, you can change that with the lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
If you want to change this color later on, you can do so by
plt.gca().get_lines()[0].set_color("black")
This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
and if you have more lines you can loop over them as well.
When shell=True
the shell is the child process, and the commands are its children. So any SIGTERM
or SIGKILL
will kill the shell but not its child processes, and I don't remember a good way to do it.
The best way I can think of is to use shell=False
, otherwise when you kill the parent shell process, it will leave a defunct shell process.
For small changes, I have used hexedit:
http://rigaux.org/hexedit.html
Simple but fast and useful.
If you dump the preprocessor #defines
gcc -dM -E - < /dev/null
g++ -dM -E -x c++ - < /dev/null
You can usually find stuff that will help you. With compile time logic.
#define __LITTLE_ENDIAN__ 1
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
Various compilers may have different defines however.
All the above commands create a new branch and with the latest commit being the one specified in the command, but just in case you want your current branch HEAD
to move to the specified commit, below is the command:
git checkout <commit_hash>
It detaches and point the HEAD
to specified commit and saves from creating a new branch when the user just wants to view the branch state till that particular commit.
You then might want to go back to the latest commit & fix the detached HEAD:
Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like
--defaults-file="X:\path\to\my.ini"
this is the file the server actually uses (independent of what mysql --help
prints).
I am using Typescript with vue-property-decorator and what happened to me is that my IDE auto-completed "MyComponent.vue.js" instead of "MyComponent.vue". That got me this error.
It seems like the moral of the story is that if you get this error and you are using any kind of single-file component setup, check your imports in the router.
Run below command where pom.xml
is placed:
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
And start your remote java application with debugging option on port 5005
It is true that a typical IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as IPsec (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the MTU on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.
For linux Ubuntu Open Terminal and Write :-
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
I ran into the same problem.
In most scenarios using the hack-ish setTimeout(() => { }, 0)
in componentDidMount()
worked.
But not in a special case; and I didn't want to use the ReachDOM findDOMNode
since the documentation says:
Note: findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.
(Source: findDOMNode)
So in that particular component I had to use the componentDidUpdate()
event, so my code ended up being like this:
componentDidMount() {
// feel this a little hacky? check this: http://stackoverflow.com/questions/26556436/react-after-render-code
setTimeout(() => {
window.addEventListener("resize", this.updateDimensions.bind(this));
this.updateDimensions();
}, 0);
}
And then:
componentDidUpdate() {
this.updateDimensions();
}
Finally, in my case, I had to remove the listener created in componentDidMount
:
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this));
}
Use Elastic Load Balacing, it supports SSL termination at the Load Balancer, including offloading SSL decryption from application instances and providing centralized management of SSL certificates.
CSS zoom
property is widely supported now > 86% of total browser population.
See: http://caniuse.com/#search=zoom
document.querySelector('#sel-jsz').style.zoom = 4;
_x000D_
#sel-001 {_x000D_
zoom: 2.5;_x000D_
}_x000D_
#sel-002 {_x000D_
zoom: 5;_x000D_
}_x000D_
#sel-003 {_x000D_
zoom: 300%;_x000D_
}
_x000D_
<div id="sel-000">IMG - Default</div>_x000D_
_x000D_
<div id="sel-001">IMG - 1X</div>_x000D_
_x000D_
<div id="sel-002">IMG - 5X</div>_x000D_
_x000D_
<div id="sel-003">IMG - 3X</div>_x000D_
_x000D_
_x000D_
<div id="sel-jsz">JS Zoom - 4x</div>
_x000D_
Just a tiny update with built-in wireless debugging in Android 11:
adb pair [IP_ADDRESS]:[PORT]
and type pairing code.another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
Python is a case-sensitive language. All Python keywords are lowercase. Use if
, not If
.
Also, don't put a colon after the call to print()
. Also, indent the print()
and exit()
calls, as Python uses indentation rather than brackets to represent code blocks.
And also, proceed = "y" or "Y"
won't do what you want. Use proceed = "y"
and if answer.lower() == proceed:
, or something similar.
There's also the fact that your program will exit as long as the input value is not the single character "y" or "Y", which contradicts the prompting of "N" for the alternate case. Instead of your else
clause there, use elif answer.lower() == info_incorrect:
, with info_incorrect = "n"
somewhere beforehand. Then just reprompt for the response or something if the input value was something else.
I'd recommend going through the tutorial in the Python documentation if you're having this much trouble the way you're learning now. http://docs.python.org/tutorial/index.html
This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.
For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.
If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.
(Edit: this is the updated version of the documentation linked above.)
For calling the method of one class within the second class, you have to first create the object of that class which method you want to call than with the object reference you can call the method.
class A {
public void fun(){
//do something
}
}
class B {
public static void main(String args[]){
A obj = new A();
obj.fun();
}
}
But in your case you have the static method in Date and TemperatureRange class. You can call your static method by using the class name directly like below code or by creating the object of that class like above code but static method ,mostly we use for creating the utility classes, so best way to call the method by using class name. Like in your case -
public static void main (String[] args){
String dateVal = Date.date("01","11,"12"); // calling the date function by passing some parameter.
String tempRangeVal = TemperatureRange.TempRange("80","20");
}
Chrome 46 and newer should be showing mixed content without any warning, just without the green lock in address bar.
Source: Simplifying the Page Security Icon in Chrome at Google Online Security Blog.
Disable this warning by adding property below.
For Spring application:
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
Normal JPA:
hibernate.temp.use_jdbc_metadata_defaults=false
strcpy example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string" ;
char str2[40] ;
strcpy (str2,str1) ;
printf ("str1: %s\n",str1) ;
return 0 ;
}
Output: str1: Sample string
Your case:
A simple =
operator should do the job.
string str1="Sample string" ;
string str2 = str1 ;
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
You can rename (changing URL of a remote repository) using :
git remote set-url origin new_URL
new_URL can be like https://github.com/abcdefgh/abcd.git
Too permanently delete the remote repository use :
git remote remove origin
For macOS users :
This error appears when you are using multiple Git accounts on the same machine.
Please follow below steps to remove the github.com credentials.
- Go to Finder
- Go to Applications
- Go to Utilities Folder
- Open Keychain Access
- Select the github.com and Right click on it
Delete "github.com"
Try again to Push or Pull to git and it will ask for the credentials. Enter valid credentials for repository account. Done
The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.
You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.
Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.
Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )
I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)
I would like to suggest a solution if you need to sort more than 2 lists in sync:
def SortAndSyncList_Multi(ListToSort, *ListsToSync):
y = sorted(zip(ListToSort, zip(*ListsToSync)))
w = [n for n in zip(*y)]
return list(w[0]), tuple(list(a) for a in zip(*w[1]))
conda info
will display information about the current install, including the active env location which is what you want.
Here's my output:
(base) C:\Users\USERNAME>conda info
active environment : base
active env location : C:\ProgramData\Miniconda3
shell level : 1
user config file : C:\Users\USERNAME\.condarc
populated config files :
conda version : 4.8.2
conda-build version : not installed
python version : 3.7.6.final.0
virtual packages : __cuda=10.2
base environment : C:\ProgramData\Miniconda3 (read only)
channel URLs : https://repo.anaconda.com/pkgs/main/win-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/r/win-64
https://repo.anaconda.com/pkgs/r/noarch
https://repo.anaconda.com/pkgs/msys2/win-64
https://repo.anaconda.com/pkgs/msys2/noarch
package cache : C:\ProgramData\Miniconda3\pkgs
C:\Users\USERNAME\.conda\pkgs
C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
envs directories : C:\Users\USERNAME\.conda\envs
C:\ProgramData\Miniconda3\envs
C:\Users\USERNAME\AppData\Local\conda\conda\envs
platform : win-64
user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
administrator : False
netrc file : None
offline mode : False
If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.
If that's the case find and open the Anaconda Prompt and do it from there.
Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.
Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
On my CentOS 6 I have two openssl.cnf :
/openvpn/easy-rsa/
/pki/tls/
Use pdfMake.js and this Gist.
(I found the Gist here along with a link to the package html-to-pdfmake, which I end up not using for now.)
After npm install pdfmake
and saving the Gist in htmlToPdf.js
I use it like this:
const pdfMakeX = require('pdfmake/build/pdfmake.js');
const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';
import htmlToPdf from './htmlToPdf.js';
var docDef = htmlToPdf(`<b>Sample</b>`);
pdfMake.createPdf({content:docDef}).download('sample.pdf');
Remarks:
pdfMake
's getBuffer()
function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried.jsPDF.fromHTML()
suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF.jsPDF.from_html()
function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs.Either return;
from the method early, or throw
an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
raise ValueError('could not find %c in %s' % (ch,str))
public static class StringExtensions
{
public static string Repeat(this string input, int count)
{
if (!string.IsNullOrEmpty(input))
{
StringBuilder builder = new StringBuilder(input.Length * count);
for(int i = 0; i < count; i++) builder.Append(input);
return builder.ToString();
}
return string.Empty;
}
}
Following is the util function to get current timestamp in milliseconds:
#include <sys/time.h>
long long current_timestamp() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
// printf("milliseconds: %lld\n", milliseconds);
return milliseconds;
}
About timezone:
gettimeofday() support to specify timezone, I use NULL, which ignore the timezone, but you can specify a timezone, if need.
@Update - timezone
Since the long
representation of time is not relevant to or effected by timezone itself, so setting tz
param of gettimeofday() is not necessary, since it won't make any difference.
And, according to man page of gettimeofday()
, the use of the timezone
structure is obsolete, thus the tz
argument should normally be specified as NULL, for details please check the man page.
You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().
For example type the following in the dev tools console:
// Get all event listners bound to the document object
getEventListeners(document);
None of these worked for me. I had to go to a SuperUser question.
If it is a System Process—PID 4—you need to disable the HTTP.sys driver which is started on demand by another service, such as Windows Remote Management or Print Spooler on Windows 7 or 2008.
There is two ways to disable it but the first one is safer:
Go to device manager, select “show hidden devices” from menu/view, go to “Non-Plug and Play Driver”/HTTP, double click it to disable it (or set it to manual, some services depended on it).
Reboot and use
netstat -nao | find ":80"
to check if 80 is still used.
This is the one that worked for me!
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
// Request parameters.
const params = {
'visualFeatures': 'Categories,Description,Adult,Faces',
'maxCandidates': '2',
'details': 'Celebrities,Landmarks',
'language': 'en'
};
const options = {
uri: uriBase,
qs: params,
body: fs.readFileSync(./my_local_image_path.jpg),
headers: {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
};
request.post(options, (error, response, body) => {
if (error) {
console.log('Error: ', error);
return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, ' ');
body = JSON.parse(body);
if (body.code) // err
{
console.log("AZURE: " + body.message)
}
console.log('Response\n' + jsonString);
You can tag your DOM element using #someTag
, then get it with @ViewChild('someTag')
.
See complete example:
import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({
selector: 'app',
template: `
<div #myDiv>Some text</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
console.log(this.myDiv.nativeElement.innerHTML);
}
}
console.log
will print Some text.
Simply because you don't have c++ compiler installed there in your machine, check the following
Download Microsoft Visual C++ 2008 from this page. That is a generally useful page anyway, so you should probably bookmark it. For Python 3.3+ use MS Visual C++ 2010. Install it.
Open Windows explorer (the file browser) and search for the location of ‘vcvarsall.bat’ and cut it to your clipboard.
run regedit from the Windows start key. You will need admin privilges.
Add a registry entry to HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (64 bit Windows) or HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\Setup\VC\ProductDir (32 bit) as described here.
Hint: 0.9 in the registery directory is the currently installed version of your visual studio, if you running VS 2013, you have to find the path HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\12.0....
At the Windows start key, type cmd to get a command shell. If you need to, go to your virtual environment and run activate.bat.
pip install or whatever you use to install it.
(you have cv::Mat old)
IplImage copy = old;
IplImage* new_image = ©
you work with new as an originally declared IplImage*.
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
We can also do the same using java 8.
public static<T> List<T> reverseList(List<T> list) {
List<T> reverse = new ArrayList<>(list.size());
list.stream()
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(reverse::add);
return reverse;
}
To avoid third parties, regexes, memory overheads and fast work with large scripts I created my own stream-based parser. It
can recognize comments with -- or /**/
-- some commented text
/*
drop table Users;
GO
*/
can recognize string literals with ' or "
set @s =
'create table foo(...);
GO
create index ...';
and other constructions such as
gO -- commented text
try
{
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=DATABASE-NAME;Data Source=SERVER-NAME"))
{
connection.Open();
int rowsAffected = SqlStatementReader.ExecuteSqlFile(
"C:\\target-sql-script.sql",
connection,
// Don't forget to use the correct file encoding!!!
Encoding.Default,
// Indefinitely (sec)
0
);
}
}
// implement your handlers
catch (SqlStatementReader.SqlBadSyntaxException) { }
catch (SqlException) { }
catch (Exception) { }
class SqlStatementReader
{
public class SqlBadSyntaxException : Exception
{
public SqlBadSyntaxException(string description) : base(description) { }
public SqlBadSyntaxException(string description, int line) : base(OnBase(description, line, null)) { }
public SqlBadSyntaxException(string description, int line, string filePath) : base(OnBase(description, line, filePath)) { }
private static string OnBase(string description, int line, string filePath)
{
if (filePath == null)
return string.Format("Line: {0}. {1}", line, description);
else
return string.Format("File: {0}\r\nLine: {1}. {2}", filePath, line, description);
}
}
enum SqlScriptChunkTypes
{
InstructionOrUnquotedIdentifier = 0,
BracketIdentifier = 1,
QuotIdentifierOrLiteral = 2,
DblQuotIdentifierOrLiteral = 3,
CommentLine = 4,
CommentMultiline = 5,
}
StreamReader _sr = null;
string _filePath = null;
int _lineStart = 1;
int _lineEnd = 1;
bool _isNextChar = false;
char _nextChar = '\0';
public SqlStatementReader(StreamReader sr)
{
if (sr == null)
throw new ArgumentNullException("StreamReader can't be null.");
if (sr.BaseStream is FileStream)
_filePath = ((FileStream)sr.BaseStream).Name;
_sr = sr;
}
public SqlStatementReader(StreamReader sr, string filePath)
{
if (sr == null)
throw new ArgumentNullException("StreamReader can't be null.");
_sr = sr;
_filePath = filePath;
}
public int LineStart { get { return _lineStart; } }
public int LineEnd { get { return _lineEnd == 1 ? _lineEnd : _lineEnd - 1; } }
public void LightSyntaxCheck()
{
while (ReadStatementInternal(true) != null) ;
}
public string ReadStatement()
{
for (string s = ReadStatementInternal(false); s != null; s = ReadStatementInternal(false))
{
// skip empty
for (int i = 0; i < s.Length; i++)
{
switch (s[i])
{
case ' ': continue;
case '\t': continue;
case '\r': continue;
case '\n': continue;
default:
return s;
}
}
}
return null;
}
string ReadStatementInternal(bool syntaxCheck)
{
if (_isNextChar == false && _sr.EndOfStream)
return null;
StringBuilder allLines = new StringBuilder();
StringBuilder line = new StringBuilder();
SqlScriptChunkTypes nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
SqlScriptChunkTypes currentChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
char ch = '\0';
int lineCounter = 0;
int nextLine = 0;
int currentLine = 0;
bool nextCharHandled = false;
bool foundGO;
int go = 1;
while (ReadChar(out ch))
{
if (nextCharHandled == false)
{
currentChunk = nextChunk;
currentLine = nextLine;
switch (currentChunk)
{
case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:
if (ch == '[')
{
currentChunk = nextChunk = SqlScriptChunkTypes.BracketIdentifier;
currentLine = nextLine = lineCounter;
}
else if (ch == '"')
{
currentChunk = nextChunk = SqlScriptChunkTypes.DblQuotIdentifierOrLiteral;
currentLine = nextLine = lineCounter;
}
else if (ch == '\'')
{
currentChunk = nextChunk = SqlScriptChunkTypes.QuotIdentifierOrLiteral;
currentLine = nextLine = lineCounter;
}
else if (ch == '-' && (_isNextChar && _nextChar == '-'))
{
nextCharHandled = true;
currentChunk = nextChunk = SqlScriptChunkTypes.CommentLine;
currentLine = nextLine = lineCounter;
}
else if (ch == '/' && (_isNextChar && _nextChar == '*'))
{
nextCharHandled = true;
currentChunk = nextChunk = SqlScriptChunkTypes.CommentMultiline;
currentLine = nextLine = lineCounter;
}
else if (ch == ']')
{
throw new SqlBadSyntaxException("Incorrect syntax near ']'.", _lineEnd + lineCounter, _filePath);
}
else if (ch == '*' && (_isNextChar && _nextChar == '/'))
{
throw new SqlBadSyntaxException("Incorrect syntax near '*'.", _lineEnd + lineCounter, _filePath);
}
break;
case SqlScriptChunkTypes.CommentLine:
if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
{
nextCharHandled = true;
currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
currentLine = nextLine = lineCounter;
}
else if (ch == '\n' || ch == '\r')
{
currentChunk = nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
currentLine = nextLine = lineCounter;
}
break;
case SqlScriptChunkTypes.CommentMultiline:
if (ch == '*' && (_isNextChar && _nextChar == '/'))
{
nextCharHandled = true;
nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
nextLine = lineCounter;
}
else if (ch == '/' && (_isNextChar && _nextChar == '*'))
{
throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
}
break;
case SqlScriptChunkTypes.BracketIdentifier:
if (ch == ']')
{
nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
nextLine = lineCounter;
}
break;
case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:
if (ch == '"')
{
if (_isNextChar && _nextChar == '"')
{
nextCharHandled = true;
}
else
{
nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
nextLine = lineCounter;
}
}
break;
case SqlScriptChunkTypes.QuotIdentifierOrLiteral:
if (ch == '\'')
{
if (_isNextChar && _nextChar == '\'')
{
nextCharHandled = true;
}
else
{
nextChunk = SqlScriptChunkTypes.InstructionOrUnquotedIdentifier;
nextLine = lineCounter;
}
}
break;
}
}
else
nextCharHandled = false;
foundGO = false;
if (currentChunk == SqlScriptChunkTypes.InstructionOrUnquotedIdentifier || go >= 5 || (go == 4 && currentChunk == SqlScriptChunkTypes.CommentLine))
{
// go = 0 - break, 1 - begin of the string, 2 - spaces after begin of the string, 3 - G or g, 4 - O or o, 5 - spaces after GO, 6 - line comment after valid GO
switch (go)
{
case 0:
if (ch == '\r' || ch == '\n')
go = 1;
break;
case 1:
if (ch == ' ' || ch == '\t')
go = 2;
else if (ch == 'G' || ch == 'g')
go = 3;
else if (ch != '\n' && ch != '\r')
go = 0;
break;
case 2:
if (ch == 'G' || ch == 'g')
go = 3;
else if (ch == '\n' || ch == '\r')
go = 1;
else if (ch != ' ' && ch != '\t')
go = 0;
break;
case 3:
if (ch == 'O' || ch == 'o')
go = 4;
else if (ch == '\n' || ch == '\r')
go = 1;
else
go = 0;
break;
case 4:
if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
go = 5;
else if (ch == '\n' || ch == '\r')
foundGO = true;
else if (ch == ' ' || ch == '\t')
go = 5;
else if (ch == '-' && (_isNextChar && _nextChar == '-'))
go = 6;
else
go = 0;
break;
case 5:
if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
go = 5;
else if (ch == '\n' || ch == '\r')
foundGO = true;
else if (ch == '-' && (_isNextChar && _nextChar == '-'))
go = 6;
else if (ch != ' ' && ch != '\t')
throw new SqlBadSyntaxException("Incorrect syntax was encountered while parsing go.", _lineEnd + lineCounter, _filePath);
break;
case 6:
if (ch == '\r' && (_isNextChar && _nextChar == '\n'))
go = 6;
else if (ch == '\n' || ch == '\r')
foundGO = true;
break;
default:
go = 0;
break;
}
}
else
go = 0;
if (foundGO)
{
if (ch == '\r' || ch == '\n')
{
++lineCounter;
}
// clear GO
string s = line.Append(ch).ToString();
for (int i = 0; i < s.Length; i++)
{
switch (s[i])
{
case ' ': continue;
case '\t': continue;
case '\r': continue;
case '\n': continue;
default:
_lineStart = _lineEnd;
_lineEnd += lineCounter;
return allLines.Append(s.Substring(0, i)).ToString();
}
}
return string.Empty;
}
// accumulate by string
if (ch == '\r' && (_isNextChar == false || _nextChar != '\n'))
{
++lineCounter;
if (syntaxCheck == false)
allLines.Append(line.Append('\r').ToString());
line.Clear();
}
else if (ch == '\n')
{
++lineCounter;
if (syntaxCheck == false)
allLines.Append(line.Append('\n').ToString());
line.Clear();
}
else
{
if (syntaxCheck == false)
line.Append(ch);
}
}
// this is the end of the stream, return it without GO, if GO exists
switch (currentChunk)
{
case SqlScriptChunkTypes.InstructionOrUnquotedIdentifier:
case SqlScriptChunkTypes.CommentLine:
break;
case SqlScriptChunkTypes.CommentMultiline:
if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
throw new SqlBadSyntaxException("Missing end comment mark '*/'.", _lineEnd + currentLine, _filePath);
break;
case SqlScriptChunkTypes.BracketIdentifier:
if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
throw new SqlBadSyntaxException("Unclosed quotation mark [.", _lineEnd + currentLine, _filePath);
break;
case SqlScriptChunkTypes.DblQuotIdentifierOrLiteral:
if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
throw new SqlBadSyntaxException("Unclosed quotation mark \".", _lineEnd + currentLine, _filePath);
break;
case SqlScriptChunkTypes.QuotIdentifierOrLiteral:
if (nextChunk != SqlScriptChunkTypes.InstructionOrUnquotedIdentifier)
throw new SqlBadSyntaxException("Unclosed quotation mark '.", _lineEnd + currentLine, _filePath);
break;
}
if (go >= 4)
{
string s = line.ToString();
for (int i = 0; i < s.Length; i++)
{
switch (s[i])
{
case ' ': continue;
case '\t': continue;
case '\r': continue;
case '\n': continue;
default:
_lineStart = _lineEnd;
_lineEnd += lineCounter + 1;
return allLines.Append(s.Substring(0, i)).ToString();
}
}
}
_lineStart = _lineEnd;
_lineEnd += lineCounter + 1;
return allLines.Append(line.ToString()).ToString();
}
bool ReadChar(out char ch)
{
if (_isNextChar)
{
ch = _nextChar;
if (_sr.EndOfStream)
_isNextChar = false;
else
_nextChar = Convert.ToChar(_sr.Read());
return true;
}
else if (_sr.EndOfStream == false)
{
ch = Convert.ToChar(_sr.Read());
if (_sr.EndOfStream == false)
{
_isNextChar = true;
_nextChar = Convert.ToChar(_sr.Read());
}
return true;
}
else
{
ch = '\0';
return false;
}
}
public static int ExecuteSqlFile(string filePath, SqlConnection connection, Encoding fileEncoding, int commandTimeout)
{
int rowsAffected = 0;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Simple syntax check (you can comment out these two lines below)
new SqlStatementReader(new StreamReader(fs, fileEncoding)).LightSyntaxCheck();
fs.Seek(0L, SeekOrigin.Begin);
// Read statements without GO
SqlStatementReader rd = new SqlStatementReader(new StreamReader(fs, fileEncoding));
string stmt;
while ((stmt = rd.ReadStatement()) != null)
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = stmt;
cmd.CommandTimeout = commandTimeout;
int i = cmd.ExecuteNonQuery();
if (i > 0)
rowsAffected += i;
}
}
}
return rowsAffected;
}
}
git log --format="%h" | tail -1
gives you the commit hash (ie 0dd89fb
), which you can feed into other commands, by doing something like
git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD
to view all the commits in the last day.
You can just check for null
:
if(Request.QueryString["aspxerrorpath"]!=null)
{
//your code that depends on aspxerrorpath here
}
I think you can use this
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
It finds the second li in each matched ul and notes it.
This idea can apply?. If you use CountdownLatches or Semaphores works perfect but if u are looking for the easiest answer for an interview i think this can apply.
Quoting from the gcc website:
C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
So probably you use a version of g++ which doesn't support -std=c++11
. Try -std=c++0x
instead.
Availability of C++11 features is for versions >= 4.3 only.
Put it in a TRY/CATCH
.
When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block
Reference: MSDN.
EDIT: This works for MSSQL 2005+, but I see that you now have clarified that you are working on MSSQL 2000. I'll leave this here for reference.
The SSL errors are often thrown by network management software such as Cyberroam.
To answer your question,
you will have to enter badidea into Chrome every time you visit a website.
You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors
ABCpdf.NET (http://www.websupergoo.com/abcpdf-5.htm)
We use and recommend.
Very good component, it not only convert a webpage to PDF like an image but really convert text, image, formatting, etc...
It's not free but it's cheap.
Yes. They are different file formats (and their file extensions).
Wikipedia entries for each of the formats will give you quite a bit of information:
Image formats can be separated into three broad categories:
Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.
Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.
Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)
TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.
When to use a certain image compression format really depends on what is being compressed.
Related question: Ruthlessly compressing large images for the web
Why not keep things simple and use an adjacency matrix or an adjacency list?
To pip install a library exactly where I wanted it, I navigated to the location I wanted the directory with the terminal then used
pip install mylibraryName -t .
the logic of which I took from this page: https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/download
If you are using 5.5.x:
const UPDATED_AT = null;
And for 'created_at' field, you can use:
const CREATED_AT = null;
Make sure you are on the newest version. (This was broken in Laravel 5.5.0 and fixed again in 5.5.5).
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)
Note that the select query might return more than one value or rows. so you can write a select query that must return one row.
If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable
DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
As table type variable do not exist in Oracle and others, you would have to define it:
DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
-- Then to declare a TABLE variable of this type: variable_name type_name;
-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text'
;
-- Where 'n' is the index value
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
One way would be to use a nested query:
SELECT count(*)
FROM (
SELECT COUNT(Genre) AS count
FROM movies
GROUP BY ID
HAVING (count = 4)
) AS x
The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.
Very simple, you close it :)
var myWebSocket = new WebSocket("ws://example.org");
myWebSocket.send("Hello Web Sockets!");
myWebSocket.close();
Did you check also the following site And check the introduction article of Opera
This worked for me like a charm for downloading PNG and PDF.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url)); //Absolute URL
ob_clean();
flush();
readfile($file_url); //Absolute URL
exit();
There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php
ISO standard C++ doesn't let you do this. If it did, the syntax would probably be:
a::a(void) :
b({2,3})
{
// other initialization stuff
}
Or something along those lines. From your question it actually sounds like what you want is a constant class (aka static) member that is the array. C++ does let you do this. Like so:
#include <iostream>
class A
{
public:
A();
static const int a[2];
};
const int A::a[2] = {0, 1};
A::A()
{
}
int main (int argc, char * const argv[])
{
std::cout << "A::a => " << A::a[0] << ", " << A::a[1] << "\n";
return 0;
}
The output being:
A::a => 0, 1
Now of course since this is a static class member it is the same for every instance of class A. If that is not what you want, ie you want each instance of A to have different element values in the array a then you're making the mistake of trying to make the array const to begin with. You should just be doing this:
#include <iostream>
class A
{
public:
A();
int a[2];
};
A::A()
{
a[0] = 9; // or some calculation
a[1] = 10; // or some calculation
}
int main (int argc, char * const argv[])
{
A v;
std::cout << "v.a => " << v.a[0] << ", " << v.a[1] << "\n";
return 0;
}
len()
it will count the element in the list, tuple and string and dictionary, eg.
>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple
>>> len(tup)
3
To learn Python you can use byte of python , it is best ebook for python beginners.
The answer is nice, but it introduces one problem. Whenever you assign onload
or onerror
directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.
Let me rewrite the answer a little bit.
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);
The trim() method removes whitespace from both sides of a string.
You can use a Javascript replace method to remove white space like
"hello world".replace(/\s/g, "");
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
@Swapnil Niwane
I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.
$.ajax({
method: 'GET',
url: url,
defaultHeaders: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json'
},
dataType: 'jsonp',
success: function (response) {
console.log("success ");
console.log(response);
},
error: function (xhr) {
console.log("error ");
console.log(xhr);
}
});
try CAST
function in MySQL:
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('". $_POST['post_title'] ."',
CAST('". $date ."' AS DATE))") or die(mysql_error());
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
As others have pointed out, you can also use the equivalent built-in math.hypot()
:
dist = math.hypot(x2 - x1, y2 - y1)
That's because the event onsubmit
is triggered before the form is submitted.
Remove your onSubmit
and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.
On my laptop with spanish keyboard, the problem seems to be the "/" on the key binding, I changed it to ctrl+shift+c and now it works.
{ "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": true } },
The activity in which you want to add listview footer and i have also generate an event on listview footer click.
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list_of_f = (ListView) findViewById(R.id.list_of_f);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.web_view, null); // i have open a webview on the listview footer
RelativeLayout layoutFooter = (RelativeLayout) view.findViewById(R.id.layoutFooter);
list_of_f.addFooterView(view);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg" >
<ImageView
android:id="@+id/dept_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dept_nav" />
<ListView
android:id="@+id/list_of_f"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/dept_nav"
android:layout_margin="5dp"
android:layout_marginTop="10dp"
android:divider="@null"
android:dividerHeight="0dp"
android:listSelector="@android:color/transparent" >
</ListView>
</RelativeLayout>
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
You can break nested for loops with the word 'break', it works without any labels.
In your case you need to have a condition which is sufficient to break a loop.
Here's an example:
var arr = [[1,3], [5,6], [9,10]];
for (var a = 0; a<arr.length; a++ ){
for (var i=0; i<arr[a].length; i++) {
console.log('I am a nested loop and i = ' + i);
if (i==0) { break; }
}
console.log('first loop continues');
}
It logs the following:
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
> I am a nested loop and i = 0
> first loop continues
The return; statement does not work in this case. Working pen
Here you go: Working Fidddle
$(function(){
var dateFormat = 'DD-MM-YYYY';
alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
You can do it using old DirectShow functionality.
This answer teaches you how to create QuartzTypeLib.dll
:
Run tlbimp tool (in your case path will be different):
Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll
Alternatively, this project contains the library interop.QuartzTypeLib.dll
, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:
Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")
In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).
In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266
Use this class to play your favorite MP3 file:
using QuartzTypeLib;
public sealed class DirectShowPlayer
{
private FilgraphManager FilterGraph;
public void Play(string path)
{
FilgraphManager = new FilgraphManager();
FilterGraph.RenderFile(path);
FilterGraph.Run();
}
public void Stop()
{
FilterGraph?.Stop();
}
}
PS: TlbImp.exe
can be found here:
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"
, or in
"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"
All the above solutions are good, but I like @Steve's and @bejota's the best as they do not involve fancy calls and are universal.
By universal I mean that works with any type of axes including GeoAxes
. For example, it you have projected axes for mapping:
projection = cartopy.crs.UTM(zone='17N')
ax = plt.axes(projection=projection)
im = ax.imshow(np.arange(200).reshape((20, 10)))
a call to
cax = divider.append_axes("right", size=width, pad=pad)
will fail with: KeyException: map_projection
Therefore, the only universal way of dealing colorbar size with all types of axes is:
ax.colorbar(im, fraction=0.046, pad=0.04)
Work with fraction from 0.035 to 0.046 to get your best size. However, the values for the fraction and paddig will need to be adjusted to get the best fit for your plot and will differ depending if the orientation of the colorbar is in vertical position or horizontal.
Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.
now I'll show you a sample example that exaplain how can you update your model from server.
HTML Code:
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="updateData()">Refresh Data</button>
</div>
So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData()
that will be invoked when we are need to update and refresh our Model persons.
Javascript Code:
app.controller('adsController', function($log,$scope,...){
.....
$scope.updateData = function(){
$http.get('/persons').success(function(data) {
$scope.persons = data;// Update Model-- Line X
});
}
});
Now I explain for you how it work:
when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get()
and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.
VB sample:
@Html.ActionLink("Home", "Index", Nothing, New With {.style = "font-weight:bold;", .class = "someClass"})
Sample Css:
.someClass
{
color: Green !important;
}
In my case, I found that I need the !important attribute to over ride the site.css a:link css class
In my case, I messed up the connectionString
property in a publish profile, trying to access the wrong database (Initial Catalog
). Entity Framework then complains that the entities do not match the database, and rightly so.
For natural order : Arrays.sort(array)
For reverse Order : Arrays.sort(array, Collections.reverseOrder());
-- > It is a static method in Collections class which will further call an inner class of itself to return a reverse Comparator.
A straightforward approach:
def round_time(dt, round_to_seconds=60):
"""Round a datetime object to any number of seconds
dt: datetime.datetime object
round_to_seconds: closest number of seconds for rounding, Default 1 minute.
"""
rounded_epoch = round(dt.timestamp() / round_to_seconds) * round_to_seconds
rounded_dt = datetime.datetime.fromtimestamp(rounded_epoch).astimezone(dt.tzinfo)
return rounded_dt
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img>
element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
This solution might be a bit complicated, but boost-range
has also some other nice things to offer.
#include <iostream>
#include <vector>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
boost::copy(b, std::back_inserter(a));
for (auto& iter : a) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
Often ones intention is to combine vector a
and b
just iterate over it doing some operation. In this case, there is the ridiculous simple join
function.
#include <iostream>
#include <vector>
#include <boost/range/join.hpp>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
std::vector<int> c = { 7,8,9 };
// Just creates an iterator
for (auto& iter : boost::join(a, boost::join(b, c))) {
std::cout << iter << " ";
}
std::cout << "\n";
// Can also be used to create a copy
std::vector<int> d;
boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));
for (auto& iter : d) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
For large vectors this might be an advantage, as there is no copying. It can be also used for copying an generalizes easily to more than one container.
For some reason there is nothing like boost::join(a,b,c)
, which could be reasonable.
Here's how you can work with a custom schema, a complete demo:
$> shell code,
echo "
Slingo, iOS
Slingo, Android
" > game.csv
Scala code:
import org.apache.spark.sql.types._
val customSchema = StructType(Array(
StructField("game_id", StringType, true),
StructField("os_id", StringType, true)
))
val csv_df = spark.read.format("csv").schema(customSchema).load("game.csv")
csv_df.show
csv_df.orderBy(asc("game_id"), desc("os_id")).show
csv_df.createOrReplaceTempView("game_view")
val sort_df = sql("select * from game_view order by game_id, os_id desc")
sort_df.show
For chat applications or any other application that is in constant conversation with the server, WebSockets
are the best option. However, you can only use WebSockets
with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling
to obtain similar functionality.
Just another thing... Instead of System.out.println("Error Message Here")
, use System.err.println("Error Message Here")
. This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()
) in red.
NOTE: It also works when used with System.err.print("Error Message Here")
Try this:
$('#mySelectElement option')[0].selected = true;
Regards!
Note: The user agent strings from Facebook's internal browser do indicate the actual physical device. Even the cellphone carrier (eg. AT&T)
Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 [FBAN/FBIOS;FBAV/149.0.0.39.64;FBBV/79173879;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iOS;FBSV/10.3.3;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0
Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Mobile/15B93 [FBAN/FBIOS;FBAV/148.0.0.45.64;FBBV/78032376;FBDV/iPhone10,4;FBMD/iPhone;FBSN/iOS;FBSV/11.1;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0]
These won't be the case in Safari or Chrome from iOS - only within the browser inside the Facebook app.
(I'm getting iPhone9
too though - not quite sure what that is!)
self.navigationItem.setHidesBackButton(true, animated: false)
I think COALESCE
function partially similar to the isnull
, but try it.
Why don't you go for null handling functions through application programs, it is better alternative.
As mentionned in comments, this is the updated solution in favor of Icon object with documentation.
Use Icon object
var icon = {
url: "../res/sit_marron.png", // url
scaledSize: new google.maps.Size(50, 50), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
posicion = new google.maps.LatLng(latitud,longitud)
marker = new google.maps.Marker({
position: posicion,
map: map,
icon: icon
});
If you want a vertical divider between 2 columns, all you need is add
class="col-6 border-left"
to one of your column div-s
BUT
In the world of responsive design, you may need to make it disappear sometimes.
The solution is disappearing <hr>
+ disappearing <div>
+ margin-left: -1px;
<div class="container">
<div class="row">
<div class="col-md-7">
1 of 2
</div>
<div class="border-left d-sm-none d-md-block" style="width: 0px;"></div>
<div class="col-md-5" style="margin-left: -1px;">
<hr class="d-sm-block d-md-none">
2 of 2
</div>
</div>
</div>
https://jsfiddle.net/8z1pag7s/
tested on Bootstrap 4.1
$ postgres -V # Or --version. Use "locate bin/postgres" if not found.
postgres (PostgreSQL) 9.6.1
$ postgres -V | awk '{print $NF}' # Last column is version.
9.6.1
$ postgres -V | egrep -o '[0-9]{1,}\.[0-9]{1,}' # Major.Minor version
9.6
If having more than one installation of PostgreSQL, or if getting the "postgres: command not found
" error:
$ locate bin/postgres | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/pgsql-9.3/bin/postgres -V
postgres (PostgreSQL) 9.3.5
/usr/pgsql-9.6/bin/postgres -V
postgres (PostgreSQL) 9.6.1
If locate
doesn't help, try find
:
$ sudo find / -wholename '*/bin/postgres' 2>&- | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/pgsql-9.6/bin/postgres -V
postgres (PostgreSQL) 9.6.1
Although postmaster
can also be used instead of postgres
, using postgres
is preferable because postmaster
is a deprecated alias of postgres
.
As relevant, login as postgres
.
$ psql -V # Or --version
psql (PostgreSQL) 9.6.1
If having more than one installation of PostgreSQL:
$ locate bin/psql | xargs -i xargs -t '{}' -V # xargs is intentionally twice.
/usr/bin/psql -V
psql (PostgreSQL) 9.3.5
/usr/pgsql-9.2/bin/psql -V
psql (PostgreSQL) 9.2.9
/usr/pgsql-9.3/bin/psql -V
psql (PostgreSQL) 9.3.5
=> SELECT version();
version
--------------------------------------------------------------------------------------------------------------
PostgreSQL 9.2.9 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4), 64-bit
=> SHOW server_version;
server_version
----------------
9.2.9
=> SHOW server_version_num;
server_version_num
--------------------
90209
If more curious, try => SHOW all;
.
For what it's worth, a shell command can be executed within psql
to show the client version of the psql
executable in the path. Note that the running psql
can potentially be different from the one in the path.
=> \! psql -V
psql (PostgreSQL) 9.2.9
Things have been changed after conda 4.6.
Programs "Anaconda Prompt" and "Anaconda Powershell" expose the command conda
for you automatically. Find them in your startup menu.
If you don't wanna use the prompts above and try to make conda
available in a normal cmd.exe
and a Powershell. Read the following content.
conda
in Every ShellThe purpose of the following content is to make command conda
available both in cmd.exe
and Powershell on Windows.
If you have already checked "Add Anaconda to my PATH environment variable" during Anaconda installation, skip step 1.
If Anaconda is installed for the current use only, add %USERPROFILE%\Anaconda3\condabin
(I mean condabin
, not Scripts
) into the environment variable PATH
(the user one). If Anaconda is installed for all users on your machine, add C:\ProgramData\Anaconda3\condabin
into PATH
.
Open a new Powershell, run the following command once to initialize conda
.
conda init
These steps make sure the conda
command is exposed into your cmd.exe
and Powershell.
conda init
from Conda 4.6Caveat: Add the new \path\to\anaconda3\condabin
but not \path\to\anaconda3\Scripts
into your PATH
. This is a big change introduced in conda
4.6.
Activation script initialization fron conda
4.6 release log
Conda 4.6 adds extensive initialization support so that more shells than ever before can use the new
conda activate
command. For more information, read the output fromconda init –help
We’re especially excited about this new way of working, because removing the need to modifyPATH
makes Conda much less disruptive to other software on your system.
In the old days, \path\to\anaconda3\Scripts
is the one to be put into your PATH
. It exposes command conda
and the default Python from "base" environment at the same time.
After conda
4.6, conda
related commands are separated into condabin
. This makes it possible to expose ONLY command conda
without activating the Python from "base" environment.
The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.
Dim t as single
t = Timer
'code
MsgBox Timer - t
at -l
to list jobs, which gives return like this:
age2%> at -l
11 2014-10-21 10:11 a hoppent
10 2014-10-19 13:28 a hoppent
atrm 10
kills job 10
Or so my sysadmin told me, and it
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
In SL5 I found this to work:
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat=dd-MMMM-yy hh:mm}">
<TextBlock Name="textBlock" Text="{Binding JustificationDate, StringFormat='Justification Date: \{0:dd-MMMM-yy hh:mm\}'}">
subclass the handler you want to be able to disable temporarily:
class ToggledHandler(logging.StreamHandler):
"""A handler one can turn on and off"""
def __init__(self, args, kwargs):
super(ToggledHandler, self).__init__(*args, **kwargs)
self.enabled = True # enabled by default
def enable(self):
"""enables"""
self.enabled = True
def disable(self):
"""disables"""
self.enabled = False
def emit(self, record):
"""emits, if enabled"""
if self.enabled:
# this is taken from the super's emit, implement your own
try:
msg = self.format(record)
stream = self.stream
stream.write(msg)
stream.write(self.terminator)
self.flush()
except Exception:
self.handleError(record)
finding the handler by name is quite easy:
_handler = [x for x in logging.getLogger('').handlers if x.name == your_handler_name]
if len(_handler) == 1:
_handler = _handler[0]
else:
raise Exception('Expected one handler but found {}'.format(len(_handler))
once found:
_handler.disable()
doStuff()
_handler.enable()
This will do it:
cd ~/My\ Code
I've had to use that to work with files stored in the iCloud Drive. You won't want to use double quotes (") as then it must be an absolute path. In other words, you can't combine double quotes with tilde (~).
By way of example I had to use this for a recent project:
cd ~/Library/Mobile\ Documents/com~apple~CloudDocs/Documents/Documents\ -\ My\ iMac/Project
I hope that helps.
You could dispatching events like
el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
I don't know probably is too late to answer to this question. But if someone is in my situation and struggling with this problem will useful.
Few antivirus programs detect adb.exe as a virus. You should take a look in the place where antivirus is putting your detected threats and restore it from there. For Avast Antivirus
is inside of virus chest
Hope it will be useful for someone !
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
This arstechnica article describes the basic steps:
Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?
Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.
Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.
You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.
The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.
If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.
If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Declaring a variable as volatile means that modifying its value immediately affects the actual memory storage for the variable. The compiler cannot optimize away any references made to the variable. This guarantees that when one thread modifies the variable, all other threads see the new value immediately. (This is not guaranteed for non-volatile variables.)
Declaring an atomic variable guarantees that operations made on the variable occur in an atomic fashion, i.e., that all of the substeps of the operation are completed within the thread they are executed and are not interrupted by other threads. For example, an increment-and-test operation requires the variable to be incremented and then compared to another value; an atomic operation guarantees that both of these steps will be completed as if they were a single indivisible/uninterruptible operation.
Synchronizing all accesses to a variable allows only a single thread at a time to access the variable, and forces all other threads to wait for that accessing thread to release its access to the variable.
Synchronized access is similar to atomic access, but the atomic operations are generally implemented at a lower level of programming. Also, it is entirely possible to synchronize only some accesses to a variable and allow other accesses to be unsynchronized (e.g., synchronize all writes to a variable but none of the reads from it).
Atomicity, synchronization, and volatility are independent attributes, but are typically used in combination to enforce proper thread cooperation for accessing variables.
Addendum (April 2016)
Synchronized access to a variable is usually implemented using a monitor or semaphore. These are low-level mutex (mutual exclusion) mechanisms that allow a thread to acquire control of a variable or block of code exclusively, forcing all other threads to wait if they also attempt to acquire the same mutex. Once the owning thread releases the mutex, another thread can acquire the mutex in turn.
Addendum (July 2016)
Synchronization occurs on an object. This means that calling a synchronized method of a class will lock the this
object of the call. Static synchronized methods will lock the Class
object itself.
Likewise, entering a synchronized block requires locking the this
object of the method.
This means that a synchronized method (or block) can be executing in multiple threads at the same time if they are locking on different objects, but only one thread can execute a synchronized method (or block) at a time for any given single object.
you can also use for loop to append or write data to a file. example:
for i in {1..10}; do echo "Hello Linux Terminal"; >> file.txt done
">>" is used to append.
">" is used to write.
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
This code should work in all browsers.
function replaceContentInContainer(matchClass, content) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].innerHTML = content;
}
}
}
The way it works is by looping through all of the elements in the document, and searching their class list for matchClass
. If a match is found, the contents is replaced.
In my case i kept getting the same error message. I use fedora. I solved it by doing:
sudo dnf install pycurl
This installed eveything that I needed for it to work.
This error is usually caused by the missing Visual C++ Redistributable file
, which is a required dependency for most of the application on Windows Computer.
Download Visual C++ Redistributable from here and install it. After installing this, Reboot the system.
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
All others answers are related to jQuery UI datepicker
, but the question is about bootstrap-datepicker
.
You can use the on changeDate
event to trigger a change event on the related input, and then handle both ways of changing the date from the onChange
handler:
changeDate
Fired when the date is changed.
Example:
$('#dp3').datepicker().on('changeDate', function (ev) {
$('#date-daily').change();
});
$('#date-daily').val('0000-00-00');
$('#date-daily').change(function () {
console.log($('#date-daily').val());
});
Here is a working fiddle: http://jsfiddle.net/IrvinDominin/frjhgpn8/
Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".
the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
Another way of doing the same could be using the Gson Class
String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);
This will give an object obtained after parsing the json string to work with.
What suited my purpose was to create a div that was always bounded within the overall browser window by a fixed amount.
What worked, at least on firefox, was this
<div style="position: absolute; top: 127px; left: 75px;right: 75px; bottom: 50px;">
Insofar as the actual window is not forced into scrolling, the div preserves its boundaries to the window edge during all re-sizing.
Hope this saves someone some time.
Your schema is for its target namespace http://www.example.org/Test
so it defines an element with name MyElement
in that target namespace http://www.example.org/Test
. Your instance document however has an element with name MyElement
in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.
You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>
.
It is also used for debugging purposes.
Here is a handy list of some of these values:
http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values
A common PyTorch convention is to save models using either a .pt or .pth file extension.
Save/Load Entire Model Save:
path = "username/directory/lstmmodelgpu.pth"
torch.save(trainer, path)
Load:
model = torch.load(PATH)
model.eval()
Solved the issue. Change your class name to make only the first letter capitalized. so if you got something like 'MyClass' change it to 'Myclass'. apply it to both the file name and class name.
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to @Thisguyhastwothumbs
Run this query to check if the table exists in the database:
IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';
The range
function wil give you a list of numbers, while the for
loop will iterate through the list and execute the given code for each of its items.
for i in range(5):
print i
This simply executes print i
five times, for i ranging from 0 to 4.
for i in range(5):
a=i+1
This will execute a=i+1
five times. Since you are overwriting the value of a
on each iteration, at the end you will only get the value for the last iteration, that is 4+1.
Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html
A very simple way:
import * as myFunctionContainer from 'whatever-lib';
const fooSpy = spyOn(myFunctionContainer, 'myFunc');
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
You only need to use "copy":
On that's way you iterate over the original dictionary fields and on the fly can change the desired dict (d dict). It's work on each python version, so it's more clear.
In [1]: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
In [2]: for i in d.copy():
...: if not d[i]:
...: d.pop(i)
...:
In [3]: d
Out[3]: {'a': [1], 'b': [1, 2]}
You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.
In other words, after compilation,
DoesEntityExist<int>
is a different type to
DoesEntityExist<string>
This is how the compiler is able to enfore compile-time type safety.
For the scenario you describe, you should pass the type as an argument that can be examined at run time.
The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.
If you just need the indexed columns EXEC sp_helpindex 'TABLE_NAME'
Regarding the following solution:
grep -Fxq "$FILENAME" my_list.txt
In case you are wondering (as I did) what -Fxq
means in plain English:
F
: Affects how PATTERN is interpreted (fixed string instead of a regex)x
: Match whole lineq
: Shhhhh... minimal printingFrom the man file:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
(-F is specified by POSIX.)
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by POSIX.)
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is
found, even if an error was detected. Also see the -s or --no-messages option. (-q is specified by
POSIX.)
Here is another solution if you want to include different browsers in on file. If you and Mac user, from sublime menu go to, Tools > New Plugin. Delete the generated code and past the following:
import sublime, sublime_plugin
import webbrowser
class OpenBrowserCommand(sublime_plugin.TextCommand):
def run(self,edit,keyPressed):
url = self.view.file_name()
if keyPressed == "1":
navegator = webbrowser.get("open -a /Applications/Firefox.app %s")
if keyPressed == "2":
navegator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
if keyPressed == "3":
navegator = webbrowser.get("open -a /Applications/Safari.app %s")
navegator.open_new(url)
Save. Then open up User Keybindings. (Tools > Command Palette > "User Key bindings"), and add this somewhere to the list:
{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3"}}
Now open any html file in Sublime and use one of the keybindings, which it would open that file in your favourite browser.
enctype='multipart/form-data
is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.
If you want to allow a user to upload a file via a form, you must use this enctype.
In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.
I encountered the same issue, when jdk 1.7 was used to compile then jre 1.4 was used for execution.
My solution was to set environment variable PATH by adding pathname C:\glassfish3\jdk7\bin in front of the existing PATH setting. The updated value is "C:\glassfish3\jdk7\bin;C:\Sun\SDK\bin". After the update, the problem was gone.
I have upgraded my older version of WCF to WCF 4 with below changes, hope you can also make the similar changes.
1. Web.config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Demo_BasicHttp">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="InheritedFromHost"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="DemoServices.CalculatorService.ServiceImplementation.CalculatorService" behaviorConfiguration="Demo_ServiceBehavior">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="Demo_BasicHttp" contract="DemoServices.CalculatorService.ServiceContracts.ICalculatorServiceContract">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Demo_ServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add scheme="http" binding="basicHttpBinding" bindingConfiguration="Demo_BasicHttp"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
2. App.config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ICalculatorServiceContract" maxBufferSize="2147483647" maxBufferPoolSize="33554432" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="00:10:00">
<readerQuotas maxArrayLength="2147483647" maxBytesPerRead="4096" />
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" proxyCredentialType="None" realm="" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:24357/CalculatorService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICalculatorServiceContract" contract="ICalculatorServiceContract" name="Demo_BasicHttp" />
</client>
</system.serviceModel>
$request->route()->getName();
.NET 4.0 allows primary interop assemblies (or rather, the bits of it that you need) to be embedded into your assembly so that you don't need to deploy them alongside your application.
For whatever reason, this assembly can't be embedded - but it sounds like that's not a problem for you. Just open the Properties tab for the assembly in Visual Studio 2010 and set "Embed Interop Types" to "False".
EDIT: See also Michael Gustus's answer, removing the Class
suffix from the types you're using.
select Name, Value, AnotherColumn
from out_pumptable
where Value =
(
select Max(Value)
from out_pumptable as f where f.Name=out_pumptable.Name
)
group by Name, Value, AnotherColumn
Try like this, It works.
You should have font-weight set to 900 for Font Awesome 5 Free font-family to work.
This is the working one:
.css-selector::before {
font-family: 'Font Awesome 5 Free';
content: "\f101";
font-weight: 900;
}
Change the .env file as follow
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
And the go to the gmail security section ->Allow Less secure app access
Then run
php artisan config:clear
Refresh the site
You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ]
will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
.
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)
In your case, I would use shell form
ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"
I've been using Bitvise SSH Server and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, Tunnelier, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.
It's not Open Source and it costs $39.95, but I think it's worth it.
UPDATE 2009-05-21 11:10: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current pricing.
The method .attr() allows getting attribute value of the first element in a jQuery object:
$('#myelement').attr('name');
I am placing JLBorges's excellent response to a similar question verbatim from cplusplus.com, as it is the most succinct explanation I've read on the subject.
In a template that we write, there are two kinds of names that could be used - dependant names and non- dependant names. A dependant name is a name that depends on a template parameter; a non-dependant name has the same meaning irrespective of what the template parameters are.
For example:
template< typename T > void foo( T& x, std::string str, int count ) { // these names are looked up during the second phase // when foo is instantiated and the type T is known x.size(); // dependant name (non-type) T::instance_count ; // dependant name (non-type) typename T::iterator i ; // dependant name (type) // during the first phase, // T::instance_count is treated as a non-type (this is the default) // the typename keyword specifies that T::iterator is to be treated as a type. // these names are looked up during the first phase std::string::size_type s ; // non-dependant name (type) std::string::npos ; // non-dependant name (non-type) str.empty() ; // non-dependant name (non-type) count ; // non-dependant name (non-type) }
What a dependant name refers to could be something different for each different instantiation of the template. As a consequence, C++ templates are subject to "two-phase name lookup". When a template is initially parsed (before any instantiation takes place) the compiler looks up the non-dependent names. When a particular instantiation of the template takes place, the template parameters are known by then, and the compiler looks up dependent names.
During the first phase, the parser needs to know if a dependant name is the name of a type or the name of a non-type. By default, a dependant name is assumed to be the name of a non-type. The typename keyword before a dependant name specifies that it is the name of a type.
Summary
Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.
The docs for the spinner-widget says
A spinner does not support item click events.
You should use setOnItemSelectedListener
to handle your problem.
Yes.
See:
public static void main(String args[]) {
HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String,Object>>();
map.put("key", new HashMap<String, Object>());
map.get("key").put("key2", "val2");
System.out.println(map.get("key").get("key2"));
}
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
I have tried these hash functions and got the following result. I have about 960^3 entries, each 64 bytes long, 64 chars in different order, hash value 32bit. Codes from here.
Hash function | collision rate | how many minutes to finish
==============================================================
MurmurHash3 | 6.?% | 4m15s
Jenkins One.. | 6.1% | 6m54s
Bob, 1st in link | 6.16% | 5m34s
SuperFastHash | 10% | 4m58s
bernstein | 20% | 14s only finish 1/20
one_at_a_time | 6.16% | 7m5s
crc | 6.16% | 7m56s
One strange things is that almost all the hash functions have 6% collision rate for my data.
Yes, you can install Postman using these commands:
wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
rm postman.tar.gz
sudo ln -s /opt/Postman/Postman /usr/bin/postman
You can also get Postman to show up in the Unity Launcher:
cat > ~/.local/share/applications/postman.desktop <<EOL
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
EOL
You don't need node.js or any other dependencies with a standard Ubuntu dev install.
See more at our blog post at https://blog.bluematador.com/posts/postman-how-to-install-on-ubuntu-1604/.
EDIT: Changed icon.png location. Latest versions of Postman changed their directory structure slightly.
use -Wa,-adhln as option on gcc or g++ to produce a listing output to stdout.
-Wa,... is for command line options for the assembler part (execute in gcc/g++ after C/++ compilation). It invokes as internally (as.exe in Windows). See
>as --help
as command line to see more help for the assembler tool inside gcc
After much digging around we were able to scrape the info more or less (mainly from Keycloak's own JS client lib):
/auth/realms/{realm}/tokens/login
/auth/realms/{realm}/tokens/access/codes
As for OpenID Connect UserInfo, right now (1.1.0.Final) Keycloak doesn't implement this endpoint, so it is not fully OpenID Connect compliant. However, there is already a patch that adds that as of this writing should be included in 1.2.x.
But - Ironically Keycloak does send back an id_token
in together with the access token. Both the id_token
and the access_token
are signed JWTs, and the keys of the token are OpenID Connect's keys, i.e:
"iss": "{realm}"
"sub": "5bf30443-0cf7-4d31-b204-efd11a432659"
"name": "Amir Abiri"
"email: "..."
So while Keycloak 1.1.x is not fully OpenID Connect compliant, it does "speak" in OpenID Connect language.
ERROR
There was a mistake when I added to the same list from where I took elements:
fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
for (i in this) {
this.add(_fun(i)) <--- ERROR
}
return this <--- ERROR
}
DECISION
Works great when adding to a new list:
fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
val newList = mutableListOf<T>() <--- DECISION
for (i in this) {
newList.add(_fun(i)) <--- DECISION
}
return newList <--- DECISION
}
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
(server: ubuntu 14)
1.) install nvm (node version manager) https://github.com/creationix/nvm
2.) nvm install node
3.) npm -v (inquire npm version => 3.8.6)
4.) node -v (inquire node version => v6.0.0)
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position
other than static
set on it, too.
CSS:
#someDiv {
z-index:9;
}
Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
Be aware that need to change both location:
File > Settings... > Editor > Code Style > "Hard Wrap at"
and
File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at
Do I even need a for loop to create a list?
No, you can (and in general circumstances should) use the built-in function range()
:
>>> range(1,5)
[1, 2, 3, 4]
i.e.
def naturalNumbers(n):
return range(1, n + 1)
Python 3's range()
is slightly different in that it returns a range
object and not a list, so if you're using 3.x wrap it all in list()
: list(range(1, n + 1))
.
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)