I've found Waldo!
How I've done it
First, I'm filtering out all colours that aren't red
waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];
Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.
corr = ImageCorrelate[red,
Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]],
NormalizedSquaredEuclideanDistance];
I use Binarize
to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation
pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];
I had to play around a little with the level. If the level is too high, too many false positives are picked out.
Finally I'm combining this result with the original image to get the result above
found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]
Solved 403: Forbidden when visiting localhost. Using ports 80,443,3308 (the later to handle conflict with MySQL Server installation) Windows 10, XAMPP 7.4.1, Apache 2.4.x My web files are in a separate folder.
httpd.conf - look for these lines and set it up where you have your files, mine is web folder.
DocumentRoot "C:/web"
<Directory "C:/web">
Changed these 2 lines.
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "C:/web/project1"
ServerName project1.localhost
<Directory "C:/web/project1">
Order allow,deny
allow from all
</Directory>
</VirtualHost>
to this
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "C:/web/project1"
ServerName project1.localhost
<Directory "C:/web/project1">
Require all granted
</Directory>
</VirtualHost>
Add your details in your hosts file C:\Windows\System32\drivers\etc\hosts file
127.0.0.1 localhost
127.0.0.1 project1.localhost
Stop start XAMPP, and click Apache admin (or localhost) and the wonderful XAMPP dashboard now displays! And visit your project at project1.localhost
the discussion and answer here was massively helpful to me:
If you have special logic required for the first route only you can do the following:
loaded = false;
constructor(private router: Router....) {
router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
.subscribe((e) => {
this.loaded = true;
alert('loaded - this fires only once');
});
I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.
Unfortunately, the meaning of things like ( and \( are swapped between Emacs style regular expressions and most other styles. So if you try to escape these you may be doing the opposite of what you want.
So you really have to know what style you are trying to quote.
Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:
var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
if (functionLock) {
functionCallbacks.push(callback);
} else {
$.longRunning(function(response) {
while(functionCallbacks.length){
var thisCallback = functionCallbacks.pop();
thisCallback(response);
}
});
}
}
You can also implement this using DOM event listeners or a pubsub solution.
You can use all
> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE
On a similar note, if you want to check whether any of the elements is TRUE you can use any
> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE
When i tried the solution with /XD i found, that the path to exclude should be the source path - not the destination.
e.g. this Works
robocopy c:\test\a c:\test\b /MIR /XD c:\test\a\leavethisdiralone\
Just pass a callback as argument like this:
function getMeta(url, callback) {_x000D_
var img = new Image();_x000D_
img.src = url;_x000D_
img.onload = function() { callback(this.width, this.height); }_x000D_
}_x000D_
getMeta(_x000D_
"http://snook.ca/files/mootools_83_snookca.png",_x000D_
function(width, height) { alert(width + 'px ' + height + 'px') }_x000D_
);
_x000D_
I was debugging a menu hover
state with Chrome and did this to be able to see the hover state code:
In the Elements
panel click over Toggle Element state
button and select :hover
.
In the Scripts
panel go to Event Listeners Breakpoints
in the right bottom section and select Mouse -> mouseup
.
Now inspect the Menu and select the box you want. When you release the mouse button it should stop and show you the selected element hover state in the Elements
panel (look at the Styles
section).
With C# 6.0, you can create a dictionary in following way:
var dict = new Dictionary<string, int>
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
It even works with custom types.
After commenting @Marcin answer, I have more carefully checked one of my students code where I found the same weird behavior, even after only 2 epochs ! (So @Marcin's explanation was not very likely in my case).
And I found that the answer is actually very simple: the accuracy computed with the Keras method evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels. You can check that by recomputing the accuracy yourself (first call the Keras method "predict" and then compute the number of correct answers returned by predict): you get the true accuracy, which is much lower than the Keras "evaluate" one.
I encountered this issue when using a different AWS profile. I saw the error when I was using an account with admin permissions, so the possibility of permissions issues seemed unlikely.
It's really a pet peeve of mine that AWS is so prone to issuing error messages that have such little correlation with the required actions, from a user perspective.
If you just want a button to open up a new window, then something like this works:
btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Parent root;
try {
root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
Stage stage = new Stage();
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.show();
// Hide this current window (if this is what you want)
((Node)(event.getSource())).getScene().getWindow().hide();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Don't know much VB.NET syntax but here's and idea
Dim source As New Bitmap("C:\image.png")
Dim target As New Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)
Using graphics As Graphics = Graphics.FromImage(target)
graphics.DrawImage(source, new Size(48, 48))
End Using
I have struggled a long time to modify the extension attributes in our domain. Then I wrote a powershell script and created an editor with a GUI to set and remove extAttributes from an account.
If you like, you can take a look at it at http://toolbocks.de/viewtopic.php?f=3&t=4
I'm sorry, that the description in the text is in German. The GUI itself is in English.
I use this script on a regular basis in our domain and it never deleted anything or did any other harm. I provide no guarantee, that this script works as expected in your domain. But as I provide the source, you can (and should) have a look at it, before you run it.
Where supported, you can use the ::input-placeholder
pseudoselector combined with ::before
.
See an example at:
http://codepen.io/JonFabritius/pen/nHeJg
I was just working on this and came across this article, from which I modified this stuff:
Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
Fowloing code remove newline from both side of string:
select ltrim(rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13)),''||CHR(10)||CHR(13)) from dual
but in most cases this one is just enought :
select rtrim('asbda'||CHR(10)||CHR(13) ,''||CHR(10)||CHR(13))) from dual
//R stands for ROW and C stands for COLUMN:
//i stands for ROW and j stands for COLUMN:
#include<stdio.h>
int main(){
int M[100][100];
int R,C,i,j;
printf("Please enter how many rows you want:\n");
scanf("%d",& R);
printf("Please enter how column you want:\n");
scanf("%d",& C);
printf("Please enter your matrix:\n");
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
scanf("%d", &M[i][j]);
}
printf("\n");
}
for(i = 0; i < R; i++){
for(j = 0; j < C; j++){
printf("%d\t", M[i][j]);
}
printf("\n");
}
getch();
return 0;
}
Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:
var re = new RegExp(yyy, 'g');
xxx.match(re);
Any flags you need (such as /g) can go into the second parameter.
This a single solution, in where your_field is a field that will set and new_value is a new value field, that can a function or a single value
foreach ($array as $key => $item) {
$item["your_field"] = "new_value";
$array[$key] = $item;
}
In your case new_value will be a date() function
I believe your problem is this: in your while loop, n is divided by 2, but never cast as an integer again, so it becomes a float at some point. It is then added onto y, which is then a float too, and that gives you the warning.
make it simple :D
function dataURItoBlob(dataURI,mime) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = window.atob(dataURI);
// separate out the mime component
// write the bytes of the string to an ArrayBuffer
//var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ia], { type: mime });
return blob;
}
The solution below has a "SEO friendlier" version:
function hyphenize($string) {
$dict = array(
"I'm" => "I am",
"thier" => "their",
// Add your own replacements here
);
return strtolower(
preg_replace(
array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
array( '-', '' ),
// the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
cleanString(
str_replace( // preg_replace can be used to support more complicated replacements
array_keys($dict),
array_values($dict),
urldecode($string)
)
)
)
);
}
function cleanString($text) {
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'/–/' => '-', // UTF-8 hyphen to "normal" hyphen
'/[’‘‹›‚]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => ' ', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.
After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru
"behaved better" than viaggi-economy-per
(the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).
There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.
In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict
needs to be hand tailored, of course.
A simple approach:
// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped
$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);
// Replace sequences of spaces with hyphen
$str = preg_replace('/ */', '-', $str);
// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)
// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);
// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything
Note that you might have to first urldecode()
the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.
So the finished function along with test cases:
function hyphenize($string) {
return
## strtolower(
preg_replace(
array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
array('-', ''),
## cleanString(
urldecode($string)
## )
)
## )
;
}
print implode("\n", array_map(
function($s) {
return $s . ' becomes ' . hyphenize($s);
},
array(
'Never%20gonna%20give%20you%20up',
"I'm not the man I was",
"'Légeresse', dit sa majesté",
)));
Never%20gonna%20give%20you%20up becomes never-gonna-give-you-up
I'm not the man I was becomes im-not-the-man-I-was
'Légeresse', dit sa majesté becomes legeresse-dit-sa-majeste
To handle UTF-8 I used a cleanString
implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.
The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.
I would use a decimal with the proper precision for your data.
This is my sort. It will do number sort , string sort and date sort .
import { Pipe , PipeTransform } from "@angular/core";
@Pipe({
name: 'sortPipe'
})
export class SortPipe implements PipeTransform {
transform(array: Array<string>, key: string): Array<string> {
console.log("Entered in pipe******* "+ key);
if(key === undefined || key == '' ){
return array;
}
var arr = key.split("-");
var keyString = arr[0]; // string or column name to sort(name or age or date)
var sortOrder = arr[1]; // asc or desc order
var byVal = 1;
array.sort((a: any, b: any) => {
if(keyString === 'date' ){
let left = Number(new Date(a[keyString]));
let right = Number(new Date(b[keyString]));
return (sortOrder === "asc") ? right - left : left - right;
}
else if(keyString === 'name'){
if(a[keyString] < b[keyString]) {
return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
} else if (a[keyString] > b[keyString]) {
return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
} else {
return 0;
}
}
else if(keyString === 'age'){
return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
}
});
return array;
}
}
I followed many links including the official documentation, however it all ended up in this error:
Requires: container-selinux >= 2.9
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest
The only way it worked for me is as follows (yum upgrade
worked I guess):
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
yum upgrade docker-ce
If you are using @Configuation then instantiate below static bean. If not static @Configutation is instantiated very early and and the BeanPostProcessors responsible for resolving annotations like @Value, @Autowired etc, cannot act on it. Refer here
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
For Typescript users willing to set and get typed properties:
/**
* Silly wrapper to be able to type the storage keys
*/
export class TypedStorage<T> {
public removeItem(key: keyof T): void {
localStorage.removeItem(key);
}
public getItem<K extends keyof T>(key: K): T[K] | null {
const data: string | null = localStorage.getItem(key);
return JSON.parse(data);
}
public setItem<K extends keyof T>(key: K, value: T[K]): void {
const data: string = JSON.stringify(value);
localStorage.setItem(key, data);
}
}
// write an interface for the storage
interface MyStore {
age: number,
name: string,
address: {city:string}
}
const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();
storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok
const address: {city:string} = storage.getItem("address");
Pragma
is the HTTP/1.0 implementation and cache-control
is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.
It may just be me but it seemed like most of these answers were not complete or would not work correctly. I made something very quick and dirty. That being said not sure how good of an idea it is to do it this way, but it works perfectly every time.
while (true)
{
if(DateTime.Now.ToString("HH:mm") == "22:00")
{
//do something here
//ExecuteFunctionTask();
//Make sure it doesn't execute twice by pausing 61 seconds. So that the time is past 2200 to 2201
Thread.Sleep(61000);
}
Thread.Sleep(10000);
}
it will print log messages in your developer console (firebug/webkit dev tools/ie dev tools)
If Perl 5.10+ is not an option, here is a quick and dirty approximation. It's not exactly the same, since say has some magic when its first arg is a handle, but for printing to STDOUT:
sub say {print @_, "\n"}
say 'hello';
Don't forget to enable tcp/ip connections in SQL SERVER Configuration tools
This has been asked before on Stack. See the following links:
Basically you just need to set up the thread with a stop function that sets a sentinel value that the thread will check. In your case, you'll have the something in your loop check the sentinel value to see if it's changed and if it has, the loop can break and the thread can die.
Indeed, you can leave it empty (W3 validator doesn't complain).
Taking the idea one step further: leave out the ="". The advantage of this is that the link isn't treated as an anchor to the current page.
<a href>sth</a>
(A==B).all()
test if all values of array (A==B) are True.
Note: maybe you also want to test A and B shape, such as A.shape == B.shape
Special cases and alternatives (from dbaupp's answer and yoavram's comment)
It should be noted that:
A
or B
is empty and the other one contains a single element, then it return True
. For some reason, the comparison A==B
returns an empty array, for which the all
operator returns True
.A
and B
don't have the same shape and aren't broadcastable, then this approach will raise an error.In conclusion, if you have a doubt about A
and B
shape or simply want to be safe: use one of the specialized functions:
np.array_equal(A,B) # test if same shape, same elements values
np.array_equiv(A,B) # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
You can automatically do it in Notepad++ (add text at the beginning and/or end of each line) by using one regular expression in Replace (Ctrl+H):
Explanation: Expression $1
in Replace with input denotes all the characters that include the round brackets (.*)
in Find what regular expressin.
Tested, it works.
Hope that helps.
I ended up just making a short and sweet fsize
function(note, no error checking)
int fsize(FILE *fp){
int prev=ftell(fp);
fseek(fp, 0L, SEEK_END);
int sz=ftell(fp);
fseek(fp,prev,SEEK_SET); //go back to where we were
return sz;
}
It's kind of silly that the standard C library doesn't have such a function, but I can see why it'd be difficult as not every "file" has a size(for instance /dev/null
)
Just define your action method like this
public string ThemePath()
and simply return the string itself.
I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.
You can try my lib for multiple bluetooth connection :
In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);
Slightly upgraded answer from @David George:
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
public static double distanceBetweenLocations(Location l1, Location l2) {
if(l1.hasAltitude() && l2.hasAltitude()) {
return distance(l1.getLatitude(), l2.getLatitude(), l1.getLongitude(), l2.getLongitude(), l1.getAltitude(), l2.getAltitude());
}
return l1.distanceTo(l2);
}
distance function is the same, but I've created I small wrapper function, which takes 2 Location objects. Thanks to this, I only use distance function if both of locations actually have altitude, because sometimes they don't. And it can lead to strange results (if location doesn't know its altitude 0 will be returned). In this case, I fall back to classic distanceTo function.
you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.
On Excel 2010 try this:
You can simply write
hex(x)[2:]
to get the first two characters removed.
There are sometimes when ./manage.py makemigrations
is superior to ./manage.py makemigrations <myapp>
because it can handle certain conflicts between apps.
Those occasions occur silently and it takes several hours of swearing
to understand the real meaning of the dreaded No changes detected
message.
Therefore, it is a far better choice to make use of the following command:
./manage.py makemigrations <myapp1> <myapp2> ... <myappN>
If using MySQL Workbench, simply look in the Session tab in the Information pane located in the sidebar.
Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.
Basic mapping: <property name="some_flag" type="yes_no"/>
Annotation mapping (Hibernate extensions):
@Type(type="yes_no")
public boolean getFlag();
I think this should be fine.
static boolean addWillOverFlow(int a, int b) {
return (Integer.signum(a) == Integer.signum(b)) &&
(Integer.signum(a) != Integer.signum(a+b));
}
It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.
On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.
Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.
Notes:
GMT confuses seconds, which is why UTC was invented.
Warning! different regional timezones might produce the same datetime value due to daylight savings time
Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.
When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.
no matter what timezone the current MySQL session is in:
SELECT
CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime`
FROM `table_name`
You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:
SELECT `timestamp_field` FROM `table_name`
SELECT UTC_TIMESTAMP();
SELECT UTC_TIMESTAMP;
SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');
Example result: 2015-03-24 17:02:41
SELECT NOW();
SELECT CURRENT_TIMESTAMP;
SELECT CURRENT_TIMESTAMP();
SELECT @@system_time_zone;
Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return 02:00:00 if your timezone is +2:00.
SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`
SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`
SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`
SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00')
FROM `table_name`
SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND)
Note: A timezone can be set in 2 formats:
Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.
default_time_zone='+00:00'
or
timezone='UTC'
To see what value they are set to
SELECT @@global.time_zone;
To set a value for it use either one:
SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';
SELECT @@session.time_zone;
To set it use either one:
SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";
both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".
For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html
Note: you can not do this as it will return NULL:
SELECT
CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime`
FROM `table_name`
For CONVERT_TZ
to work, you need the timezone tables to be populated
SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;
If they are empty, then fill them up by running this command
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation
the fix being to run this
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql
echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql
mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql
(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011
https://chrisjean.com/updating-daylight-saving-time-on-linux/)
SELECT
tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND) AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC
CONVERT_TZ
also applies any necessary DST changes based on the rules in the above tables and the date that you use.
Note:
According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.
Only the named timezones will change time during daylight savings time.
Abbreviations like CET
will always be a winter time and CEST
will be summer time while +01:00 will always be UTC
time + 1 hour and both won't change with DST.
The system
timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)
You can read more about working with DST here
related questions:
Sources:
This method can be more optimized than above
def rindex(iterable, value):
try:
return len(iterable) - next(i for i, val in enumerate(reversed(iterable)) if val == value) - 1
except StopIteration:
raise ValueError
Can be set via "Secure Text Entry" via Interface Builder
I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.
I was having the issue described in this question, having installed the pdfx package via pip.
When I ran it however, nothing...
pip list | grep pdfx
pdfx (1.3.0)
Yet:
which pdfx
pdfx not found
The problem on Linux is that pip install ...
drops scripts into ~/.local/bin
and this is not on the default Debian/Ubuntu $PATH
.
Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813
To fix, just add ~/.local/bin
to your $PATH
, for example by adding the following line to your .bashrc
file:
export PATH="$HOME/.local/bin:$PATH"
After that, restart your shell and things should work as expected.
I had the same issue in Travis and solved by adding:
addons:
chrome: stable
to my .travis.yml
file.
Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
CSS font-stretch is now supported in all major browsers (except iOS Safari and Opera Mini). It is not easy to find a common font-family that supports expanding fonts, but it is easy to find fonts that support condensing, for example:
font-stretch: condense;
font-family: sans-serif, "Helvetica Neue", "Lucida Grande", Arial;
I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:
rm -rf lib
svn up
This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.
I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.
I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.
On the server, to turn the raw posted data back into a C# class, here's what I would do.
First, define a C# class which will contain the posted data.
Supposing my webpage is posting JSON data like this:
{
"UserID" : 1,
"FirstName" : "Mike",
"LastName" : "Mike",
"Address1" : "10 Really Street",
"Address2" : "London"
}
Then I'd define a C# class like this...
public class JSONRequest
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<>
of Order records.)
Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);
And that's it. You now have a JSONRequest
class containing the various fields which were POSTed to your server.
What you're trying to insert is not a date, I think, but a string. You need to use to_date()
function, like this:
insert into table t1 (id, date_field) values (1, to_date('20.06.2013', 'dd.mm.yyyy'));
List<T>.ForEach
doesn't play particularly well with async
(neither does LINQ-to-objects, for the same reasons).
In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.
using (DataContext db = new DataLayer.DataContext())
{
var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
var results = await Task.WhenAll(tasks);
}
The benefits of this approach over giving an async
delegate to ForEach
are:
async void
cannot be caught with catch
; this approach will propagate exceptions at the await Task.WhenAll
line, allowing natural exception handling.await Task.WhenAll
. If you use async void
, you cannot easily tell when the operations have completed.GetAdminsFromGroupAsync
sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.i think that is the solution
ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();
String hql = "FROM table ";
org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();
cat.getLibCat();//table colonm getter
combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());
Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe
program, which won't open unnecessary windows.
Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2
Otherwise, just quote stuff as Andrew points out.
In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):
"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2
At the risk of being accused of shameless self promotion I would like to point out that in my quest for a free load testing tool I went to this article: http://www.devcurry.com/2010/07/10-free-tools-to-loadstress-test-your.html
Either I couldn't get the throughput I wanted, or I couldn't get the flexibility I wanted. AND I wanted to easily aggregate the results of multiple load test generation hosts in post test analysis.
I tried out every tool on the list and to my frustration found that none of them quite did what I wanted to be able to do. So I built one and am sharing it.
Here it is: http://sourceforge.net/projects/loadmonger
PS: No snide comments on the name from folks who are familiar with urban slang. I wasn't but am slightly more worldly now.
I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:
angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()
I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.
int *a[]
, when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:
int (*aptr)[N]
Where N
is a particular positive integer (not a variable).
If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):
template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
(*aptr)[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(&a);
}
You could also take a reference:
template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
for (size_t i=0; i<SZ; ++i)
arr[i] = rand() % 9;
}
int main()
{
int a[5];
generateArray(a);
}
The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
That is all the language has to say, as far as C++03 is concerned.
you can retrieve value like this
string str = (string)(range.Cells[row, col] as Excel.Range).Value2 ;
select entire used range
Excel.Range range = xlWorkSheet.UsedRange;
source :
http://csharp.net-informations.com/excel/csharp-read-excel.htm
flaming
My grep-a-like program ack
has a -1
option that stops at the first match found anywhere. It supports the -m 1
that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.
There is np.argwhere
,
import numpy as np
arr = np.array([[1,2,3], [0, 1, 0], [7, 0, 2]])
np.argwhere(arr == 0)
which returns all found indices as rows:
array([[1, 0], # Indices of the first zero
[1, 2], # Indices of the second zero
[2, 1]], # Indices of the third zero
dtype=int64)
Make your life easier by using CSS Selectors
I know I have come late to party but I have a nice suggestion for you.
Using BeautifulSoup
is already been suggested I would rather prefer using CSS Selectors
to scrape data inside HTML
import urllib2
from bs4 import BeautifulSoup
main_url = "http://www.example.com"
main_page_html = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)
# Scrape all TDs from TRs inside Table
for tr in main_page_soup.select("table.class_of_table"):
for td in tr.select("td#id"):
print(td.text)
# For acnhors inside TD
print(td.select("a")[0].text)
# Value of Href attribute
print(td.select("a")[0]["href"])
# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
return page
except Exception:
while 1:
print("Trying again the URL:")
print(passed_url)
try:
page = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
print("-------------------------------------")
print("---- URL was successfully scraped ---")
print("-------------------------------------")
return page
except Exception:
time.sleep(20)
continue
Using the simple app.run()
from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.
Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.
That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).
Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.
if you are using IIS, maybe you should try
"application pools" --> "DefaultAppPool" --> "application pools default value"
--> "32-Bit-application-activ" --> set false
Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.
type
cmd.exe /k cd c:/
in a text file and save as cmd.bat Clicking this file does the trick. You can pin it to the start menu as well.
To start in a partitioned drive (e.g. D), use
cmd.exe /k d:
service: It runs in the background on your system. For example,
background process: chef making soup
IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.
IN my case i had to send the data backwards from FragmentB->FragmentA hence Intents was not an option as the fragment would already be initialised All though all of the above answers sounds good it takes a lot of boiler plate code to implement, so i went with a much simpler approach of using LocalBroadcastManager, it exactly does the above said but without alll the nasty boilerplate code. An example is shared below.
In Sending Fragment(Fragment B)
public class FragmentB {
private void sendMessage() {
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", "your message");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And in the Message to be Received Fragment(FRAGMENT A)
public class FragmentA {
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register receiver
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter("custom-event-name"));
}
// This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
}
};
}
Hope it helps someone
A percentage in the value of the font-size
property is relative to the parent element’s font size. CSS 2.1 says this obscurely and confusingly (referring to “inherited font size”), but CSS3 Text says it very clearly.
The parent of the body
element is the root element, i.e. the html
element. Unless set in a style sheet, the font size of the root element is implementation-dependent. It typically depends on user settings.
Setting font-size: 100%
is pointless in many cases, as an element inherits its parent’s font size (leading to the same result), if no style sheet sets its own font size. However, it can be useful to override settings in other style sheets (including browser default style sheets).
For example, an input
element typically has a setting in browser style sheet, making its default font size smaller than that of copy text. If you wish to make the font size the same, you can set
input { font-size: 100% }
For the body
element, the logically redundant setting font-size: 100%
is used fairly often, as it is believed to help against some browser bugs (in browsers that probably have lost their significance now).
You're looking for the document.documentElement.scrollTop
property.
Simple way to detect scroll up/down on android listview
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
if(prevVisibleItem != firstVisibleItem){
if(prevVisibleItem < firstVisibleItem)
//ScrollDown
else
//ScrollUp
prevVisibleItem = firstVisibleItem;
}
dont forget
yourListView.setOnScrollListener(yourScrollListener);
Just use substring: "apple".substring(3);
will return le
Have you tried:
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("Data")
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)
Use my Plugin :
$.fn.removeCss=function(all){
if(all===true){
$(this).removeAttr('class');
}
return $(this).removeAttr('style')
}
For your case ,Use it as following :
$(<mySelector>).removeCss();
or
$(<mySelector>).removeCss(false);
if you want to remove also CSS defined in its classes :
$(<mySelector>).removeCss(true);
To do this for a specific target, you can do the following:
target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Also, if you don't have the gradlew file in your current directory:
You can install gradle with homebrew with the following command:
$ brew install gradle
As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):
$ gradle test
it seems that the
yum install ruby-devel
was enough for me to perform
gem install datamapper
afterwards.
It's possible that you will need to install another packages:
yum install gcc gcc-c++
to be able to build native extensions
You could extend FutureTask
class, and override the done()
method, then add the FutureTask
object to the ExecutorService
, so the done()
method will invoke when the FutureTask
completed immediately.
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.
getCurrentDate() {
var date = new Date();
var newDate = new Date(8 * 60 * 60000 + date.valueOf() +
(date.getTimezoneOffset() * 60000));
var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
var strDate = newDate + '';
return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}
It is kind of late for answer, but maybe it helps someone in future. I found it easier to use struct for this kind of problem.
Following sample is copy pasted part from MS code:
namespace System.IdentityModel.Tokens.Jwt
{
//
// Summary:
// List of registered claims from different sources http://tools.ietf.org/html/rfc7519#section-4
// http://openid.net/specs/openid-connect-core-1_0.html#IDToken
public struct JwtRegisteredClaimNames
{
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Actort = "actort";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Typ = "typ";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Sub = "sub";
//
// Summary:
// http://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
public const string Sid = "sid";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Prn = "prn";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Nbf = "nbf";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string Nonce = "nonce";
//
// Summary:
// http://tools.ietf.org/html/rfc7519#section-4
public const string NameId = "nameid";
}
}
Binding = your textual representation of a specific column gets mapped to a physical column in some table, in some database, on some server.
Multipart identifier could be: MyDatabase.dbo.MyTable. If you get any of these identifiers wrong, then you have a multipart identifier that cannot be mapped.
The best way to avoid it is to write the query right the first time, or use a plugin for management studio that provides intellisense and thus help you out by avoiding typos.
The value
attribute of a checkbox
is what you set by:
<input type='checkbox' name='test' value='1'>
So when someone checks that box, the server receives a variable named test
with a value
of 1
- what you want to check for is not the value
of it (which will never change, whether it is checked or not) but the checked
status of the checkbox.
So, if you replace this code:
if (arrChecks[i].value == "on")
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
With this:
arrChecks[i].checked = !arrChecks[i].checked;
It should work. You should use true
and false
instead of 0
and 1
for this.
As Sanf0rd mentioned, Google launched the BottomNavigationView as part of the Design Support Library version 25.0.0. The limitations he mentioned are mostly true, except that you CAN change the background color of the view and even the text color and icon tint color. It also has an animation when you add more than 4 items (sadly it cannot be enabled or disabled manually).
I wrote a detailed tutorial about it with examples and an accompanying repository, which you can read here: https://blog.autsoft.hu/now-you-can-use-the-bottom-navigation-view-in-the-design-support-library/
You have to add these in your app level build.gradle
:
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
You can include it in your layout like this:
<android.support.design.widget.BottomNavigationView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="@color/darkGrey"
app:itemIconTint="@color/bottom_navigation_item_background_colors"
app:itemTextColor="@color/bottom_navigation_item_background_colors"
app:menu="@menu/menu_bottom_navigation" />
You can specify the items via a menu resource like this:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_one"
android:icon="@android:drawable/ic_dialog_map"
android:title="One"/>
<item
android:id="@+id/action_two"
android:icon="@android:drawable/ic_dialog_info"
android:title="Two"/>
<item
android:id="@+id/action_three"
android:icon="@android:drawable/ic_dialog_email"
android:title="Three"/>
<item
android:id="@+id/action_four"
android:icon="@android:drawable/ic_popup_reminder"
android:title="Four"/>
</menu>
And you can set the tint and text color as a color list, so the currently selected item is highlighted:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="@color/colorAccent"
android:state_checked="false"/>
<item
android:color="@android:color/white"
android:state_checked="true"/>
</selector>
Finally, you can handle the selection of the items with an OnNavigationItemSelectedListener:
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_one:
// Switch to page one
break;
case R.id.action_two:
// Switch to page two
break;
case R.id.action_three:
// Switch to page three
break;
}
return true;
}
});
Having read the above answers i found that for my situation the following fixed the issue.
This threw the error
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).
This answer relates to the questions asked in the comments of the OP's post:
To force a view to appear in a given oriention put the following in viewWillAppear:
UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
UIViewController *c = [[UIViewController alloc]init];
[self presentModalViewController:c animated:NO];
[self dismissModalViewControllerAnimated:NO];
}
It's a bit of a hack, but this forces the UIViewController
to be presented in portrait even if the previous controller was landscape
UPDATE for iOS7
The methods above are now deprecated, so for iOS 7 use the following:
UIApplication* application = [UIApplication sharedApplication];
if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
{
UIViewController *c = [[UIViewController alloc]init];
[c.view setBackgroundColor:[UIColor redColor]];
[self.navigationController presentViewController:c animated:NO completion:^{
[self.navigationController dismissViewControllerAnimated:YES completion:^{
}];
}];
}
Interestingly, at the time of writing, either the present or dismiss must be animated. If neither are, then you will get a white screen. No idea why this makes it work, but it does! The visual effect is different depending on which is animated.
The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)
You would be better off using the className "property" on the elements.
Copy the hosts
file and add 127.0.0.1
and name which you want to show or run at the browser link. For example:
127.0.0.1 abc
Then run abc/
as a local host in the browser.
you really should try to use jQuery in a separate file, not inline. Here is what you need:
<a class="notificationClose "><img src="close.png"/></a>
And then this at the bottom of your page in <script>
tags at the very least or in a external JavaScript file.
$(".notificationClose").click(function() {
$("#notification").fadeOut("normal", function() {
$(this).remove();
});
});
AtomicInteger
Maybe this is of some worth also: there is a Java class called AtomicInteger
.
This class has some useful methods like addAndGet(int delta)
or incrementAndGet()
(and their counterparts) which allow you to increment/decrement the value of the same instance. Though the class is designed to be used in the context of concurrency, it's also quite useful in other scenarios and probably fits your need.
final AtomicInteger count = new AtomicInteger( 0 ) ;
…
count.incrementAndGet(); // Ignoring the return value.
You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
You can use sort of Maybe monad (though I'd prefer Jay's answer)
public class Maybe<T>
{
private readonly T _value;
public Maybe(T value)
{
_value = value;
IsNothing = false;
}
public Maybe()
{
IsNothing = true;
}
public bool IsNothing { get; private set; }
public T Value
{
get
{
if (IsNothing)
{
throw new InvalidOperationException("Value doesn't exist");
}
return _value;
}
}
public override bool Equals(object other)
{
if (IsNothing)
{
return (other == null);
}
if (other == null)
{
return false;
}
return _value.Equals(other);
}
public override int GetHashCode()
{
if (IsNothing)
{
return 0;
}
return _value.GetHashCode();
}
public override string ToString()
{
if (IsNothing)
{
return "";
}
return _value.ToString();
}
public static implicit operator Maybe<T>(T value)
{
return new Maybe<T>(value);
}
public static explicit operator T(Maybe<T> value)
{
return value.Value;
}
}
Your method would look like:
public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
{
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
{
string value = HttpContext.Current.Request.QueryString[key];
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
//Could not convert. Pass back default value...
return new Maybe<T>();
}
}
return new Maybe<T>();
}
Note that COLUMNS
is:
SIGWINCH
signal.That second point usually means that your COLUMNS
variable will only be set in your interactive shell, not in a bash script.
If your script's stdin
is connected to your terminal you can manually look up the width of your terminal by asking your terminal:
tput cols
And to use this in your SVN command:
svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"
(Note: you should quote "$@"
and stay away from eval
;-))
If you're okay adding more third-party packages, I used the angular2-moment library. Installation was pretty straightforward, and you should follow the latest instructions on the README. I also installed typings as a result of this.
Worked like a charm for me, and barely added any code to get it working.
This issue was even more strange for us. Everything worked if you had previously visited the sharepoint site from the browser, before you made the SOAP call. However, if you did the SOAP call first we'd throw the above error.
We were able to resolve this issue by installing the sharepoint certificate on the client and adding the domain to the local intranet sites.
One major difference between Sequelize and Persistence.js is that the former supports a STRING
datatype, i.e. VARCHAR(255)
. I felt really uncomfortable making everything TEXT
.
are you behind any proxy?
check your browser for proxy that you might use:
execute the command: gem install xxx --http-proxy=http://user:password@server
and you should be good to go.
Oracle: Just felt to do it in different way. Disadvantage: It doesn't perform full index scan. But still gives the result and can use this in substring.
select employee_name
from employees
where lpad(employee_name,1) ='A'
OR lpad(employee_name,1) = 'B'
order by employee_name
We can use LEFT in SQL Server instead of lpad . Still suggest not a good idea to use this method.
Depending on the version of Windows you might find the use of the "Choice" option to be helpful. It is not supported in most if not all x64 versions as far as I can tell. A handy substitution called Choice.vbs along with examples of use can be found on SourceForge under the name Choice.zip
.move-wrap {
display: table;
table-layout: fixed; // prevent some responsive bugs
width: 100%; // set a width if u like
/* TODO: js-fallback IE7 if u like ms */
}
.move-down {
display: table-footer-group;
}
.move-up {
display: table-header-group;
}
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
For the parent
element, add the following properties:
.parent {
overflow: hidden;
position: relative;
width: 100%;
}
then for .child-right
these:
.child-right {
background:green;
height: 100%;
width: 50%;
position: absolute;
right: 0;
top: 0;
}
Find more detailed results with CSS examples here and more information about equal height columns here.
You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.
http://jsfiddle.net/ayyadurai/GXzhZ/1/
window.onload = function() {_x000D_
var minute = 5;_x000D_
var sec = 60;_x000D_
setInterval(function() {_x000D_
document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
sec--;_x000D_
if (sec == 00) {_x000D_
minute --;_x000D_
sec = 60;_x000D_
if (minute == 0) {_x000D_
minute = 5;_x000D_
}_x000D_
}_x000D_
}, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
In my case new File()
doesn't work, it causes a FileNotFoundException
when run in a Jenkins pipeline job. The following code solved this, and is even easier in my opinion:
def fileContents = readFile "path/to/file"
I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble. Possibly the exception was caused because new File()
creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.
In my case, I had a very old version of npm. Upgrading npm using sudo npm install npm -g
fixed the problem for me. Additionally I also did rm -rf node_modules
and npm cache clean
and npm config set registry "http://registry.npmjs.org/"
<input id="name" type="text" #myInput />
{{ myInput.focus() }}
this is the best and simplest way, because code "myInput.focus()" runs after input created
WARNING: this solution is acceptable only if you have single element in the form (user will be not able to select other elements)
Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.
The way is that the child directive can require
the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:
<div parent-directive>
<div child-directive></div>
<div child-directive></div>
</div>
Then the directives can be coded like:
app.directive('parentDirective', function($window) {
return {
controller: function($scope) {
var registeredElements = [];
this.registerElement = function(childElement) {
registeredElements.push(childElement);
}
}
};
});
app.directive('childDirective', function() {
return {
require: '^parentDirective',
template: '<span>Child directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
parentController.registerElement(iElement);
}
};
});
You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview
This is my summary of the above and works perfectly for me. Thanks for the info!
<script language='javascript' type='text/javascript'>
$(document).ready(function () {
var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
if (firstInput != null) {
firstInput.focus();
}
});
</script>
Re: using icon in :before
–
recent Font Awesome builds include the .fa-icon()
mixin for SASS and LESS. This will automatically include the font-family
as well as some rendering tweaks (e.g. -webkit-font-smoothing
). Thus you can do, e.g.:
// Add "?" icon to header.
h1:before {
.fa-icon();
content: "\f059";
}
You must ";" separator, CSV => Comma Separator Value
ofstream Morison_File ("linear_wave_loading.csv"); //Opening file to print info to
Morison_File << "'Time'; 'Force(N/m)' " << endl; //Headings for file
for (t = 0; t <= 20; t++) {
u = sin(omega * t);
du = cos(omega * t);
F = (0.5 * rho * C_d * D * u * fabs(u)) + rho * Area * C_m * du;
cout << "t = " << t << "\t\tF = " << F << endl;
Morison_File << t << ";" << F;
}
Morison_File.close();
My company does the same thing for a number of customers where we host a web site for them although in our case it's xyz.company.com rather than www.company.com. We do get them to set the A record on xyz.company.com to point to an IP address we allocate them.
As to how you could cope with a change in IP address I don't think there is a perfect solution. Some ideas are:
Use a NAT or IP load balancer and give your customers an IP address belonging to it. If the IP address of the web server needs to change you could make an update on the NAT or load balancer,
Offer a DNS hosting service as well and get your customers to host their domain with you so that you'd be in a position to update the A records,
Get your customers to set their A record up to one main web server and use a HTTP redirect for each customer's web requests.
If you need to do it manually, one time:
First, merge in a temporary table, with something like:
create table MERGED as select * from table 1 UNION select * from table 2
Then, identify the primary key constraints with something like
SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1
Where PK is the primary key field...
Solve the duplicates.
Rename the table.
[edited - removed brackets in the UNION query, which was causing the error in the comment below]
The most efficient way is to take input make the logic and run
so the code is like this to make your own space maker
need = input("Write a string:- ")
result = ''
for character in need:
result = result + character + ' '
print(result) # to rid of space after O
but if you want to use what python give then use this code
need2 = input("Write a string:- ")
print(" ".join(need2))
Disabling the Sync to VBlank checkbox in nvidia-settings (OpenGL Settings tab) does the trick for me.
ES6 features like promises aren't defined when targeting ES5. There are other libraries, but core-js is the javascript library that the Angular team uses. It contains polyfills for ES6.
Angular 2 has changed a lot since this question was asked. Type declarations are much easier to use in Typescript 2.0.
npm install -g typescript
For ES6 features in Angular 2, you don't need Typings. Just use typescript 2.0 or higher and install @types/core-js with npm:
npm install --save-dev @types/core-js
Then, add the TypeRoots and Types attributes to your tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"typeRoots": [
"../node_modules/@types"
],
"types" : [
"core-js"
]
},
"exclude": [
"node_modules"
]
}
This is much easier than using Typings, as explained in other answers. See Microsoft's blog post for more info: Typescript: The Future of Declaration Files
In the medical industry, VT is used as the start of frame character in the MLLP/LLP/HLLP protocols that are used to frame HL-7 data, which has been a standard for medical exchange since the late 80s and is still in wide use.
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
Now as from angular2 beta 8 we can use *ngIf
and *ngFor
on same component see here.
Alternate:
Sometimes we can't use HTML tags inside another like in tr
, th
(table
) or in li
(ul
). We cannot use another HTML tag but we have to perform some action in same situation so we can HTML5 feature tag <template>
in this way.
<template ngFor #abc [ngForOf]="someArray">
code here....
</template>
<template [ngIf]="show">
code here....
</template>
For more information about structural directives in angular2 see here.
For the sake of completeness:
while read _ _ one _ two _; do
echo "$one $two"
done < file.txt
Instead of _
an arbitrary variable (such as junk
) can be used as well. The point is just to extract the columns.
Demo:
$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
In component.ts add this function
_keyUp(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.key);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
In your template use the following
<input(keyup)="_keyUp($event)">
This will catch the input before angular2 catches the event.
There seems to be quite a variety of ways of preventing the system keyboard from appearing, both programmatically and in xml. However, this is the way that has worked for me while supporting pre API 11 devices.
// prevent system keyboard from appearing
if (android.os.Build.VERSION.SDK_INT >= 11) {
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
} else {
editText.setRawInputType(InputType.TYPE_NULL);
editText.setFocusable(true);
}
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
let str = 'https://example.com is a great site'
str.replace(/(https?:\/\/[^\s]+)/g,"<a href='$1' target='_blank' >$1</a>")
Short Code Big Work!...
Result:-
<a href="https://example.com" target="_blank" > https://example.com </a>
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
keep it simple and explicit. You can of course pre-define a dictionary.
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
If you plan on modifying your simulate
function to include more return codes, maintaining this code might become a bit of an issue.
The simulate
might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.
Most portably...
#include <limits>
using std::numeric_limits;
...
cout.precision(numeric_limits<double>::digits10 + 1);
cout << d;
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.
When using unique_ptr
, there can be at most one unique_ptr
pointing at any one resource. When that unique_ptr
is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr
to any resource, any attempt to make a copy of a unique_ptr
will cause a compile-time error. For example, this code is illegal:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr
However, unique_ptr
can be moved using the new move semantics:
unique_ptr<T> myPtr(new T); // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr
Similarly, you can do something like this:
unique_ptr<T> MyFunction() {
unique_ptr<T> myPtr(/* ... */);
/* ... */
return myPtr;
}
This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr
as a safer, better replacement for auto_ptr
.
shared_ptr
, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr
to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
shared_ptr<T> myPtr(new T); // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.
Internally, shared_ptr
uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
In short:
unique_ptr
when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.shared_ptr
when you want multiple pointers to the same resource.Hope this helps!
Try as below:
var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);
I can't believe nobody suggested this:
int i = 9;
i.ToString("D2"); // Will give you the string "09"
or
i.ToString("D8"); // Will give you the string "00000009"
If you want hexadecimal:
byte b = 255;
b.ToString("X2"); // Will give you the string "FF"
You can even use just "C" to display as currency if you locale currency symbol. See here: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_
From the Haskell Wiki:
Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. This page collects resources on the industrial use of Haskell.
According to Wikipedia, the Haskell language was created out of the need to consolidate existing functional languages into a common one which could be used for future research in functional-language design.
It is apparent based on the information available that it has outgrown it's original purpose and is used for much more than research. It is now considered a general purpose functional programming language.
If you're still asking yourself, "Why should I use it?", then read the Why use it? section of the Haskell Wiki Introduction.
The namespace System.Security.Cryptography
contains the TripleDESCryptoServiceProvider
and RijndaelManaged
classes
Don't forget to add a reference to the System.Security
assembly.
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php
Let me add a little to Sebastian Roth's answer.
Your project can be compiled by using ndk-build
in the command line after adding the code Sebastian had posted. But as for me, there were syntax errors in Eclipse, and I didn't have code completion.
Note that your project must be converted to a C/C++ project.
How to convert a C/C++ project
To fix this issue right-click on your project, click Properties
Choose C/C++ General -> Paths and Symbols and include the ${ANDROID_NDK}/sources/cxx-stl/stlport/stlport
to Include directories
Click Yes when a dialog shows up.
Before
After
Update #1
GNU C. Add directories, rebuild. There won't be any errors in C source files
GNU C++. Add directories, rebuild. There won't be any errors in CPP source files.
In my case in which I synced my mysql data and htdocs to dropbox, I just needed to delete the conflicted files in mysql/data folder and subfolders. The conflicted files can be identified by its names, dropbox will tell you that. It has solved the problem for me.
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.
Any <input type="file">
based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)
C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.
C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.
C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.
In javascript, it is not possible but yes with the help of “Web Clips” we can create a "add to home screen" icon or shortcut in iPhone( by the code file of .mobileconfig)
http://appdistro.cttapp.com/webclip/
after create a mobileconfig file we can pass this url in iphone safari browser install certificate and after done it check your iphone home screen there is a shortcut icon of your Web page or webapp..
Here is another method to get date
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
I have found a great solution for fixed backgrounds on mobile devices requiring no JavaScript at all.
body:before {
content: "";
display: block;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: -10;
background: url(photos/2452.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Please be aware of the negative z-index
value of -10
. html
root element default z-index
is 0
. This value must be the smallest z-index
to have it as background.
Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger
syntax.
Try changing
$('input[name = butAssignProd]').click();
to
$('input[name = butAssignProd]').trigger("click");
If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?
The easiest way is using Ajax Post Request:
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success,
dataType: dataType
});
where:
Then in the success handler redirect the browser with something like window.location.
If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
Problem 2 is OK, because " System.out.println(set);" means "System.out.println(set.toString());" set is an instance of List, so complier will call List.toString();
public static void test(List<?> set){
set.add(new Long(2)); //--> Error
set.add("2"); //--> Error
System.out.println(set);
}
Element ? will not promise Long and String, so complier will not accept Long and String Object
public static void test(List<String> set){
set.add(new Long(2)); //--> Error
set.add("2"); //--> Work
System.out.println(set);
}
Element String promise it a String, so complier will accept String Object
Problem 3: these symbols are same, but you can give them differet specification. For example:
public <T extends Integer,E extends String> void p(T t, E e) {}
Problem 4: Collection does not allow type parameter covariance. But array does allow covariance.
Set private int selected_position = -1;
to prevent from any item being selected on start.
@Override
public void onBindViewHolder(final OrdersHolder holder, final int position) {
final Order order = orders.get(position);
holder.bind(order);
if(selected_position == position){
//changes background color of selected item in RecyclerView
holder.itemView.setBackgroundColor(Color.GREEN);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
//this updated an order property by status in DB
order.setProductStatus("0");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//status switch and DB update
if (order.getProductStatus().equals("0")) {
order.setProductStatus("1");
notifyItemChanged(selected_position);
selected_position = position;
notifyItemChanged(selected_position);
} else {
if (order.getProductStatus().equals("1")){
//calls for interface implementation in
//MainActivity which opens a new fragment with
//selected item details
listener.onOrderSelected(order);
}
}
}
});
}
I was just having this problem on Windows 10 and the issue in my case was that I was just running psql
and it was defaulting to trying to log in with my Windows username ("Nathan"), but there was no PostgreSQL user with that name, and it wasn't telling me that.
So the solution was to run psql -U postgres
rather than just psql
, and then the password I entered at installation worked.
You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
And as a one-liner:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
An efficient method for extracting, decoding, and checking for errors is:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = str_replace( ' ', '+', $data );
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
file_put_contents("img.{$type}", $data);
This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update
again:
since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.
and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.
After iOS 13 you should detect iOS devices like this, since iPad will not be detected as iOS devices by old ways (due to new "desktop" options, enabled by default):
let isIOS = /iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
The first condition for iOS < 13 or iPhone or iPad with disabled Desktop mode, the second condition for iPadOS 13 in the default configuration, since it position itself like Macintosh Intel, but actually is the only Macintosh with multi-touch.
Rather a hack than a real solution, but work reliably for me
P.S. As being said earlier, you probably should add IE checkup
let isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream
In my case Codec ID of mp4 file was the issue, Codec ID: isom (isom/iso2/avc1/mp41) was not playing in IE 10 and 11 using video tag, after I converted it to "mp42 (mp42/isom/avc1)" using FFmpeg it started playing in IE as well.
As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:
U+0022
("
, the quotation mark)U+005C
(\
, the backslash or reverse solidus) U+0000
to U+001F
(the ASCII control characters)In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:
U+002F
(/
)U+0027
('
)U+003C
(<
)U+003E
(>
)U+0026
(&
)U+0085
(Next Line)U+2028
(Line Separator)U+2029
(Paragraph Separator)Some of the above characters can be escaped with the following short escape sequences defined in the standard:
\"
represents the quotation mark character (U+0022).\\
represents the reverse solidus character (U+005C).\/
represents the solidus character (U+002F).\b
represents the backspace character (U+0008).\f
represents the form feed character (U+000C).\n
represents the line feed character (U+000A).\r
represents the carriage return character (U+000D).\t
represents the character tabulation character (U+0009).The other characters which need to be escaped will use the \uXXXX
notation, that is \u
followed by the four hexadecimal digits that encode the code point.
The \uXXXX
can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).
$parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it
<div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
<div>
<div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
<a ng-click="addSomething(parentIndex)">Add Something</a>
</div>
</div>
</div>
I was failing to send a body on a DELETE that required one and was getting this message as a result.
There are a couple of things that need to be adjusted in your layout:
You are nesting col
elements within form-group
elements. This should be the other way around (the form-group
should be within the col-sm-xx
element).
You should always use a row
div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12
is still on the same row with the above 3 .col-sm-4
resulting in a total of columns greater than 12, and causing the overlap problem.
Here is a fixed demo.
And an excerpt of what the problematic section HTML should become:
<fieldset>
<legend>Personal Information</legend>
<div class='row'>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_title">Title</label>
<input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_firstname">First name</label>
<input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_lastname">Last name</label>
<input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-12'>
<div class='form-group'>
<label for="user_email">Email</label>
<input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
</div>
</div>
</div>
</fieldset>
When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.
ga('create', 'UA-XXXXX-Y', {
cookieFlags: 'max-age=7200;secure;samesite=none'
});
Also more info in this blog post
The page How to Write Doc Coments for the Javadoc Tool contains a good number of good examples. One section is called Examples of Doc Comments and contains quite a few usages.
Also, the Javadoc FAQ contains some more examples to illustrate the answers.
Update with a strict with join
& split
cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
cities.join(' ').split
Result will be:
["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Note that: this doesn't work with a city with spaces
When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.
In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).
The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:
patch -p1 < save.patch
I found IE11 is giving more than one user agent strings in different environments.
Instead of relying on MSIE
, and other approaches, It's better to rely on Trident
version
const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;
Hope this helps :)
If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {
@Test
public void testAcreate() {
System.out.println("first");
}
@Test
public void testBupdate() {
System.out.println("second");
}
@Test
public void testCdelete() {
System.out.println("third");
}
}
Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.
I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.
Heres another good comparison of individual characteristics of each protocol.
Try this :
import re
[int(s) for s in re.split('[\s,]+',example_string)]
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
And this works for me:
$(function () {
$('#datetimepicker5').datetimepicker({
format: 'HH:mm'
});
});
If you import os
you can use os.getcwd
to get the current working directory, and you can use os.chdir
to change your directory
In my case, I was moving a SProc between servers and the profile name in my TSQL code did not match the profile name on the new server.
Updating TSQL profile name == New server profile name fixed the error for me.
You have to update the PATH based on the terminal(bash or zsh) which you use.
~/.bashrc
or ~/.zshrc
in an editorvi ~/.zshrc (or) code ~/.zshrc
export GOPATH=$HOME/go:/$HOME/projects/go
Here you can add one or more paths separated by a semicolon :
from different locations of your GO projects on the system to the GOPATH
environment variable i.e /path/1:path/2:path/3
etc.
In my case, I have added 2 paths, as shown above, one from the root $HOME/go
and the other one from the projects directory :/$HOME/projects/go
Just add the second .absolute div before the other .second div:
<div class="absolute" style="top: 54px"></div>
<div class="absolute">
<div id="relative"></div>
</div>
Because the two elements have an index 0.
In jquery, u can delcare variable two styles.
One is,
$.name = 'anirudha';
alert($.name);
Second is,
var hText = $("#head1").text();
Second is used when you read data from textbox
, label
, etc.
function convertBoolean(value): boolean {
if (typeof value == 'string') {
value = value.toLowerCase();
}
switch (value) {
case true:
case "true":
case "evet": // Locale
case "t":
case "e": // Locale
case "1":
case "on":
case "yes":
case 1:
return true;
case false:
case "false":
case "hayir": // Locale
case "f":
case "h": // Locale
case "0":
case "off":
case "no":
case 0:
return false;
default:
return null;
}
}
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
block1 = new Droid(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic), 100, 10);
//OR
builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic));
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.
I'm using this function
function isNull() {
for (var i = 0; i < arguments.length; i++) {
if (
typeof arguments[i] !== 'undefined'
&& arguments[i] !== undefined
&& arguments[i] != null
&& arguments[i] != NaN
&& arguments[i]
) return arguments[i];
}
}
test
console.log(isNull(null, null, undefined, 'Target'));
If you want to know if list element at index i
is set or not, you can simply check the following:
if len(l)<=i:
print ("empty")
If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None
. That is you can write:
l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
print ("list has actually an element at position i, which is None")
Most of the answer here covers almost everything except this tool, one of the coolest ways to see the log.
It is Facebook's Stetho. This is the superb tool to monitor/log your app's network traffic on google chrome. You can also find here on Github.
You can simply go to Menu > All Programs > Visual Studio 2013. Select the folder link "Visual Studio Tools". This will open the folder. There is bunch of shortcuts for command prompt which you can use. They worked perfectly for me.
I think the trick here might be there are different versions for different processors, hence they put them all together.