Maybe you add keypress
or keydown
to the input fields and assign the event to function that will do the submit when enter is clicked.
Your template would look like this
<form (keydown)="keyDownFunction($event)">
<input type="text" />
</form
And you function inside the your class would look like this
keyDownFunction(event) {
if (event.keyCode === 13) {
alert('you just pressed the enter key');
// rest of your code
}
}
The typical command is:
docker container ls -f 'status=exited'
However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:
You can filter on multiple statuses by passing multiple filters on the status:
docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'
If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q
, and you can also limit to just the containers that exited successfully with an exit code filter:
docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')
For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering
I had similar issue with selenium: I downgraded my selenium using NuGet and got the same error message. My solution was to remove the newer version lines from the app.config file.
You can use %
:
SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'
I suspect this just hasn’t been implemented properly yet. The Swift Programming Guide definitely seems to imply that the compiler can infer exhaustive matches 'like a switch statement'. It doesn’t make any mention of needing a general catch
in order to be exhaustive.
You'll also notice that the error is on the try
line, not the end of the block, i.e. at some point the compiler will be able to pinpoint which try
statement in the block has unhandled exception types.
The documentation is a bit ambiguous though. I’ve skimmed through the ‘What’s new in Swift’ video and couldn’t find any clues; I’ll keep trying.
Update:
We’re now up to Beta 3 with no hint of ErrorType inference. I now believe if this was ever planned (and I still think it was at some point), the dynamic dispatch on protocol extensions probably killed it off.
Beta 4 Update:
Xcode 7b4 added doc comment support for Throws:
, which “should be used to document what errors can be thrown and why”. I guess this at least provides some mechanism to communicate errors to API consumers. Who needs a type system when you have documentation!
Another update:
After spending some time hoping for automatic ErrorType
inference, and working out what the limitations would be of that model, I’ve changed my mind - this is what I hope Apple implements instead. Essentially:
// allow us to do this:
func myFunction() throws -> Int
// or this:
func myFunction() throws CustomError -> Int
// but not this:
func myFunction() throws CustomErrorOne, CustomErrorTwo -> Int
Yet Another Update
Apple’s error handling rationale is now available here. There have also been some interesting discussions on the swift-evolution mailing list. Essentially, John McCall is opposed to typed errors because he believes most libraries will end up including a generic error case anyway, and that typed errors are unlikely to add much to the code apart from boilerplate (he used the term 'aspirational bluff'). Chris Lattner said he’s open to typed errors in Swift 3 if it can work with the resilience model.
well, this using lodash or vanilla javascript it depends on the situation.
but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id; // return the ones with equal id
});
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
You can do this more simply using plot()
instead of plot_date()
.
First, convert your strings to instances of Python datetime.date
:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
In your html you can pass in an array for the name i.e
<input type="text" name="address[]" />
This way php will receive an array of addresses.
In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.
That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap
Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.
You have four ways of accessing a specific item in a vector:
[]
operatorat(...)
std::for_each
from the algorithm
header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.In the following examples I will be using the following vector as a lab rat and explaining the first three methods:
static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));
This creates a vector as seen below:
1 2 3 4
First let's look at the []
way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the []
operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:
v[10] = 9;
This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100
instead of 234
, which is somewhat connected to that very location where you retrieve an item from you vector.
A much better way is to use at(...)
. This will automatically check for out of bounds
behaviour and break throwing an std::out_of_range
. So in the case when we have
v.at(10) = 9;
We will get:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)
The third way is similar to the []
operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:
std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9; // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...
As you can see we can also do
*(it+10) = 9;
which is again an invalid memory access. This is basically the same as using at(0 + offset)
but without the out of bounds error checking.
I would advice using at(...)
whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the []
operator.
Try This
DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '08/16/84'
SELECT @tmpdate = @date
SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())
SELECT Convert(Varchar(Max),@years)+' Years '+ Convert(Varchar(max),@months) + ' Months '+Convert(Varchar(Max), @days)+'days'
I think as simple as below would give you what you are looking for.
In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']
You can do this with a combination of map
and lambda
as well but list comprehension looks more elegant and pythonic.
For a smaller input list comprehension is way to go but if the input is really big then i guess generators are the ideal way.
In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'
Here is a comparison of all possible solutions for bigger input
In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
...: for i in l:
...: yield i.get('value', None)
...:
In[4]: def list_comp_verison():
...: return [i.get('value', None) for i in l]
...:
In[5]: def list_verison():
...: ll = []
...: for i in l:
...: ll.append(i.get('value', None))
...: return ll
In[10]: def map_lambda_version():
...: m = map(lambda i:i.get('value', None), l)
...: return m
...:
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
As you can see, generators are a better solution in comparison to the others, map is also slower compared to generator for reason I will leave up to OP to figure out.
xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>
</body></head>");
Make sure that you're using the latest version of JSch. I had this exact same problem when using JSch 0.1.31 and trying to connect to a RedHat 5 server. Updating to the latest version solved the problem.
You can do this replacing position:absolute;
by position:fixed;
.
$(document).ready(function() {
// do needed things
});
This will trigger once the DOM structure is ready.
Try regular expressions. You can find a certain pattern in your text and replace it with something that you want. I can't give you the exact code right now but you can test out your expressions using this.
Just had the same problem adding menu items to Wordpress. I am using Wordpress 4.9.9 on Ubuntu 18.04, PHP 7.0. I simply uncommented the following line and increased it to 1500 in /etc/php/7.0/apache2/php.ini
; How many GET/POST/COOKIE input variables may be accepted<br>
max_input_vars = 1500
Then used the following to effect the change:
sudo apache2ctl configtest #(if it does not return ok Apache will not start)
sudo service apache2 reload
Hope that helps.
As of version 8.0 (2018), MySQL finally supports window functions.
Window functions are both handy and efficient. Here is a solution that demonstrates how to use them to solve this assignment.
In a subquery, we can use ROW_NUMBER()
to assign a position to each record in the table within column1/column2
groups, ordered by id
. If there is no duplicates, the record will get row number 1
. If duplicate exists, they will be numbered by ascending id
(starting at 1
).
Once records are properly numbered in the subquery, the outer query just deletes all records whose row number is not 1.
Query :
DELETE FROM tablename
WHERE id IN (
SELECT id
FROM (
SELECT
id,
ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id) rn
FROM output
) t
WHERE rn > 1
)
I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS. I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack. It will also hold the connections open until they time-out in order to slow the client down in his attacks.
Multiple connection coming from different machines/IP's should not be a problem however.
There's more info in this MSDN post:
http://msdn.microsoft.com/en-us/library/bb463275.aspx
Check out the MaxConcurrentSession sproperty.
Most of these answers either does not answer the question or is unnecessarily long in the explanation.
OK so JSON only uses double quotation marks, we get that!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:
var d = {
name: 'whatever',
address: 'whatever',
DOB: '01/01/2001'
}
$.ajax({
type: "POST",
url: 'some/url',
dataType: 'json',
data: JSON.stringify(d),
...
}
This will escape the characters for you.
This was also suggested by Mark Amery, Great answer BTW
Hope this helps someone.
Try library(getopt) ... if you want things to be nicer. For example:
spec <- matrix(c(
'in' , 'i', 1, "character", "file from fastq-stats -x (required)",
'gc' , 'g', 1, "character", "input gc content file (optional)",
'out' , 'o', 1, "character", "output filename (optional)",
'help' , 'h', 0, "logical", "this help"
),ncol=5,byrow=T)
opt = getopt(spec);
if (!is.null(opt$help) || is.null(opt$in)) {
cat(paste(getopt(spec, usage=T),"\n"));
q();
}
Use curl
to fetch the HTTP-header only (not the whole file) and parse it:
$ curl -I --stderr /dev/null http://www.google.co.uk/index.html | head -1 | cut -d' ' -f2
200
You can’t really — background colours apply to the entirely of element backgrounds. Keeps ’em simple.
You could define a CSS gradient with sharp colour boundaries for the background instead, e.g.
background: -webkit-linear-gradient(left, grey, grey 30%, white 30%, white);
But only a few browsers support that at the moment. See http://jsfiddle.net/UES6U/2/
(See also http://www.webkit.org/blog/1424/css3-gradients/ for an explanation CSS3 gradients, including the sharp colour boundary trick.)
I do this like that:
if (listView1.SelectedItems.Count > 0)
{
var item = listView1.SelectedItems[0];
//rest of your logic
}
Graphically, the cron syntax for Quarz is (source):
+-------------------- second (0 - 59)
| +----------------- minute (0 - 59)
| | +-------------- hour (0 - 23)
| | | +----------- day of month (1 - 31)
| | | | +-------- month (1 - 12)
| | | | | +----- day of week (0 - 6) (Sunday=0 or 7)
| | | | | | +-- year [optional]
| | | | | | |
* * * * * * * command to be executed
So if you want to run a command every 30 minutes you can say either of these:
0 0/30 * * * * ?
0 0,30 * * * * ?
You can check crontab expressions using either of these:
To hide Navigation bar :
[self.navigationController setNavigationBarHidden:YES animated:YES];
To show Navigation bar :
[self.navigationController setNavigationBarHidden:NO animated:YES];
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
I've also thought of this. Finally, my solution is to use github gist. Don't forget it also has highlight functionality. Just copy it. :)
Lets check how the comparison with null is defined:
static void Main()
{
Console.WriteLine($"null != null => {null != null}");
Console.WriteLine($"null == null => {null == null}");
Console.WriteLine($"null != true => {null != true}");
Console.WriteLine($"null == true => {null == true}");
Console.WriteLine($"null != false => {null != false}");
Console.WriteLine($"null == false => {null == false}");
}
and the results are:
null != null => False
null == null => True
null != true => True
null == true => False
null != false => True
null == false => False
So you can safely use:
// check if null or false
if (nullable != true) ...
// check if null or true
if (nullable != false) ...
// check if true or false
if (nullable != null) ...
Here is my Leetcode solution using Binary Search:->
class Solution:
def binary_search(self,s,x):
low=0
high=len(s)-1
flag=1
while low<=high:
mid=(high+low)//2
if s[mid]==x:
flag=0
break
elif s[mid]<x:
low=mid+1
else:
high=mid-1
if flag:
s[low]=x
return s
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums:
return 0
s=[]
s.append(nums[0])
for i in range(1,len(nums)):
if s[-1]<nums[i]:
s.append(nums[i])
else:
s=self.binary_search(s,nums[i])
return len(s)
Raising an event when a property changes is precisely what INotifyPropertyChanged does. There's one required member to implement INotifyPropertyChanged and that is the PropertyChanged event. Anything you implemented yourself would probably be identical to that implementation, so there's no advantage to not using it.
You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use
&
infoo(&$a);
.
For example, instead of using:
// Wrong way!
myFunc(&$arg); # Deprecated pass-by-reference argument
function myFunc($arg) { }
Use:
// Right way!
myFunc($var); # pass-by-value argument
function myFunc(&$arg) { }
When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".
And than replace all "Milan" Strings with "Milan Vasic".
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
Mainly invalid query strings will give this warning.
Wrong due to a subtle syntax error (misplaced right parenthesis) when using INSTR
function:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active'>0);
Correct:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active')>0;
You want str replace, because performance-wise it's much cheaper and still fits your needs!
$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);
(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)
Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...
In my case,
Build Phases -> check Compile Sources files -> delete xxx.swift files that xcode says "can't find "xxx.swift"
BookTitle
have a Composite key. so if the key of BookTitle
is referenced as a foreign key
you have to bring the complete composite key.
So to resolve the problem you need to add the complete composite key in the BookCopy
. So add ISBN
column as well. and they at the end.
foreign key (ISBN, Title) references BookTitle (ISBN, Title)
I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.
The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:
FileUpload fileUpload = new FileUpload();
is not inside a function in your code behind.
If you want to detect links with http:// OR without http:// OR ftp OR other possible cases like removing trailing punctuation at the end, take a look at this code.
https://jsfiddle.net/AndrewKang/xtfjn8g3/
A simple way to use that is to use NPM
npm install --save url-knife
By using very simple method, we can follow this:
$http({
url : "submit_form_adv.php",
method : 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p)+' = '+encodeURIComponent(obj[p]));
return str.join('&');
},
data : {sample_id : 100, sample_name: 'Abin John'},
}).success(function(data, status, headers, config) {
}).error(function(ata, status, headers, config) {
});
I got this problem, and tried many ways to solve it. Finally, it turned out that make clean
and make
again solved it. The reason is:
I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean
saved the day.
The accepted answer is good, but it does NOT solve the problem when we need our component to reflect changes in URL.
Say, your component's code is something like:
export const Customer = (props) => {
const history = useHistory();
...
}
And you change URL:
const handleGoToPrev = () => {
history.push(`/app/customer/${prevId}`);
}
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import store from '../store/store';
export const PrivateRoute = ({ component: Component, ...rest }) => {
let isLoggedIn = !!store.getState().data.user;
return (
<Route {...rest} render={props => isLoggedIn
? (
<Component key={props.match.params.id || 'empty'} {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
} />
)
}
<PrivateRoute exact path="/app/customer/:id" component={Customer} />
just hope to improve FILE macro a bit:
#define FILE (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
this catches / and \, like Czarek Tomczak requested, and this works great in my mixed environment.
Try tagging it with:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
The '-Wait' option seemed to block for me even though my process had finished.
I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.
So:
$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :
@Service
public class ClassB {
private ClassA classA;
@Autowired
public ClassB(ClassA classA) {
this.classA = classA;
}
public void useClassAObjectHere(){
classA.callMethodOnObjectA();
}
}
Appearently Browsers still have troubles (although Chrome and Firefox Nightly do fine). I have a hacky approach for the people that really have to use a number field (maybe because of the little arrows that text fields dont have).
I added a keyup
event Handler to the form input and tracked the state and set the value once it comes valid again.
var currentString = '';_x000D_
var badState = false;_x000D_
var lastCharacter = null;_x000D_
_x000D_
document.getElementById("field").addEventListener("keyup",($event) => {_x000D_
if ($event.target.value && !$event.target.validity.badInput) {_x000D_
currentString = $event.target.value;_x000D_
} else if ($event.target.validity.badInput) {_x000D_
if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {_x000D_
$event.target.value = ((+currentString) + (+$event.key / 10));_x000D_
badState = false;_x000D_
} else {_x000D_
badState = true;_x000D_
}_x000D_
}_x000D_
document.getElementById("number").textContent = $event.target.value;_x000D_
lastCharacter = $event.key;_x000D_
});_x000D_
_x000D_
document.getElementById("field").addEventListener("blur",($event) => {_x000D_
if (badState) {_x000D_
$event.target.value = (+currentString);_x000D_
badState = false;_x000D_
document.getElementById("number").textContent = $event.target.value;_x000D_
}_x000D_
});
_x000D_
#result{_x000D_
padding: 10px;_x000D_
background-color: orange;_x000D_
font-size: 25px;_x000D_
width: 400px;_x000D_
margin-top: 10px;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
#field{_x000D_
padding: 5px;_x000D_
border-radius: 5px;_x000D_
border: 1px solid grey;_x000D_
width: 400px;_x000D_
}
_x000D_
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">_x000D_
_x000D_
<span id="result" >_x000D_
<span >Current value: </span>_x000D_
<span id="number"></span>_x000D_
</span>
_x000D_
@Directive({_x000D_
selector: '[appFloatHelper]'_x000D_
})_x000D_
export class FloatHelperDirective {_x000D_
private currentString = '';_x000D_
private badState = false;_x000D_
private lastCharacter: string = null;_x000D_
_x000D_
@HostListener("blur", ['$event']) onBlur(event) {_x000D_
if (this.badState) {_x000D_
this.model.update.emit((+this.currentString));_x000D_
this.badState = false;_x000D_
}_x000D_
}_x000D_
_x000D_
constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {_x000D_
this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {_x000D_
if (el.nativeElement.value && !el.nativeElement.validity.badInput) {_x000D_
this.currentString = el.nativeElement.value;_x000D_
} else if (el.nativeElement.validity.badInput) {_x000D_
if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {_x000D_
model.update.emit((+this.currentString) + (+e.key / 10));_x000D_
el.nativeElement.value = (+this.currentString) + (+e.key / 10);_x000D_
this.badState = false;_x000D_
} else {_x000D_
this.badState = true;_x000D_
}_x000D_
} _x000D_
this.lastCharacter = e.key;_x000D_
});_x000D_
}_x000D_
_x000D_
}
_x000D_
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">
_x000D_
I was frustrated trying to connect my Android App to my RESTful service using https. Also I was a bit annoyed about all the answers that suggested to disable certificate checking altogether. If you do so, whats the point of https?
After googled about the topic for a while, I finally found this solution where external jars are not needed, just Android APIs. Thanks to Andrew Smith, who posted it on July, 2014
/**
* Set up a connection to myservice.domain using HTTPS. An entire function
* is needed to do this because myservice.domain has a self-signed certificate.
*
* The caller of the function would do something like:
* HttpsURLConnection urlConnection = setUpHttpsConnection("https://littlesvr.ca");
* InputStream in = urlConnection.getInputStream();
* And read from that "in" as usual in Java
*
* Based on code from:
* https://developer.android.com/training/articles/security-ssl.html#SelfSigned
*/
public static HttpsURLConnection setUpHttpsConnection(String urlString)
{
try
{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// My CRT file that I put in the assets folder
// I got this file by following these steps:
// * Go to https://littlesvr.ca using Firefox
// * Click the padlock/More/Security/View Certificate/Details/Export
// * Saved the file as littlesvr.crt (type X.509 Certificate (PEM))
// The MainActivity.context is declared as:
// public static Context context;
// And initialized in MainActivity.onCreate() as:
// MainActivity.context = getApplicationContext();
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("littlesvr.crt"));
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
return urlConnection;
}
catch (Exception ex)
{
Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
return null;
}
}
It worked nice for my mockup App.
I found the answer here:
https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery
Basically, if you want to check one radio button, you MUST pass the value as an array:
$('input:radio[name=cols]').val(['Site']);
$('input:radio[name=rows]').val(['Site']);
It seems there are pros and cons to using either ??
or ?:
. The pro to using ?:
is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ??
the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else
.
The following is an example of the difference of using the ??
operator using both null and false:
$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---
$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---
By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:
$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---
Personally, I think it would be really nice if a future rev of PHP included another new operator: :?
that replaced the above syntax. ie:
// $var = $false :? "true";
That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://....',
success: function () {
alert("done!"+ geturl.getAllResponseHeaders());
}
});
dplyr package could be nice alternative to this problem:
library(dplyr)
df %>%
group_by(group) %>%
summarize(mean = mean(dt),
sum = sum(dt))
To get 1st quadrant and 3rd quadrant
df %>%
group_by(group) %>%
summarize(q1 = quantile(dt, 0.25),
q3 = quantile(dt, 0.75))
According to the Documentation :
MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message
Here MailAddressCollection has a in built method called
public void Add(string addresses)
1. Summary:
Add a list of email addresses to the collection.
2. Parameters:
addresses:
*The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
*email addresses must be separated with a comma character (",").
Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma
In your case :
simply replace all the ; with ,
Msg.To.Add(toEmail.replace(";", ","));
For reference :
I don't suggest you to use syntax like you did. AngularJs lets you to have different functionalities as you want (run
, config
, service
, factory
, etc..), which are more professional.In this function you don't even have to inject that by yourself like
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
you can use it, as you know.
A simpler way of doing this is to use a global js variable that simply holds the id of the clicked radio button. Then you don't have to waste code spinning thru your radio lists looking for the selected value. I have done this in cases where I have a dynamically generated list of 100 or more radio buttons. spinning thru them is (almost imperceptible) slow, but this is an easier solution.
you can also do this with the id, but you usually just want the value.
<script>
var gRadioValue = ''; //global declared outside of function
function myRadioFunc(){
var radioVal = gRadioValue;
// or maybe: var whichRadio = document.getElementById(gWhichCheckedId);
//do somethign with radioVal
}
<script>
<input type="radio" name="rdo" id="rdo1" value="1" onClick="gRadioValue =this.value;"> One
<input type="radio" name="rdo" id="rdo2" value="2" onClick="gRadioValue =this.value;"> Two
...
<input type="radio" name="rdo" id="rdo99" value="99" onClick="gRadioValue =this.value;"> 99
File -> Preferences -> Settings or just press Ctrl + , and search for spaces, then just deactivate this option:
I had to reopen the file so the changes would take effect.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
I know it not right way. It is not break the loop. It is a Jugad
let result = true;_x000D_
[1, 2, 3].forEach(function(el) {_x000D_
if(result){_x000D_
console.log(el);_x000D_
if (el === 2){_x000D_
result = false;_x000D_
}_x000D_
}_x000D_
});
_x000D_
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by
with out the need of any aggregate functions.
So the query can be simplified to this.
select * from comments_table group by commentname;
Try out the query in action here
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
It's easy,this is my solution using objects!
My POJO
public class Person implements Serializable{
private String name;
private int age;
//get & set
}
Method Notification
Person person = new Person();
person.setName("david hackro");
person.setAge(10);
Intent notificationIntent = new Intent(this, Person.class);
notificationIntent.putExtra("person",person);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
.setPriority(2)
.setLargeIcon(bm)
.setTicker(fotomulta.getTitle())
.setContentText(fotomulta.getMessage())
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setContentTitle(fotomulta.getTicketText())
.setDefaults(Notification.DEFAULT_ALL);
New Activity
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_push);
person = (Person) getIntent().getSerializableExtra("person");
}
Good Luck!!
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Or using Joda Time, you can use ISODateTimeFormat.dateTime()
.
Collection Interface has 3 views
Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct
My addition: How to convert "key-value pair" (aka entrySet)into list.
Map m=new HashMap();
m.put(3, "dev2");
m.put(4, "dev3");
List<Entry> entryList = new ArrayList<Entry>(m.entrySet());
for (Entry s : entryList) {
System.out.println(s);
}
ArrayList has this constructor.
Try this option.
update that coding part in Page_Load event before catching IsPostback
TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");
I haven't tested your code, just tried to help you understand how it operates in comment;
WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID
The simplest example of a recursive CTE
I can think of to illustrate its operation is;
;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
)
SELECT n
FROM Numbers
Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.
A1:
In this case, N
is not a variable. N
is an alias. It is the equivalent of SELECT 1 AS N
. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE
in T-SQL
. I've included the analog of a simple CTE
in Excel
to try and illustrate in a more familiar way what is happening.
-- Outside
;WITH CTE (MyColName) AS
(
SELECT 1
)
-- Inside
;WITH CTE AS
(
SELECT 1 AS MyColName
-- Or
SELECT MyColName = 1
-- Etc...
)
Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager
A2:
Does this code answer your question?
--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL
SELECT 5, 'Tridip', NULL UNION ALL
SELECT 6, 'Arijit', 5 UNION ALL
SELECT 7, 'Amit', 5 UNION ALL
SELECT 8, 'Dev', 6
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
-- Anchor
SELECT ID
,Name
,MgrID
,nLevel = 1
,Family = ROW_NUMBER() OVER (ORDER BY Name)
FROM Employee
WHERE MgrID IS NULL
UNION ALL
-- Recursive query
SELECT E.ID
,E.Name
,E.MgrID
,H.nLevel+1
,Family
FROM Employee E
JOIN Hierarchy H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel
SELECT ID,space(nLevel+
(CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
)+Name
FROM Hierarchy
ORDER BY Family, nLevel
A generic solution especially for Windows Edge browser (as the -ms-user-select: none; CSS rule doesn't work):
window.ondragstart = function() {return false}
Note: This can save you having to add draggable="false"
to every img
tag when you still need the click event (i.e. you can't use pointer-events: none
), but don't want the drag icon image to appear.
You can use the #Requires
statement (supports modules from PowerShell 3.0).
The #Requires statement prevents a script from running unless the PowerShell version, modules, snap-ins, and module and snap-in version prerequisites are met.
So At the top of the script, simply add #Requires -Module <ModuleName>
If the required modules are not in the current session, PowerShell imports them.
If the modules cannot be imported, PowerShell throws a terminating error.
For an extensive coverage review the contents of RFC2965. Of course that doesn't necessarily mean that all browsers behave exactly the same way.
However in general the rule for default Path if none specified in the cookie is the path in the URL from which the Set-Cookie header arrived. Similarly the default for the Domain is the full host name in the URL from which the Set-Cookie arrived.
Matching rules for the domain require the cookie Domain to match the host to which the request is being made. The cookie can specify a wider domain match by include *. in the domain attribute of Set-Cookie (this one area that browsers may vary). Matching the path (assuming the domain matches) is a simple matter that the requested path must be inside the path specified on the cookie. Typically session cookies are set with path=/ or path=/applicationName/ so the cookie is available to all requests into the application.
*
I'm unable to test this right now but I have an inkling that at least IE7/6 would treat the path example.com
as if it were .example.com
.
You can use Batch update but queries must be action(i.e. insert,update and delete) queries
Statement s = c.createStatement();
String s1 = "update emp set name='abc' where salary=984";
String s2 = "insert into emp values ('Osama',1420)";
s.addBatch(s1);
s.addBatch(s2);
s.executeBatch();
I ran into this problem with templated classes. Here's a more general solution I had to use:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// Friend means operator<< can use private variables
// It needs to be declared as a template, but T is taken
template <class U>
friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}
// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
obj.toString(os);
return os;
}
Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.
The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(
Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.
This works too:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// For some reason this requires using T, and not U as above
friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
{
obj.toString(os);
return os;
}
}
I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.
Eg 9 / 4 = 2.25
int(9) / int(4) = 2
9 / 4 - remainder / deniminator = 2
9 /4 - 9 % 4 / 4 = 2
Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.
I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?
The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {...
- which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.
function parseMyXML ($xml) { //pass in an XML string
$myXML = new XMLReader();
$myXML->xml($xml);
while ($myXML->read()) { //start reading.
if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myXML->name; //make $tag contain the name of the tag
switch ($tag) {
case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
$variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
break;
case 'Tag2': //this tag contains child elements, of which we only want one.
while($myXML->read()) { //so we tell it to keep reading
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
$variable2 = $myXML->readInnerXML(); //...put it in $variable2.
break;
}
}
break;
case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
while($myXML->read()) {
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
$variable3 = $myXML->readInnerXML();
break;
} else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
$variable4 = $myXML->readInnerXML();
break;
}
}
break;
}
}
}
$myXML->close();
}
If you really don't want to use any server controls, you should put the Response.Write
in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
For an alternative solution, check if you added your app to settings.gradle successfully
include ':app'
You can wrap the following in a DIV:
<div class="your-class">
<label for="First_Name">First Name:</label>
<input name="first_name" id="First_Name" type="text" />
<label for="Name">Last Name:</label>
<input name="last_name" id="Last_Name" type="text" />
</div>
Give each input float:left
in your CSS:
.your-class input{
float:left;
}
example only
You might have to adjust margins.
Remember to apply clear:left
or both to whatever comes after ".your-class"
I ran into this issue as well and found this post. Ultimately none of these answers solved my problem, instead I had to put in a rewrite rule to strip out the location /rt
as the backend my developers made was not expecting any additional paths:
+-(william@wkstn18)--(Thu, 05 Nov 20)-+
+-(~)--(16:13)->wscat -c ws://WebsocketServerHostname/rt
error: Unexpected server response: 502
Testing with wscat repeatedly gave a 502 response. Nginx error logs provided the same upstream error as above, but notice the upstream string shows the GET Request is attempting to access localhost:12775/rt and not localhost:12775:
2020/11/05 22:13:32 [error] 10175#10175: *7 upstream prematurely closed
connection while reading response header from upstream, client: WANIP,
server: WebsocketServerHostname, request: "GET /rt/socket.io/?transport=websocket
HTTP/1.1", upstream: "http://127.0.0.1:12775/rt/socket.io/?transport=websocket",
host: "WebsocketServerHostname"
Since the devs had not coded their websocket (listening on 12775) to expect /rt/socket.io but instead just /socket.io/ (NOTE: /socket.io/ appears to just be a way to specify websocket transport discussed here). Because of this, rather than ask them to rewrite their socket code I just put in a rewrite rule to translate WebsocketServerHostname/rt to WebsocketServerHostname:12775 as below:
upstream websocket-rt {
ip_hash;
server 127.0.0.1:12775;
}
server {
listen 80;
server_name WebsocketServerHostname;
location /rt {
proxy_http_version 1.1;
#rewrite /rt/ out of all requests and proxy_pass to 12775
rewrite /rt/(.*) /$1 break;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://websocket-rt;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
There is a javascript library DNS-JS.com that does just this.
DNS.Query("dns-js.com",
DNS.QueryType.A,
function(data) {
console.log(data);
});
First check if your wlan card support hosted network and if no update the card driver. Follow this steps
1) open cmd with administrative rights
2) on the black screen type: netsh wlan show driver | findstr Hosted
3) See Hosted network supported, if No then update drivers
I solved my z-index
problem by making the body wrapper z-index:-1
and the body z-index:-2
, and the other divs z-index:1
.
And then the later divs didn't work unless I had z-index
200+. Even though I had position:relative
on each element, with the body at default z-index
it wouldn't work.
Hope this helps somebody.
Copying the Bold Text From one sheet to another sheet in excel By using VBScript 'Create instance Object
Set oXL = CreateObject("Excel.application")
oXL.Visible = True
Set oWB = oXL.Workbooks.Open("FilePath.xlsx")
Set oSheet = oWB.Worksheets("Sheet1") 'Source Sheet in workbook
Set oDestSheet = oWB.Worksheets("Sheet2") 'Destination sheet in workbook
r = oSheet.usedrange.rows.Count
c = oSheet.usedrange.columns.Count
For i = 1 To r
For j = 1 To c
If oSheet.Cells(i,j).font.Bold = True Then
oSheet.cells(i,j).copy
oDestSheet.Cells(i,j).pastespecial
End If
Next
Next
oWB.Close
oXL.Quit
private void button1_Click(object sender, EventArgs e)
{
long myTicks = 633896886277130000;
DateTime dtime = new DateTime(myTicks);
MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
}
Gives
September 27, 2009
Is that what you need?
I don't see how that format is necessarily easy to work with in SQL queries, though.
Have you checked the docstring of write()
? It says:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
So you need to convert y
to str
first.
Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0)
to get to the beginning of the file.`
Edit: As for the IOError
, this issue seems related. A cite from there:
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.
So, I suggest you try f.seek(0)
and maybe the problem goes away.
Try the following in viewDidLoad
self.navigationItem.title = "Your Title"
Maybe, something like
for t in threading.enumerate():
if t.daemon:
t.join()
Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.
In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).
Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
SubToBeCalled
End If
End Sub
This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.
Cheers!
Prior to Flask 0.11, jsonfiy
would not allow returning an array directly. Instead, pass the list as a keyword argument.
@app.route('/get_records')
def get_records():
results = [
{
"rec_create_date": "12 Jun 2016",
"rec_dietary_info": "nothing",
"rec_dob": "01 Apr 1988",
"rec_first_name": "New",
"rec_last_name": "Guy",
},
{
"rec_create_date": "1 Apr 2016",
"rec_dietary_info": "Nut allergy",
"rec_dob": "01 Feb 1988",
"rec_first_name": "Old",
"rec_last_name": "Guy",
},
]
return jsonify(results=list)
Use the vbcrlf
for new line in SSSR. e.g.
= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1")
Create site/includes/.htaccess
file and add this line:
Deny from all
Good question, although not a trivial one to answer.
Defines how transactions relate to each other. Common options:
REQUIRED
: Code will always run in a transaction. Creates a new transaction or reuses one if available.REQUIRES_NEW
: Code will always run in a new transaction. Suspends the current transaction if one exists.Defines the data contract between transactions.
ISOLATION_READ_UNCOMMITTED
: Allows dirty reads.ISOLATION_READ_COMMITTED
: Does not allow dirty reads.ISOLATION_REPEATABLE_READ
: If a row is read twice in the same transaction, the result will always be the same. ISOLATION_SERIALIZABLE
: Performs all transactions in a sequence.The different levels have different performance characteristics in a multi-threaded application. I think if you understand the dirty reads
concept you will be able to select a good option.
Example of when a dirty read can occur:
thread 1 thread 2
| |
write(x) |
| |
| read(x)
| |
rollback |
v v
value (x) is now dirty (incorrect)
So a sane default (if such can be claimed) could be ISOLATION_READ_COMMITTED
, which only lets you read values which have already been committed by other running transactions, in combination with a propagation level of REQUIRED
. Then you can work from there if your application has other needs.
A practical example of where a new transaction will always be created when entering the provideService
routine and completed when leaving:
public class FooService {
private Repository repo1;
private Repository repo2;
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void provideService() {
repo1.retrieveFoo();
repo2.retrieveFoo();
}
}
Had we instead used REQUIRED
, the transaction would remain open if the transaction was already open when entering the routine.
Note also that the result of a rollback
could be different as several executions could take part in the same transaction.
We can easily verify the behaviour with a test and see how results differ with propagation levels:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:/fooService.xml")
public class FooServiceTests {
private @Autowired TransactionManager transactionManager;
private @Autowired FooService fooService;
@Test
public void testProvideService() {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
fooService.provideService();
transactionManager.rollback(status);
// assert repository values are unchanged ...
}
With a propagation level of
REQUIRES_NEW
: we would expect fooService.provideService()
was NOT rolled back since it created it's own sub-transaction.
REQUIRED
: we would expect everything was rolled back and the backing store was unchanged.
First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).
You just have to put your const outside your class declaration.
Two possibilities : Declare your const in your class file (your const have a clear relation with your class)
private const val CONST_USED_BY_MY_CLASS = 1
class MyClass {
// I can use my const in my class body
}
Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :
package com.project.constants
const val URL_PATH = "https:/"
Then you just have to import it where you need it :
import com.project.constants
MyClass {
private fun foo() {
val url = URL_PATH
System.out.print(url) // https://
}
}
This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :
MyClass {
companion object {
private const val URL_PATH = "https://"
const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
}
}
Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :
MyClass {
companion object {
val URL_PATH = "https://"
}
}
In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.
@JvmField val foo = Foo()
Since Django 2.0 the ForeignKey field requires two positional arguments:
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)
Here are some methods can used in on_delete
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.
Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.
you can find more about on_delete by reading the documentation.
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
It allows the Entity Framework to create a proxy around the virtual property so that the property can support lazy loading and more efficient change tracking. See What effect(s) can the virtual keyword have in Entity Framework 4.1 POCO Code First? for a more thorough discussion.
Edit to clarify "create a proxy around":
By "create a proxy around" I'm referring specifically to what the Entity Framework does. The Entity Framework requires your navigation properties to be marked as virtual so that lazy loading and efficient change tracking are supported. See Requirements for Creating POCO Proxies.
The Entity Framework uses inheritance to support this functionality, which is why it requires certain properties to be marked virtual in your base class POCOs. It literally creates new types that derive from your POCO types. So your POCO is acting as a base type for the Entity Framework's dynamically created subclasses. That's what I meant by "create a proxy around".
The dynamically created subclasses that the Entity Framework creates become apparent when using the Entity Framework at runtime, not at static compilation time. And only if you enable the Entity Framework's lazy loading or change tracking features. If you opt to never use the lazy loading or change tracking features of the Entity Framework (which is not the default) then you needn't declare any of your navigation properties as virtual. You are then responsible for loading those navigation properties yourself, either using what the Entity Framework refers to as "eager loading", or manually retrieving related types across multiple database queries. You can and should use lazy loading and change tracking features for your navigation properties in many scenarios though.
If you were to create a standalone class and mark properties as virtual, and simply construct and use instances of those classes in your own application, completely outside of the scope of the Entity Framework, then your virtual properties wouldn't gain you anything on their own.
Edit to describe why properties would be marked as virtual
Properties such as:
public ICollection<RSVP> RSVPs { get; set; }
Are not fields and should not be thought of as such. These are called getters and setters and at compilation time, they are converted into methods.
//Internally the code looks more like this:
public ICollection<RSVP> get_RSVPs()
{
return _RSVPs;
}
public void set_RSVPs(RSVP value)
{
_RSVPs = value;
}
private RSVP _RSVPs;
That's why they're marked as virtual for use in the Entity Framework, it allows the dynamically created classes to override the internally generated get
and set
functions. If your navigation property getter/setters are working for you in your Entity Framework usage, try revising them to just properties, recompile, and see if the Entity Framework is able to still function properly:
public virtual ICollection<RSVP> RSVPs;
For future reference to people who find this page later you can use:
<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>
In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.
When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.
When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).
A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.
One possible C loop would be:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
/*
** Do something with c, such as check against '\n'
** and increment a line counter.
*/
}
}
For now, I would ignore feof
and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.
Pitfall to avoid: using char
for the type of c. getchar
returns the next character cast to an unsigned char
and then to an int
. This means that on most [sane] platforms the value of EOF
and valid "char
" values in c
don't overlap so you won't ever accidentally detect EOF
for a 'normal' char
.
Below I will insert a checkbox dynamically. Style is included to align the checkbox and most important to make sure word wrap is straight. the most important thing here is display: table-cell; for the alignment
The visual basic code.
'the code to dynamically insert a checkbox
Dim tbl As Table = New Table()
Dim tc1 As TableCell = New TableCell()
tc1.CssClass = "tdCheckTablecell"
'get the data for this checkbox
Dim ds As DataSet
Dim Company As ina.VullenCheckbox
Company = New ina.VullenCheckbox
Company.IDVeldenperScherm = HETid
Company.IDLoginBedrijf = HttpContext.Current.Session("welkbedrijf")
ds = Company.GetsDataVullenCheckbox("K_GetS_VullenCheckboxMasterDDLOmschrijvingVC") 'ds6
'create the checkbox
Dim radio As CheckBoxList = New CheckBoxList
radio.DataSource = ds
radio.ID = HETid
radio.CssClass = "tdCheck"
radio.DataTextField = "OmschrijvingVC"
radio.DataValueField = "IDVullenCheckbox"
radio.Attributes.Add("onclick", "documentChanged();")
radio.DataBind()
'connect the checkbox
tc1.Controls.Add(radio)
tr.Cells.Add(tc1)
tbl.Rows.Add(tr)
'the style for the checkbox
input[type="checkbox"] {float: left; width: 5%; height:20px; border: 1px solid black; }
.tdCheck label { width: 90%;display: table-cell; align:right;}
.tdCheck {width:100%;}
and the HTML output
<head id="HEAD1">
<title>
name
</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR" /><meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE" />
</head>
<style type='text/css'>
input[type="checkbox"] {float: left; width: 20px; height:20px; }
.tdCheck label { width: 90%;display: table-cell; align:right;}
.tdCheck {width:100%;}
.tdLabel {width:100px;}
.tdCheckTableCell {width:400px;}
TABLE
{
vertical-align:top;
border:1;border-style:solid;margin:0;padding:0;border-spacing:0;
border-color:red;
}
TD
{
vertical-align:top; /*labels ed en de items in het datagrid*/
border: 1; border-style:solid;
border-color:green;
font-size:30px }
</style>
<body id="bodyInternet" >
<form name="Form2" method="post" action="main.aspx?B" id="Form2">
<table border="0">
<tr>
<td class="tdLabel">
<span id="ctl16_ID{A}" class="DynamicLabel">
TITLE
</span>
</td>
<td class="tdCheckTablecell">
<table id="ctl16_{A}" class="tdCheck" onclick="documentChanged();" border="0">
<tr>
<td>
<input id="ctl16_{A}_0" type="checkbox" name="ctl16${A}$0" />
<label for="ctl16_{A}_0">
this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp this is just dummy text to show the text will warp
</label>
</td>
</tr>
<tr>
<td>
<input id="ctl16_{A}_1" type="checkbox" name="ctl16${A}$1" />
<label for="ctl16_{A}_1">
ITEM2
</label>
</td>
</tr>
<tr>
<td>
<input id="ctl16_{A}_2" type="checkbox" name="ctl16${A}$2" />
<label for="ctl16_{A}_2">
ITEM3
</label>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.
private string RemoveJunkChars(string input)
{
return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}
public class ThreadClass {
volatile int i = 1;
volatile boolean state=true;
synchronized public void printOddNumbers(){
try {
while (!state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = false;
i++;
notifyAll();
}
synchronized public void printEvenNumbers(){
try {
while (state) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" "+i);
state = true;
i++;
notifyAll();
}
}
Then call the above class like this
// I am ttying to print 10 values.
ThreadClass threadClass=new ThreadClass();
Thread t1=new Thread(){
int k=0;
@Override
public void run() {
while (k<5) {
threadClass.printOddNumbers();
k++;
}
}
};
t1.setName("Thread1");
Thread t2=new Thread(){
int j=0;
@Override
public void run() {
while (j<5) {
threadClass.printEvenNumbers();
j++;
}
}
};
t2.setName("Thread2");
t1.start();
t2.start();
out put:
System.out: Thread1 1
System.out: Thread2 2
System.out: Thread1 3
System.out: Thread2 4
System.out: Thread1 5
System.out: Thread2 6
System.out: Thread1 7
System.out: Thread2 8
System.out: Thread1 9
System.out: Thread2 10
I had the same problem. I wanted to 'bury' a folder at the bottom of the sort instead of bringing it to the top with the '!' character. Windows recognizes most special characters as just that, 'special', and therefore they ALL are sorted at the top.
However, if you think outside of the English characters, you will find a lot of luck. I used Character Map and the arial font, scrolled down past '~' and the others to the greek alphabet. Capitol Xi, ?, worked best for me, but I didn't check to see which was the actual 'lowest' in the sort.
Create a new style
<style name="my_dialog_theme" parent="ThemeOverlay.AppCompat.Dialog">
<item name="colorAccent">@color/colorAccent</item> <!--header background-->
<item name="android:windowBackground">@color/colorPrimary</item> <!--calendar background-->
<item name="android:colorControlActivated">@color/colorAccent</item> <!--selected day-->
<item name="android:textColorPrimary">@color/colorPrimaryText</item> <!--days of the month-->
<item name="android:textColorSecondary">@color/colorAccent</item> <!--days of the week-->
</style>
Then initialize the dialog
Calendar mCalendar = new GregorianCalendar();
mCalendar.setTime(new Date());
new DatePickerDialog(mContext, R.style.my_dialog_theme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//do something with the date
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();
Result:
Another simple PHP example of using cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Example found here: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
Instead of using curl_setopt
you can use curl_setopt_array
.
For me the issue was about a comma not in the filename but as below: -
Response.ok(streamingOutput,MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment, filename=your_file_name").build();
I accidentally put a comma after attachment. Got it resolved by replacing comma with a semicolon.
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
Reason for the error:
Column
expands to the maximum size in main axis direction (vertical axis), and so does the ListView
.
Solutions
So, you need to constrain the height of the ListView
. There are many ways of doing it, you can choose that best suits your need.
If you want to allow ListView
to take up all remaining space inside Column
use Expanded
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
If you want to limit your ListView
to certain height
, you can use SizedBox
.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
If your ListView
is small, you may try shrinkWrap
property on it.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
Adding .gem
to vendor/cache
seems to work. No options required in Gemfile
.
I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.
In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.
So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.
Edit: I only just noticted the previous reply, after posting. 100% agree.
using System.IO;
using System.Text;
using System.Security.Cryptography;
public static class EncryptionHelper
{
public static string Encrypt(string clearText)
{
string EncryptionKey = "abc123";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(string cipherText)
{
string EncryptionKey = "abc123";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
}
I'm hesitant to offer this as it misuses ye olde html. It's not a GOOD solution but it is a solution: use a table.
CSS:
table.navigation {
width: 990px;
}
table.navigation td {
text-align: center;
}
HTML:
<table cellpadding="0" cellspacing="0" border="0" class="navigation">
<tr>
<td>HOME</td>
<td>ABOUT</td>
<td>BASIC SERVICES</td>
<td>SPECIALTY SERVICES</td>
<td>OUR STAFF</td>
<td>CONTACT US</td>
</tr>
</table>
This is not what tables were created to do but until we can reliably perform the same action in a better way I guess it is just about permissable.
Check if you have the correct file mentioned in form statement in HTML:
For eg:
form action="insert.php" method="POST">
</form>
when you are in trial.php but instead you give another fileName
Check constraints are supported as of version 8.0.15 (yet to be released)
https://bugs.mysql.com/bug.php?id=3464
[23 Jan 16:24] Paul Dubois
Posted by developer: Fixed in 8.0.15.
Previously, MySQL permitted a limited form of CHECK constraint syntax, but parsed and ignored it. MySQL now implements the core features of table and column CHECK constraints, for all storage engines. Constraints are defined using CREATE TABLE and ALTER TABLE statements.
You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:
or on OS X:
For example, You have next things:
A link to open your app: http://example.com
The package name of your app: com.example.mypackage
Then you need to do next:
Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).
<activity
android:name=".MainActivity">
<intent-filter android:label="@string/filter_title_view_app_from_web">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://example.com" -->
<data
android:host="example.com"
android:scheme="http" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Create a HTML file to test the link or use this methods.
Open your Activity directly (just open your Activity, without a choosing dialog).
Open this link with browser or your programm (by choosing dialog).
Use Mobile Chrome to test
That's it.
And its not necessary to publish app in market to test deep linking =)
Also, for more information, check documentation and useful presentation.
SELECT DATEADD(m,DATEDIFF(m,0,GETDATE())-1,0) AS PreviousMonthStart
SELECT DATEADD(ms,-2,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) AS PreviousMonthEnd
If you do df.count > 0
. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.
The best way to do this is to perform df.take(1)
and check if its null. This will return java.util.NoSuchElementException
so better to put a try around df.take(1)
.
The dataframe return an error when take(1)
is done instead of an empty row. I have highlighted the specific code lines where it throws the error.
The aim of using StringBuilder, i.e reducing memory. Is it achieved?
No, not at all. That code is not using StringBuilder
correctly. (I think you've misquoted it, though; surely there aren't quotes around id2
and table
?)
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder
in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder
(there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2
and table
):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size
in the StringBuilder
constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder
having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append
] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder
under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder
for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder
:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilder
s are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
In Swift -
var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)
For me it was simply a matter of restarting the docker daemon..
I faced the same problem. There are two types of permissions in Android:
Here is the strategy to get dangerous permissions in Android 6.0
onRequestPermissionsResult
Here is my case: I need to write to external storage.
First, I check if I have the permission:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check the user's approval:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
Assuming the data file is actually Tab separated, not space aligned:
<test.tsv awk '{print $4}' | sort | uniq
Where $4 will be:
The easiest solution is to check the baseURI property, which is set only when the element is inserted in the DOM, and it reverts to an empty string when it is removed.
var div = document.querySelector('div');_x000D_
_x000D_
// "div" is in the DOM, so should print a string_x000D_
console.log(div.baseURI);_x000D_
_x000D_
// Remove "div" from the DOM_x000D_
document.body.removeChild(div);_x000D_
_x000D_
// Should print an empty string_x000D_
console.log(div.baseURI);
_x000D_
<div></div>
_x000D_
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
Perhaps an overkill if you need it just once, but you can use YaLinqo library* to filter collections (and perform any other transformations). This library allows peforming SQL-like queries on objects with fluent syntax. Its where
function accepts a calback with two arguments: a value and a key. For example:
$filtered = from($array)
->where(function ($v, $k) use ($allowed) {
return in_array($k, $allowed);
})
->toArray();
(The where
function returns an iterator, so if you only need to iterate with foreach
over the resulting sequence once, ->toArray()
can be removed.)
* developed by me
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
scipy.stats.rv_discrete
might be what you want. You can supply your probabilities via the values
parameter. You can then use the rvs()
method of the distribution object to generate random numbers.
As pointed out by Eugene Pakhomov in the comments, you can also pass a p
keyword parameter to numpy.random.choice()
, e.g.
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
If you are using Python 3.6 or above, you can use random.choices()
from the standard library – see the answer by Mark Dickinson.
Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.
Try this code:
SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$'
This makes sure that all characters match.
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
function drawDataURIOnCanvas(strDataURI, canvas) {
"use strict";
var img = new window.Image();
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
img.setAttribute("src", strDataURI);
}
You want a parameter source:
Set<Integer> ids = ...;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
parameters, getRowMapper());
This only works if getJdbcTemplate()
returns an instance of type NamedParameterJdbcTemplate
This code is supported in MVC4 onwards
@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })
Hey define color #000
into as like you and modify your css as like this
.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }
or this
li a { text-decoration: none; color:#000; }
li a:visited { text-decoration: none; color:#000; }
li a:hover { text-decoration: none; color:#000; }
li a:focus { text-decoration: none; color:#000; }
li a:hover, .navBtn:active { text-decoration: none; color:#000; }
I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.
if ($ucounter % 1000 == 0) { echo '+'; }
An updated answer for C++11:
Use the sleep_for
and sleep_until
functions:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
sleep_for(nanoseconds(10));
sleep_until(system_clock::now() + seconds(1));
}
With these functions there's no longer a need to continually add new functions for better resolution: sleep
, usleep
, nanosleep
, etc. sleep_for
and sleep_until
are template functions that can accept values of any resolution via chrono
types; hours, seconds, femtoseconds, etc.
In C++14 you can further simplify the code with the literal suffixes for nanoseconds
and seconds
:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
using std::chrono::system_clock;
sleep_for(10ns);
sleep_until(system_clock::now() + 1s);
}
Note that the actual duration of a sleep depends on the implementation: You can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that's the shortest it can do.
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.
C:\Users>python --version
Python 2.7.11
C:\Users>conda create --name p3 python=3
C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3 C:\Anaconda3\envs\p3
root * C:\Anaconda3
C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...
[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.
For more info: http://conda.pydata.org/docs/test-drive.html
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
Or to use this in Java 8:
try {
Files.newDirectoryStream( directory ).forEach( file -> {
try { Files.delete( file ); }
catch ( IOException e ) { throw new UncheckedIOException(e); }
} );
}
catch ( IOException e ) {
e.printStackTrace();
}
It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear
getYear
is no longer used and has been replaced by thegetFullYear
method.The
getYear
method returns the year minus 1900; thus:
- For years greater than or equal to 2000, the value returned by
getYear
is 100 or greater. For example, if the year is 2026,getYear
returns 126.- For years between and including 1900 and 1999, the value returned by
getYear
is between 0 and 99. For example, if the year is 1976,getYear
returns 76.- For years less than 1900, the value returned by
getYear
is less than 0. For example, if the year is 1800,getYear
returns -100.- To take into account years before and after 2000, you should use
getFullYear
instead ofgetYear
so that the year is specified in full.
I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.
try this
var x= [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
function joinObj(a, attr) {
var out = [];
for (var i=0; i<a.length; i++) {
out.push(a[i][attr]);
}
return out.join(", ");
}
var z = joinObj(x,'name');
z > "Joe, Kevin, Peter"
var y = joinObj(x,'age');
y > "22, 24, 21"
If you want to send as Cc using MimeMessageHelper
List<String> emails= new ArrayList();
email.add("email1");
email.add("email2");
for (String string : emails) {
message.addCc(string);
}
Same you can use to add multiple recipient.
absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id
) to prevent multiple rows in the child table (address
) from relating to the same row in the referenced table (student
).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html
What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).
Till ES5, to swap two numbers, you have to create a temp variable and then swap it. But in ES6, its very easy to swap two numbers using array destructuring. See example.
let x,y;
[x,y]=[2,3];
console.log(x,y); // return 2,3
[x,y]=[y,x];
console.log(x,y); // return 3,2
This may be cleaner (you dont need all the into
statements):
var query =
from order in dc.Orders
from vendor
in dc.Vendors
.Where(v => v.Id == order.VendorId)
.DefaultIfEmpty()
from status
in dc.Status
.Where(s => s.Id == order.StatusId)
.DefaultIfEmpty()
select new { Order = order, Vendor = vendor, Status = status }
//Vendor and Status properties will be null if the left join is null
Here is another left join example
var results =
from expense in expenseDataContext.ExpenseDtos
where expense.Id == expenseId //some expense id that was passed in
from category
// left join on categories table if exists
in expenseDataContext.CategoryDtos
.Where(c => c.Id == expense.CategoryId)
.DefaultIfEmpty()
// left join on expense type table if exists
from expenseType
in expenseDataContext.ExpenseTypeDtos
.Where(e => e.Id == expense.ExpenseTypeId)
.DefaultIfEmpty()
// left join on currency table if exists
from currency
in expenseDataContext.CurrencyDtos
.Where(c => c.CurrencyID == expense.FKCurrencyID)
.DefaultIfEmpty()
select new
{
Expense = expense,
// category will be null if join doesn't exist
Category = category,
// expensetype will be null if join doesn't exist
ExpenseType = expenseType,
// currency will be null if join doesn't exist
Currency = currency
}
If you're using Python 3, raw_input
has changed to input
Python 3 example:
line = input('Enter a sentence:')
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
the same rules should apply to Java.
in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9
I've found this to be the most useful for matching a URL..
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
On Mac/unix and Windows:
ssh-keygen
then follow the prompts. It will ask you for a name to the file (say you call it pubkey, for example).
Right away, you should have your key fingerprint and your key's randomart image visible to you.
Then just use your favourite text editor and enter command vim pubkey.pub
and it (your ssh-rsa key) should be there.
Replace vim with emacs or whatever other editor you have/prefer.
Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.
In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()
from datetime import datetime
date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'
it works well on Edge and Chrome:
width: fit-content;
height: fit-content;
The
linecache
module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by thetraceback
module to retrieve source lines for inclusion in the formatted traceback...
Edit: CMake now has builtin support for this. See new answer.
You can also force the build of the dependent target in a secondary make process
See my answer on a related topic.
Works for me. If you trying EditText with Label and trying change to underline color use this. Change to TextInputEditText instead EditText.
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/editTextTextPersonName3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/_16sdp"
android:layout_marginLeft="@dimen/_16sdp"
android:layout_marginTop="@dimen/_16sdp"
android:layout_marginEnd="@dimen/_8sdp"
android:layout_marginRight="@dimen/_8sdp"
android:textColorHint="@color/white"
app:layout_constraintEnd_toStartOf="@+id/guideline3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:backgroundTint="@color/white"
android:hint="Lastname"
android:textSize="@dimen/_14sdp"
android:inputType="textPersonName"
android:textColor="@color/white"
android:textColorHint="@color/white" />
</com.google.android.material.textfield.TextInputLayout>
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]>
which means a list of Object tables and not a list of Employee.
Object[0] refers an Employee entity
Object[1] refers a Departement entity
When you use fetch, there is just one select and the result is the list of Employee List<Employee>
containing the list of departements. It overrides the lazy declaration of the entity.
Thanks Jacob for the answer. really helpfull if anyone interesting with monotouch c# version
private void SetScrollPositionDown() {
if (tblShoppingListItem.ContentSize.Height > tblShoppingListItem.Frame.Size.Height) {
PointF offset = new PointF(0, tblShoppingListItem.ContentSize.Height - tblShoppingListItem.Frame.Size.Height);
tblShoppingListItem.SetContentOffset(offset,true );
}
}
The equation below is a expression that tests if a point is within a given circle where xP & yP are the coordinates of the point, xC & yC are the coordinates of the center of the circle and R is the radius of that given circle.
If the above expression is true then the point is within the circle.
Below is a sample implementation in C#:
public static bool IsWithinCircle(PointF pC, Point pP, Single fRadius){
return Distance(pC, pP) <= fRadius;
}
public static Single Distance(PointF p1, PointF p2){
Single dX = p1.X - p2.X;
Single dY = p1.Y - p2.Y;
Single multi = dX * dX + dY * dY;
Single dist = (Single)Math.Round((Single)Math.Sqrt(multi), 3);
return (Single)dist;
}
The simplest way is an anonymous method passed into Label.Invoke
:
// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
// Running on the UI thread
form.Label.Text = newText;
});
// Back on the worker thread
Notice that Invoke
blocks execution until it completes--this is synchronous code. The question doesn't ask about asynchronous code, but there is lots of content on Stack Overflow about writing asynchronous code when you want to learn about it.
As of SQL Server 2012 you can use the eomonth
built-in function, which is intended for getting the end of the month but can also be used to get the start as so:
select dateadd(day, 1, eomonth(<date>, -1))
If you need the result as a datetime
etc., just cast
it:
select cast(dateadd(day, 1, eomonth(<date>, -1)) as datetime)
To add to what others posted:
ExecuteScalar conceptually returns the leftmost column from the first row of the resultset from the query; you could ExecuteScalar a SELECT * FROM staff, but you'd only get the first cell of the resulting rows Typically used for queries that return a single value. I'm not 100% sure about SQLServer but in Oracle, you wouldnt use it to run a FUNCTION (a database code that returns a single value) and expect it to give you the return value of the function even though functions return single values.. However, if youre running the function as part of a query, e.g. SELECT SUBSTR('abc', 1, 1) FROM DUAL then it would give the return value by virtue of the fact that the return value is stored in the top leftmost cell of the resulting rowset
ExecuteNonQuery would be used to run database stored procedures, functions and queries that modify data (INSERT/UPDATE/DELETE) or modify database structure (CREATE TABLE...). Typically the return value of the call is an indication of how many rows were affected by the operation but check the DB documentation to guarantee this
You can also create a Docker container with Alpine as the OS and the install Python and Pyspark as packages. That will have it all containerised.
I'm not familiar with DB2, but have you tried COALESCE?
ie:
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
Pure Python (2 & 3), a snippet without 3rd party dependencies.
This function writes compressed, true-color (4 bytes per pixel) RGBA
PNG's.
def write_png(buf, width, height):
""" buf: must be bytes or a bytearray in Python3.x,
a regular string in Python2.x.
"""
import zlib, struct
# reverse the vertical line order and add null bytes at the start
width_byte_4 = width * 4
raw_data = b''.join(
b'\x00' + buf[span:span + width_byte_4]
for span in range((height - 1) * width_byte_4, -1, - width_byte_4)
)
def png_pack(png_tag, data):
chunk_head = png_tag + data
return (struct.pack("!I", len(data)) +
chunk_head +
struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head)))
return b''.join([
b'\x89PNG\r\n\x1a\n',
png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
png_pack(b'IDAT', zlib.compress(raw_data, 9)),
png_pack(b'IEND', b'')])
... The data should be written directly to a file opened as binary, as in:
data = write_png(buf, 64, 64)
with open("my_image.png", 'wb') as fh:
fh.write(data)
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
I took a slightly different approach than others
static float NextFloat(Random random)
{
double val = random.NextDouble(); // range 0.0 to 1.0
val -= 0.5; // expected range now -0.5 to +0.5
val *= 2; // expected range now -1.0 to +1.0
return float.MaxValue * (float)val;
}
The comments explain what I'm doing. Get the next double, convert that number to a value between -1 and 1 and then multiply that with float.MaxValue
.
Formatting are CASE-SENSITIVE so USE MM for month not mm (this is for minute) and yyyy For Reference you can use following cheatsheet.
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
Examples:
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
This is what caused the problem in my case (CMakeLists.txt
):
set (CMAKE_CXX_FLAGS "...some flags...")
It makes invisible all earlier defined include directories. After removing / refactoring this line everything works fine.
I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:
Function FirstBlankRow(ByVal rngToSearch As Range) As Long
Dim R As Range
Dim C As Range
Dim RowIsBlank As Boolean
For Each R In rngToSearch.Rows
RowIsBlank = True
For Each C In R.Cells
If IsEmpty(C.Value) = False Then RowIsBlank = False
Next C
If RowIsBlank Then
FirstBlankRow = R.Row
Exit For
End If
Next R
End Function
I am a beginner tinkering on somebody else's code so please be lenient and further correct my errors. I tried your code and played with the VBA help The following worked with me:
Function currAddressTest(dataRangeTest As Range) As String
currAddressTest = ActiveSheet.Name & "$" & dataRangeTest.Address(False, False)
End Function
When I select data source argument for my function, it is turned into Sheet1$A1:G3 format. If excel changes it to Table1[#All] reference in my formula, the function still works properly
I then used it in your function (tried to play and add another argument to be injected to WHERE...
Function SQL(dataRange As Range, CritA As String)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim currAddress As String
currAddress = ActiveSheet.Name & "$" & dataRange.Address(False, False)
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM [" & currAddress & "]" & _
"WHERE [A] = '" & CritA & "' " & _
"ORDER BY 1 ASC"
rs.Open strSQL, cn
SQL = rs.GetString
End Function
Hope your function develops further, I find it very useful. Have a nice day!
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
One huge difference (for me) is that Visual Studio Code is one monitor only. With Visual Studio you can use multi-screen setups.
Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.
Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.
One thing to consider might be a "ForTest" suffix:
internal void DoThisForTest(string name)
{
DoThis(name);
}
private void DoThis(string name)
{
// Real implementation
}
Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.
It's worth mentioning that in some cases
File myFolder = new File("directory");
doesn't point to the root elements. For example when you place your application on C:
drive (C:\myApp.jar
) then myFolder
points to (windows)
C:\Users\USERNAME\directory
instead of
C:\Directory
In the special case: "All elements of List1 goes to a new List2": (e.g. a string list)
List<string> list2 = new List<string>(list1);
In this case, list2 is generated with all elements from list1.
Both are fine, but only the first one will allow you to inspect the Exception itself.
Both swallow the Exception, and you should only catch exceptions to do something meaningfull. Hiding a problem is not meaningful!
Lets say the two rectangles are rectangle A and rectangle B. Let their centers be A1 and B1 (coordinates of A1 and B1 can be easily found out), let the heights be Ha and Hb, width be Wa and Wb, let dx be the width(x) distance between A1 and B1 and dy be the height(y) distance between A1 and B1.
Now we can say we can say A and B overlap: when
if(!(dx > Wa+Wb)||!(dy > Ha+Hb)) returns true
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:
if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }
if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
&& $string !~ /Bush/i) {
print "$string\n"
}
The script file
bash-3.2$ cat test.sh
#!/bin/bash
echo "The argument is arg: $1"
for ((n=0;n<$1;n++));
do
echo "Hi"
done
and the output below
bash-3.2$ ./test.sh 3
The argument is arg: 3
Hi
Hi
Hi
bash-3.2$
For your example you can try
DateTime StartDate = new DateTime(2009, 3, 10);
DateTime EndDate = new DateTime(2009, 3, 26);
int DayInterval = 3;
List<DateTime> dateList = new List<DateTime>();
while (StartDate.AddDays(DayInterval) <= EndDate)
{
StartDate = StartDate.AddDays(DayInterval);
dateList.Add(StartDate);
}
In my case, the tomcat directory was owned by root, and I was not running eclipse as root.
So I had to
sudo chown -R $USER apache-tomcat-VERSION/
I got this error when the chrome driver was not closed properly. Eg, if I try to find something and click it and it doesn't exist, the driver throws an exception and the thread ended there ( I did not close the driver ).
So, when I ran the same method again later where I had to reinitialize the driver, the driver didn't initialize and it threw the exception.
My solve was simply to wrap the selenium tasks in a try catch and close the driver properly
Just for the record, if you are using eslint-plugin-vue, the correct place to add 'parser': 'babel-eslint'
is inside parserOptions
param.
'parserOptions': {
'parser': 'babel-eslint',
'ecmaVersion': 2018,
'sourceType': 'module'
}
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
html
"input type ="text" id="txtnothing" runat ="server" "
javacript
var txt = document.getElementById("txtnothing");
txt.value = Date.now();
code
If Not (Session("txtnothing") Is Nothing OrElse String.IsNullOrEmpty(Session("txtnothing"))) Then
If Session("txtnothing") = txtnothing.Value Then
lblMsg.Text = "Please try again not a valid request"
Exit Sub
End If
End If
Session("txtnothing") = txtnothing.Value