You can use std::numeric_limits
which is defined in <limits>
to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a -
in front for negative infinity).
#include <limits>
//...
std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();
As noted in the comments, min()
returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.
There is of course the std::max_element
and min_element functions (defined in <algorithm>
) which may be a better choice for finding the largest or smallest value in an array.
Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];
int minThreshold = [myNumber intValue];
NSLog(@"Setting for minThreshold %i", minThreshold);
if ((int)minThreshold < 1 )
{
NSLog(@"Not a number");
}
else
{
NSLog(@"Setting for integer minThreshold %i", minThreshold);
}
[f release];
You can convert, but I don't think there's anything built in to do it automatically:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
(Note that this will throw a NullPointerException if either integers
or any element within it is null
.)
EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList
:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
You can use setTableId((short)100)
. I think this was changed in Java 5 so that numeric literals assigned to byte or short and within range for the target are automatically assumed to be the target type. That latest J2ME JVMs are derived from Java 4 though.
For those we need the Swift version of the answer of @Jeff Thompson:
// Get a current time for where you want to start measuring from
var date = NSDate()
// do work...
// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
var timePassed_ms: Double = date.timeIntervalSinceNow * -1000.0
I hope this help you.
You can get much more detailed information than the bash built-in time
(which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time
.
Editor's note:
To ensure that you're invoking the external utility time
rather than your shell's time
keyword, invoke it as /usr/bin/time
.
time
is a POSIX-mandated utility, but the only option it is required to support is -p
.
Specific platforms implement specific, nonstandard extensions: -v
works with GNU's time
utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -l
to produce similar output - see man 1 time
.
Example of verbose output:
$ /usr/bin/time -v sleep 1
Command being timed: "sleep 1"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 1%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 210
Voluntary context switches: 2
Involuntary context switches: 1
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
I'm using Bootstrap 3, so i don't know if there is an easier way to do it Bootstrap 4 but this css should work for you:
.pull-right-xs {
float: right;
}
@media (min-width: 768px) {
.pull-right-xs {
float: left;
}
}
...and add class to second column:
<div class="row">
<div class="col-xs-3 col-md-6">
1
</div>
<div class="col-xs-3 col-md-6 pull-right-xs">
2
</div>
<div class="col-xs-6 col-md-12">
3
</div>
</div>
EDIT:
Ohh... it looks like what i was writen above is exacly a .pull-xs-right class in Bootstrap 4 :X Just add it to second column and it should work perfectly.
You can also use list comprehension on splitted string
[ int(x) for x in example_string.split(',') ]
I know it's very late for this one... But here is a (not so simple) oneliner to get what you were looking for:
git show-branch --all 2>/dev/null | grep -E "\[$(git branch | grep -E '^\*' | awk '{ printf $2 }')" | tail -n+2 | sed -E "s/^[^\[]*?\[/[/"
git show-branch
(sending the warnings to /dev/null
).grep -E "\[$BRANCH_NAME"
.$BRANCH_NAME
is obtained with git branch | grep -E '^\*' | awk '{ printf $2 }'
(the branch with a star, echoed without that star).tail -n+2
.[$BRANCH_NAME]
with sed -E "s/^[^\[]*?\[/[/"
.This takes care of nulls
var body = JObject.Parse("anyjsonString");
body?.SelectToken("path-string-prop")?.ToString();
body?.SelectToken("path-double-prop")?.ToObject<double>();
file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.
See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins
Changing this key worked for me:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Personal
The location didn't exist.
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
The date function can return this if you specify the format correctly:
$daynum = date("w", strtotime("wednesday"));
will return 0 for Sunday through to 6 for Saturday.
An alternative format is:
$daynum = date("N", strtotime("wednesday"));
which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
// Replace invalid characters with empty strings.
Regex.Replace(inputString, @"[^\w\.@-]", "");
The regular expression pattern [^\w.@-] matches any character that is not a word character, a period, an @ symbol, or a hyphen. A word character is any letter, decimal digit, or punctuation connector such as an underscore. Any character that matches this pattern is replaced by String.Empty, which is the string defined by the replacement pattern. To allow additional characters in user input, add those characters to the character class in the regular expression pattern. For example, the regular expression pattern [^\w.@-\%] also allows a percentage symbol and a backslash in an input string.
Regex.Replace(inputString, @"[!@#$%_]", "");
Refer this too :
Removing Invalid Characters from XML Name Tag - RegEx C#
Here is a function to remove the characters from a specified XML string:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace XMLUtils
{
class Standards
{
/// <summary>
/// Strips non-printable ascii characters
/// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
/// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
/// </summary>
/// <param name="content">contents</param>
/// <param name="XMLVersion">XML Specification to use. Can be 1.0 or 1.1</param>
private void StripIllegalXMLChars(string tmpContents, string XMLVersion)
{
string pattern = String.Empty;
switch (XMLVersion)
{
case "1.0":
pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
break;
case "1.1":
pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
break;
default:
throw new Exception("Error: Invalid XML Version!");
}
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(tmpContents))
{
tmpContents = regex.Replace(tmpContents, String.Empty);
}
tmpContents = string.Empty;
}
}
}
I made this:
function repeat(func, times) {
for (var i=0; i<times; i++) {
func(i);
}
}
Usage:
repeat(function(i) {
console.log("Hello, World! - "+i);
}, 5)
/*
Returns:
Hello, World! - 0
Hello, World! - 1
Hello, World! - 2
Hello, World! - 3
Hello, World! - 4
*/
The i
variable returns the amount of times it has looped - useful if you need to preload an x amount of images.
For a MinGW platform and if you are compiling a Debug target by a hand made CMakeLists.txt written ad hoc you need to add the qwindows.dll to the platform dir as well. The windeployqt executable does its work well but it seems that for some strange reason the CMake build needs the release variant as well. In summary it will be better to have both the qwindows.dll and qwindowsd.dll in your platform directory. I did not notice the same strange result when importing the CMake project in QtCreator and then running the build procedure. Compiling on the command line the CMake project seems to trigger the qwindows.dll dependency either if the correct one for the Debug target is set in place (qwindowsd.dll)
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
I came across this myself. I used .on
so it looks a bit different but I did this:
$('#element').on('keypress', function() {
//code to be executed
}).on('keydown', function(e) {
if (e.keyCode==8)
$('element').trigger('keypress');
});
Adding my Work Around here. I needed to delete ssn typed by user so i did this in jQuery
$(this).bind("keydown", function (event) {
// Allow: backspace, delete
if (event.keyCode == 46 || event.keyCode == 8)
{
var tempField = $(this).attr('name');
var hiddenID = tempField.substr(tempField.indexOf('_') + 1);
$('#' + hiddenID).val('');
$(this).val('')
return;
} // Allow: tab, escape, and enter
else if (event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else
{
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
{
event.preventDefault();
}
}
});
Other languages have short cuts for ranges of field numbers, but not awk, you'll have to write your code as your fear ;-)
awk -F, 'BEGIN {OFS=","} { print $1, $2, $3, $4 ..... $30, $33}' infile.csv > outfile.csv
There is no direct function in awk to use field names as column specifiers.
I hope this helps.
I'm using Object.keys(chars).map(...)
to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
In Angular 7 works perfect
HTML
<button (click)="scroll(target)">Click to scroll</button>
<div #target>Your target</div>
In component
scroll(el: HTMLElement) {
el.scrollIntoView({behavior: 'smooth'});
}
There is no "correct" way to store a 64-bit pointer in an 32-bit integer. The problem is not with casting, but with the target type loosing half of the pointer. The 32 remaining bits stored inside int
are insufficient to reconstruct a pointer to the thread function. Most answers just try to extract 32 useless bits out of the argument.
As Ferruccio said, int must be replaced with intptr_t
to make the program meaningful.
if you don´t have the library into your workspace in Eclipse you can add it with:
File
-> Import
-> Existing Android Code Into Workspace
-> browse and navigate to google-play-services_lib
project lib, (android-sdk/extras/google/google_play_services/libproject
).
/bin
and /gen
folders of my project (something similar to the clean option) and building my project again.LONG VERSION
src: https://en.wikipedia.org/wiki/C_date_and_time_functions
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
time_t current_time;
char* c_time_string;
/* Obtain current time. */
current_time = time(NULL);
if (current_time == ((time_t)-1))
{
(void) fprintf(stderr, "Failure to obtain the current time.\n");
exit(EXIT_FAILURE);
}
/* Convert to local time format. */
c_time_string = ctime(¤t_time);
if (c_time_string == NULL)
{
(void) fprintf(stderr, "Failure to convert the current time.\n");
exit(EXIT_FAILURE);
}
/* Print to stdout. ctime() has already added a terminating newline character. */
(void) printf("Current time is %s", c_time_string);
exit(EXIT_SUCCESS);
}
The output is:
Current time is Thu Sep 15 21:18:23 2016
SHORT VERSION:
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[]) {
time_t current_time;
time(¤t_time);
printf("%s", ctime(¤t_time));
The output is:
Current time is Thu Jan 28 15:22:31 2021
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
I know this is an old question, but I was looking for the similar thing. Determine when the 'X' was clicked to clear the search box. None of the answers here helped me at all. One was close but also affected when the user hit the 'enter' button, it would fire the same result as clicking the 'X'.
I found this answer on another post and it works perfect for me and only fires when the user clears the search box.
$("input").bind("mouseup", function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue == ""){
// capture the clear
$input.trigger("cleared");
}
}, 1);
});
I had similar situation. I found that one of my config maps was duplicated. I had two configmaps for the same namespace. One had the correct namespace reference, the other was pointing to the wrong namespace.
I deleted and recreated the configmap with the correct file (or fixed file). I am only using one, and that seemed to make the particular cluster happier.
So I would check the files for any typos or duplicate items that could be causing conflict.
If someone is facing issue using texttocolumns function in UFT. Please try using below function.
myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
Here we are using coma(,) as delimiter.
You should do:
try:
value_index = my_list.index(value)
except:
value_index = -1;
exit(X)
, where X is a number (according to the doc) should work.
But it is not recommended by Apple and won't be accepted by the AppStore.
Why? Because of these guidelines (one of my app got rejected):
We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.
Please refer to the attached screenshot/s for reference.
The iOS Human Interface Guidelines specify,
"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:
Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.
Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."
> It would be appropriate to remove any mechanisms for quitting your app.
Plus, if you try to hide that function, it would be understood by the user as a crash.
Another option:
if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
...
}
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:
$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
mb_substr( $str, -7, null, 'UTF-8') ;
You can click on the Project window, press Alt-Insert, and select Folder->Assets Folder. Android Studio will add it automatically to the correct location.
You are most likely looking at your Project with the new(ish) "Android View". Note that this is a view and not the actual folder structure on disk (which hasn't changed since the introduction of Gradle as the new build tool). You can switch to the old "Project View" by clicking on the word "Android" at the top of the Project window and selecting "Project".
If you think that there is a conflict you can use jQuery.noConflict()
in your code. Details are in the docs.
REFERENCING MAGIC - SHORTCUTS FOR JQUERY
If you don't like typing the full "jQuery" all the time, there are some alternative shortcuts:
Reassign jQuery to another shortcut
var $j = jQuery;
(This might be the best approach if you wish to use different libraries) Use the following technique, which allows you to use $ inside of a block of code without permanently overwriting $:
(function($) { /* some code that uses $ */ })(jQuery)
Note: If you use this technique, you will not be able to use Prototype methods inside this capsuled function that expect $ to be Prototype's $, so you're making a choice to use only jQuery in that block. Use the argument to the DOM ready event:
jQuery(function($) { /*some code that uses $ */ });
Note: Again, inside that block you can't use Prototype methods
Thats from the end of the docs and might be useful to you
If you want to hide overflow on fixed-position elements, the simplest approach I've found is to place the element inside a container element, and apply position:fixed
and overflow:hidden
to that element instead of the contained element (you must remove position:fixed
from the contained element for this to work). The content of the fixed container should then be clipped as expected.
In my case I was having trouble with using object-fit:cover
on a fixed-position element (it was spilling outside the bounds of the page body, regardless of overflow:hidden
). Placing it inside a fixed container with overflow:hidden
on the container fixed the issue.
With argc
(argument count) and argv
(argument vector) you can get the number and the values of passed arguments when your application has been launched.
This way you can use parameters (such as -version
) when your application is started to act a different way.
But you can also use int main(void)
as a prototype in C.
There is a third (less known and nonstandard) prototype with a third argument which is envp
. It contains environment variables.
Resources:
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
To get each sum in a separate column:
Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash')
and CDate<=SYSDATETIME()
and CStatus='Active';
JQuery .is
will test all specified elements and return true if at least one of them matches selector:
if ($(":checkbox[name='choices']", form).is(":checked"))
{
// one or more checked
}
else
{
// nothing checked
}
Change function file_get_content()
in your code to file_get_contents()
. You are missing 's' at the end of function name. That is why it is giving undefined function error.
Remove last unnecessary comma after $image
filed in line
"INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)
Yes, you can use the shadow spread property of the box-shadow rule:
.myDiv_x000D_
{_x000D_
border: 1px solid #333;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
box-shadow: 10px 0 5px -2px #888;_x000D_
}
_x000D_
<div class="myDiv"></div>
_x000D_
The fourth property there -2px
is the shadow spread, you can use it to change the spread of the shadow, making it appear that the shadow is on one side only.
This also uses the shadow positioning rules 10px
sends it to the right (horizontal offset) and 0px
keeps it under the element (vertical offset.)
5px
is the blur radius :)
Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS
https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en
Give it an ID like "something", then:
var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
Changing the background color (as per your updated question):
something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
I was able to figure it out. In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);
Let me know if there is a simpler way o doing it.
I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).
printf("%.2X", a);
'2' defines the precision, 'X' or 'x' defines case.
Here is firefox profile default prefs from python selenium 2.31.0 firefox_profile.py
and type "about:config" in firefox address bar to see all prefs
reference to the entries in about:config: http://kb.mozillazine.org/About:config_entries
DEFAULT_PREFERENCES = {
"app.update.auto": "false",
"app.update.enabled": "false",
"browser.download.manager.showWhenStarting": "false",
"browser.EULA.override": "true",
"browser.EULA.3.accepted": "true",
"browser.link.open_external": "2",
"browser.link.open_newwindow": "2",
"browser.offline": "false",
"browser.safebrowsing.enabled": "false",
"browser.search.update": "false",
"extensions.blocklist.enabled": "false",
"browser.sessionstore.resume_from_crash": "false",
"browser.shell.checkDefaultBrowser": "false",
"browser.tabs.warnOnClose": "false",
"browser.tabs.warnOnOpen": "false",
"browser.startup.page": "0",
"browser.safebrowsing.malware.enabled": "false",
"startup.homepage_welcome_url": "\"about:blank\"",
"devtools.errorconsole.enabled": "true",
"dom.disable_open_during_load": "false",
"extensions.autoDisableScopes" : 10,
"extensions.logging.enabled": "true",
"extensions.update.enabled": "false",
"extensions.update.notifyUser": "false",
"network.manage-offline-status": "false",
"network.http.max-connections-per-server": "10",
"network.http.phishy-userpass-length": "255",
"offline-apps.allow_by_default": "true",
"prompts.tab_modal.enabled": "false",
"security.fileuri.origin_policy": "3",
"security.fileuri.strict_origin_policy": "false",
"security.warn_entering_secure": "false",
"security.warn_entering_secure.show_once": "false",
"security.warn_entering_weak": "false",
"security.warn_entering_weak.show_once": "false",
"security.warn_leaving_secure": "false",
"security.warn_leaving_secure.show_once": "false",
"security.warn_submit_insecure": "false",
"security.warn_viewing_mixed": "false",
"security.warn_viewing_mixed.show_once": "false",
"signon.rememberSignons": "false",
"toolkit.networkmanager.disable": "true",
"toolkit.telemetry.enabled": "false",
"toolkit.telemetry.prompted": "2",
"toolkit.telemetry.rejected": "true",
"javascript.options.showInConsole": "true",
"browser.dom.window.dump.enabled": "true",
"webdriver_accept_untrusted_certs": "true",
"webdriver_enable_native_events": "true",
"webdriver_assume_untrusted_issuer": "true",
"dom.max_script_run_time": "30",
}
If you are trying to do something very similar: a is not None
, the same issue comes up. That is, Numpy complains that one must use a.any
or a.all
.
A workaround is to do:
if not (a is None):
pass
Not too pretty, but it does the job.
I've tested all given regexes but unfortunately none of them pass those tests:
String []goodNums={"3","-3","0","0.0","1.0","0.1"};
String []badNums={"001","-00.2",".3","3.","a",""," ","-"," -1","--1","-.1","-0", "2..3", "2-", "2...3", "2.4.3", "5-6-7"};
Here is the best I wrote that pass all those tests:
"^(-?0[.]\\d+)$|^(-?[1-9]+\\d*([.]\\d+)?)$|^0$"
Add this to your EditText xml file:
<EditText ...
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false">
</EditText>
It will do the same effect as android:editable="false"
. Worked for me, hope it'll work for you too.
From Javarevisited blog post:
Here are a few important differences between static and dynamic binding:
- Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
private
,final
andstatic
methods and variables use static binding and are bonded by compiler while virtual methods are bonded during runtime based upon runtime object.- Static binding uses
Type
(class
in Java) information for binding while dynamic binding uses object to resolve binding.- Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest { public static void main(String args[]) { Collection c = new HashSet(); StaticBindingTest et = new StaticBindingTest(); et.sort(c); } //overloaded method takes Collection argument public Collection sort(Collection c) { System.out.println("Inside Collection sort method"); return c; } //another overloaded method which takes HashSet argument which is sub class public Collection sort(HashSet hs) { System.out.println("Inside HashSet sort method"); return hs; } }
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car vehicle.start(); //Car's start called because start() is overridden method } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { @Override public void start() { System.out.println("Inside start method of Car"); } }
Output: Inside start method of Car
You need to manually delete the children. the <condition>
is the same for both queries.
DELETE FROM child
FROM cTable AS child
INNER JOIN table AS parent ON child.ParentId = parent.ParentId
WHERE <condition>;
DELETE FROM parent
FROM table AS parent
WHERE <condition>;
If you want to check if an element exists in a list, use the contains method.
if (list1.contains(Object o))
{
//do this
}
select convert(time,GETDATE())
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Got this with flask :
Means that the port you're trying to bind to, is already in used by another service or process : got a hint on this in my code developed on Eclipse / windows :
if __name__ == "__main__":
# Check the System Type before to decide to bind
# If the system is a Linux machine -:)
if platform.system() == "Linux":
app.run(host='0.0.0.0',port=5000, debug=True)
# If the system is a windows /!\ Change /!\ the /!\ Port
elif platform.system() == "Windows":
app.run(host='0.0.0.0',port=50000, debug=True)
You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:
myproductionbuild{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
Better to have your debug with minifyEnabled false
and productionbuild and other builds as minifyEnabled true
.
Copy your proguard-rules.txt file in the root of your module or project folder like
$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt
You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType
Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype)
under module tasks
Go to Build Variant in Left Panel and select the build from drop down
Go to project root directory in File Explorer and open cmd/terminal and run
Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)
Windows gradlew assembleRelease or assemble(#your_defined_buildtype)
You can find apk in your module/build directory.
More about the configuration and proguard files location is available at the link
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard
I saw this somewhere else. I am using 2016 Excel. What worked for me was to use YYYY Quarters (I was looking for quarterly data). So, I had the source data sorted as YYYY xQ. 2016 1Q, 2016 2Q, 2016 3Q, 2016, 4Q, 2017 1Q, 2017 2Q... You get the idea.
The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue
in such a case, and unlike the currently accepted answer, will not throw an exception.
dt2.GetValueOrDefault().ToString(format);
A conditional insert for use typically in a MySQL script would be:
insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
from dual
where [conditional predicate];
You need to use dummy table dual.
In this example, only the second insert-statement will actually insert data into the table:
create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
| 2 |
+------+
1 row in set (0.00 sec)
You could insert the desired rows' ids into a temp table and then delete all the rows that are found in that table.
which may be what @Cheekysoft meant by doing it in two steps.
http://allu.wordpress.com/2006/11/08/difference-between-final-finally-and-finalize/
final – constant declaration.
finally – The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
Did you try searching on google, and need clarification for an explanation?
You should treat it as an array like this,
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Then only, you can take its count and loop it for deletion.
You also need to pass the database connection to the query.
$result = mysqli_query($dbc, $sql);
Yours did not include it:
$result = mysqli_query($sql);
You should use an AsyncTask (or other way to perform a network operation on background).
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create and execute the download task
MyAsyncTask async = new MyAsyncTask();
async.execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
//execute on background (out of the UI thread)
protected Long doInBackground(URL... urls) {
DownloadFiles();
}
}
More info about AsyncTask on Android documentation
Hope it helps.
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.
You likely want File.toPath()
.
The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:
...
...
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
android:id="@+id/icon_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</TabHost>
in Java:
final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;
FrameLayout frameLayout = (FrameLayout) materialDialog
.findViewById(R.id.icon_frame_container);
frameLayout.setOnTouchListener(
new OnSwipeTouchListener(ShowCardActivity.this) {
second try to create AlterDailog from the builder then call show().
private boolean visible = false;
class chkSubscription extends AsyncTask<String, Void, String>
{
protected void onPostExecute(String result)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(sucObject);
builder.setInverseBackgroundForced(true);
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.dismiss();
}
});
AlertDialog myAlertDialog = builder.create();
if(visible) myAlertDialog.show();
}
@Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
}
@Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
visible = true;
}
@Override
protected void onStop()
{
visible = false;
super.onStop();
}
Have you tried using str.splitlines()
method?:
From the docs:
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless
keepends
is given and true.
For example:
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']
This method uses the universal newlines approach to splitting lines.
The main difference between Python 2.X
and Python 3.X
is that the former uses the universal newlines approach to splitting lines, so "\r"
, "\n"
, and "\r\n"
are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:
\v
or \x0b
: Line Tabulation (added in Python 3.2
).\f
or \x0c
: Form Feed (added in Python 3.2
).\x1c
: File Separator.\x1d
: Group Separator.\x1e
: Record Separator.\x85
: Next Line (C1 Control Code).\u2028
: Line Separator.\u2029
: Paragraph Separator.Unlike
str.split()
when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
>>> ''.splitlines()
[]
>>> 'Line 1\n'.splitlines()
['Line 1']
While str.split('\n')
returns:
>>> ''.split('\n')
['']
>>> 'Line 1\n'.split('\n')
['Line 1', '']
If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines()
, you could use str.splitlines()
together with str.strip()
:
>>> [str.strip() for str in 'Line 1 \n \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']
Lastly, if you want to filter out the empty strings from the resulting list, you could use filter()
:
>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']
>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']
As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function
You need to distinguish between two separate concepts: function definition and symbol declaration. "extern" is a linkage modifier, a hint to the compiler about where the symbol referred to afterwards is defined (the hint is, "not here").
If I write
extern int i;
in file scope (outside a function block) in a C file, then you're saying "the variable may be defined elsewhere".
extern int f() {return 0;}
is both a declaration of the function f and a definition of the function f. The definition in this case over-rides the extern.
extern int f();
int f() {return 0;}
is first a declaration, followed by the definition.
Use of extern
is wrong if you want to declare and simultaneously define a file scope variable. For example,
extern int i = 4;
will give an error or warning, depending on the compiler.
Usage of extern
is useful if you explicitly want to avoid definition of a variable.
Let me explain:
Let's say the file a.c contains:
#include "a.h"
int i = 2;
int f() { i++; return i;}
The file a.h includes:
extern int i;
int f(void);
and the file b.c contains:
#include <stdio.h>
#include "a.h"
int main(void){
printf("%d\n", f());
return 0;
}
The extern in the header is useful, because it tells the compiler during the link phase, "this is a declaration, and not a definition". If I remove the line in a.c which defines i, allocates space for it and assigns a value to it, the program should fail to compile with an undefined reference. This tells the developer that he has referred to a variable, but hasn't yet defined it. If on the other hand, I omit the "extern" keyword, and remove the int i = 2
line, the program still compiles - i will be defined with a default value of 0.
File scope variables are implicitly defined with a default value of 0 or NULL if you do not explicitly assign a value to them - unlike block-scope variables that you declare at the top of a function. The extern keyword avoids this implicit definition, and thus helps avoid mistakes.
For functions, in function declarations, the keyword is indeed redundant. Function declarations do not have an implicit definition.
Sure you can.
ALTER TABLE myTable ALTER COLUMN myColumn int NULL
Just substitute int for whatever datatype your column is.
regex to the rescue
/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test('01234567-9ABC-DEF0-1234-56789ABCDEF0');
or with brackets
/^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}??\}?$/
Here is an example
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)
plt.scatter(x, y, c=t)
plt.show()
Here you are setting the color based on the index, t
, which is just an array of [1, 2, ..., 100]
.
Perhaps an easier-to-understand example is the slightly simpler
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()
Note that the array you pass as c
doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c
correspond to the bottom/top of the colormap.
You can change the colormap by adding
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)
Importing matplotlib.cm
is optional as you can call colormaps as cmap="cmap_name"
just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r
. So either
plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")
will work. Examples are "jet_r"
or cm.plasma_r
. Here's an example with the new 1.5 colormap viridis:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()
You can add a colorbar by using
plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()
Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots()
or ax = fig.add_subplot(111)
), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.
Just to show progress bar, "onPageStarted" and "onPageFinished" methods are enough; but if you want to have an "is_loading" flag (along with page redirects, ...), this methods may executed with non-sequencing, like "onPageStarted > onPageStarted > onPageFinished > onPageFinished" queue.
But with my short test (test it yourself.), "onProgressChanged" method values queue is "0-100 > 0-100 > 0-100 > ..."
private boolean is_loading = false;
webView.setWebChromeClient(new MyWebChromeClient(context));
private final class MyWebChromeClient extends WebChromeClient{
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 0){
is_loading = true;
} else if (newProgress == 100){
is_loading = false;
}
super.onProgressChanged(view, newProgress);
}
}
Also set "is_loading = false
" on activity close, if it is a static variable because activity can be finished before page finish.
The docs for java.io.Serializable
are probably about as good an explanation as you'll get:
The serialization runtime associates with each serializable class a version number, called a
serialVersionUID
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a differentserialVersionUID
than that of the corresponding sender's class, then deserialization will result in anInvalidClassException
. A serializable class can declare its ownserialVersionUID
explicitly by declaring a field namedserialVersionUID
that must be static, final, and of typelong
:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a
serialVersionUID
, then the serialization runtime will calculate a defaultserialVersionUID
value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declareserialVersionUID
values, since the defaultserialVersionUID
computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpectedInvalidClassExceptions
during deserialization. Therefore, to guarantee a consistentserialVersionUID
value across different java compiler implementations, a serializable class must declare an explicitserialVersionUID
value. It is also strongly advised that explicitserialVersionUID
declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class —serialVersionUID
fields are not useful as inherited members.
I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:
min-height: 60rem
) and thus can become too tall for its contentCondition 1 helps me understand what content
means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content
. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.
Condition 2 helps me visualize the effects of align-items
: it aligns items relative to each other.
Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)
<div class="flex-container">
<div class="item">Short</div>
<div class="item">Longerrrrrrrrrrrrrr</div>
<div class="item"></div>
<div class="item" id="tall">This is Many Words</div>
<div class="item">Lorem, ipsum.</div>
<div class="item">10</div>
<div class="item">Snickers</div>
<div class="item">Wes Is Cool</div>
<div class="item">Short</div>
</div>
.flex-container {
display: flex;
/*dictates a min-height*/
min-height: 60rem;
flex-flow: row wrap;
border: 5px solid white;
justify-content: center;
align-items: center;
align-content: flex-start;
}
#tall {
/*intentionally made tall*/
min-height: 30rem;
}
.item {
margin: 10px;
max-height: 10rem;
}
Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start;
has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)
Also, note the 2nd row--see how the items are center aligned among themselves.
Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;
--it aligns the content relative to the top edge of the container.
These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
I had the exact same problem, unfortunately, adding the primary key doesn't solve the issue. So here's how I solve mine:
primary key
on the table so I alter my table and add a primary key.Delete the ADO.NET Entity Data Model
(edmx file) where I use to map and connect with my database.Add again a new file of ADO.NET Entity Data Model
to connect with my database and for mapping my model properties.Clean and rebuild the solution.
Problem solved.
When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1)
return [0.0, 1.1]
or [0.0, 1.1, 2.199999999]
? There's no way to be certain without rigorous analysis.
The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.
This might be a late answer but this is the best around: https://github.com/eKoopmans/html2pdf
Pure javascript implementation. Allows you to specify just a single element by ID and convert it.
You can loop over each row of the DataTable
and check the value.
I'm a big fan of using a foreach loop when using IEnumerable
s. Makes it very simple and clean to look at or process each row
DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
if (dr["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
}
Alternatively you can use a PrimaryKey
for your DataTable
. This helps in various ways, but you often need to define one before you can use it.
An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx
DataTable workTable = new DataTable("Customers");
// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };
Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.
Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx
DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
// do your deed
}
Finally, you can use the Select() method to find data within a DataTable
also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.
String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);
foreach (DataRow dr in drFound)
{
// do you deed. Each record here was already found to match your criteria
}
For Java 8 the following method works:
Refer, below code snippet
String fileURiString="file:///D:/etc/MySQL.txt";
URI fileURI=new URI(fileURiString);
File file=new File(fileURI);//File file=new File(fileURiString) - will generate exception
FileInputStream fis=new FileInputStream(file);
fis.close();
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
The case
statement operator is like switch
in the other languages.
This is the syntax of switch...case
in C:
switch (expression)
?{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
This is the syntax of case...when
in Ruby:
case expression
when constant1, constant2 #Each when statement can have multiple candidate values, separated by commas.
# statements
next # is like continue in other languages
when constant3
# statements
exit # exit is like break in other languages
.
.
.
else
# statements
end
For example:
x = 10
case x
when 1,2,3
puts "1, 2, or 3"
exit
when 10
puts "10" # it will stop here and execute that line
exit # then it'll exit
else
puts "Some other number"
end
For more information see the case
documentation.
There are many ways for doing that (you might want to obfuscate the source code, you can compress it, ...). Some of these methods need additional code to transform your program in an executable form (compression, for example).
But the thing all methods cannot do, is keeping the source code secret. The other party gets your binary code, which can always be transformed (reverse-engineered) into a human-readable form again, because the binary code contains all functionality information that is provided in your source code.
A dependency has to be available from the registry
to be installed just by specifying a version
descriptor.
You can certainly create and use your own registry instead of registry.npmjs.org
if your projects shouldn't be shared publicly.
But, if it's not in a registry, it'll have to be referenced by URL or Git URL. To specify a version with a Git URL, include an appropriate <commit-ish>
, such as a tag, at the end as a URL fragment.
Example, for a tag named 0.3.1
:
"dependencies": {
"myprivatemodule": "[email protected]:...#0.3.1"
}
Note: The above snippet shows the base URL the same as it was posted in the question.
The snipped portion (
...
) should be filled in:"myprivatemodule": "[email protected]:{owner}/{project}.git#0.3.1"
And, a different address format will be needed when SSH access isn't available:
"myprivatemodule": "git://github.com/{owner}/{project}.git#0.3.1"
Depending on your OS, you may also be able to link
to the dependency in another folder where you have it cloned from Github.
A HashSet uses a HashMap internally to store its entries. Each entry in the internal HashMap is keyed by a single Object, so all entries hash into the same bucket. I don't recall what the internal HashMap uses to store its values, but it doesn't really matter since that internal container will never contain duplicate values.
EDIT: To address Matthew's comment, he's right; I had it backwards. The internal HashMap is keyed with the Objects that make up the Set elements. The values of the HashMap are an Object that's just simply stored in the HashMap buckets.
You could try this
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)
-or-
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row " & MATCH(<single column I value>,<entire column E range>,0))
you could replace <single column I value>
and <entire column E range>
with named ranged. That'd probably be the easiest.
Just drag that formula all the way down the length of your I column in whatever column you want.
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println("okay1");
FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
System.out.println("okay2");
if (fileInputStream != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
engine.eval(reader);
System.out.println("okay3");
// Invocable javascriptEngine = null;
System.out.println("okay4");
Invocable invocableEngine = (Invocable)engine;
System.out.println("okay5");
int x=0;
System.out.println("invocableEngine is : "+invocableEngine);
Object object = invocableEngine.invokeFunction("backend_message",x);
System.out.println("okay6");
}
}catch(Exception e) {
System.out.println("erroe when calling js function"+ e);
}
If your using Node.js or writing JavaScript with browserify, consider the "once" npm module:
var once = require('once')
function load (file, cb) {
cb = once(cb)
loader.load('file')
loader.once('load', cb)
loader.once('error', cb)
}
shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.
I think you can use date()
function to achive this
$date = '19:24:15 06/13/2013';
echo date('h:i:s a m/d/Y', strtotime($date));
This will output
07:24:15 pm 06/13/2013
h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)
Updated
This is with DateTime
$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;
UPDATE: In iPhone OS 3.0 and later UITableViewCell
now has a backgroundColor
property that makes this really easy (especially in combination with the [UIColor colorWithPatternImage:]
initializer). But I'll leave the 2.0 version of the answer here for anyone that needs it…
It's harder than it really should be. Here's how I did this when I had to do it:
You need to set the UITableViewCell's backgroundView property to a custom UIView that draws the border and background itself in the appropriate colors. This view needs to be able to draw the borders in 4 different modes, rounded on the top for the first cell in a section, rounded on the bottom for the last cell in a section, no rounded corners for cells in the middle of a section, and rounded on all 4 corners for sections that contain one cell.
Unfortunately I couldn't figure out how to have this mode set automatically, so I had to set it in the UITableViewDataSource's -cellForRowAtIndexPath method.
It's a real PITA but I've confirmed with Apple engineers that this is currently the only way.
Update Here's the code for that custom bg view. There's a drawing bug that makes the rounded corners look a little funny, but we moved to a different design and scrapped the custom backgrounds before I had a chance to fix it. Still this will probably be very helpful for you:
//
// CustomCellBackgroundView.h
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum {
CustomCellBackgroundViewPositionTop,
CustomCellBackgroundViewPositionMiddle,
CustomCellBackgroundViewPositionBottom,
CustomCellBackgroundViewPositionSingle
} CustomCellBackgroundViewPosition;
@interface CustomCellBackgroundView : UIView {
UIColor *borderColor;
UIColor *fillColor;
CustomCellBackgroundViewPosition position;
}
@property(nonatomic, retain) UIColor *borderColor, *fillColor;
@property(nonatomic) CustomCellBackgroundViewPosition position;
@end
//
// CustomCellBackgroundView.m
//
// Created by Mike Akers on 11/21/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "CustomCellBackgroundView.h"
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight);
@implementation CustomCellBackgroundView
@synthesize borderColor, fillColor, position;
- (BOOL) isOpaque {
return NO;
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(c, [fillColor CGColor]);
CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
if (position == CustomCellBackgroundViewPositionTop) {
CGContextFillRect(c, CGRectMake(0.0f, rect.size.height - 10.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, rect.size.height - 10.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height - 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height - 10.0f));
} else if (position == CustomCellBackgroundViewPositionBottom) {
CGContextFillRect(c, CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f));
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 10.0f);
CGContextAddLineToPoint(c, 0.0f, 0.0f);
CGContextStrokePath(c);
CGContextBeginPath(c);
CGContextMoveToPoint(c, rect.size.width, 0.0f);
CGContextAddLineToPoint(c, rect.size.width, 10.0f);
CGContextStrokePath(c);
CGContextClipToRect(c, CGRectMake(0.0f, 10.0f, rect.size.width, rect.size.height));
} else if (position == CustomCellBackgroundViewPositionMiddle) {
CGContextFillRect(c, rect);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 0.0f, 0.0f);
CGContextAddLineToPoint(c, 0.0f, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, rect.size.height);
CGContextAddLineToPoint(c, rect.size.width, 0.0f);
CGContextStrokePath(c);
return; // no need to bother drawing rounded corners, so we return
}
// At this point the clip rect is set to only draw the appropriate
// corners, so we fill and stroke a rounded rect taking the entire rect
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextFillPath(c);
CGContextSetLineWidth(c, 1);
CGContextBeginPath(c);
addRoundedRectToPath(c, rect, 10.0f, 10.0f);
CGContextStrokePath(c);
}
- (void)dealloc {
[borderColor release];
[fillColor release];
[super dealloc];
}
@end
static void addRoundedRectToPath(CGContextRef context, CGRect rect,
float ovalWidth,float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0) {// 1
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);// 2
CGContextTranslateCTM (context, CGRectGetMinX(rect),// 3
CGRectGetMinY(rect));
CGContextScaleCTM (context, ovalWidth, ovalHeight);// 4
fw = CGRectGetWidth (rect) / ovalWidth;// 5
fh = CGRectGetHeight (rect) / ovalHeight;// 6
CGContextMoveToPoint(context, fw, fh/2); // 7
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);// 8
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);// 9
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);// 10
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // 11
CGContextClosePath(context);// 12
CGContextRestoreGState(context);// 13
}
urllib2 does not verify server certificate by default. Check this documentation.
Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER
Thanks to Neevek his answer worked for me but it doesn't lock the vertical scrolling when user has started scrolling the horizontal view(ViewPager) in horizontal direction and then without lifting the finger scroll vertically it starts to scroll the underlying container view(ScrollView). I fixed it by making a slight change in Neevak's code:
private float xDistance, yDistance, lastX, lastY;
int lastEvent=-1;
boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDistance = yDistance = 0f;
lastX = ev.getX();
lastY = ev.getY();
break;
case MotionEvent.ACTION_MOVE:
final float curX = ev.getX();
final float curY = ev.getY();
xDistance += Math.abs(curX - lastX);
yDistance += Math.abs(curY - lastY);
lastX = curX;
lastY = curY;
if(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
return false;
}
if(xDistance > yDistance )
{
isLastEventIntercepted=true;
lastEvent = MotionEvent.ACTION_MOVE;
return false;
}
}
lastEvent=ev.getAction();
isLastEventIntercepted=false;
return super.onInterceptTouchEvent(ev);
}
In my case setting AppPool->AdvancedSettings->Maximum Worker Proccesses to 1 helped.
Also make sure the div is currently appended to the DOM and visible.
Well, getting full path is not possible but we can have a temporary path.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
The same situation occurred when I was using VSCode with eslint. If you use VSCode,
1 - Click area that name can be both LF or CRLF where at the bottom right of the VScode.
2 - Select LF from the drop-down menu.
That's worked for me.
There is a simple example of convert enumeration to list. for this i used Collections.list(enum)
method.
public class EnumerationToList {
public static void main(String[] args) {
Vector<String> vt = new Vector<String>();
vt.add("java");
vt.add("php");
vt.add("array");
vt.add("string");
vt.add("c");
Enumeration<String> enm = vt.elements();
List<String> ll = Collections.list(enm);
System.out.println("List elements: " + ll);
}
}
Reference : How to convert enumeration to list
I used the solution @Alex Martelli suggests, but it fails
TypeError 'bool' object does not support item assignment
when the two dictionaries differ in data type at some level.
In case at the same level the element of dictionary d
is just a scalar (ie. Bool
) while the element of dictionary u
is still dictionary the reassignment fails as no dictionary assignment is possible into scalar (like True[k]
).
One added condition fixes that:
from collections import Mapping
def update_deep(d, u):
for k, v in u.items():
# this condition handles the problem
if not isinstance(d, Mapping):
d = u
elif isinstance(v, Mapping):
r = update_deep(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
In postgres 12 I needed to use this command:
UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;
Try to remove /usr/local/lib/node_modules/npm
and reinstall node again. This should work.
sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node
well it's used to tell bootstrap how many columns are to be placed in a row depending on the screen size-
col-xs-2
would show only 2 columns in a row in extra small(xs) screen, in the same way as sm defines a small screen, md(medium sized), lg(large sized), but according to bootstrap smaller first rule, if you mention
xs-col-2 md-col-4
then 2 columns would be shown in every row for screen sizes from xs upto sm(included) and changes when it gets next size i.e. for md up to lg(included) for a better understanding of screen sizes try running them in various screen modes in chrome's developer mode(ctr+shift+i) and try various pixels or devices
one liner, without opening ~/.zshrc
file
echo -n 'export PATH=~/bin:$PATH' >> ~/.zshrc
or
echo -n 'export PATH=$HOME/bin:$PATH' >> ~/.zshrc
To see the effect, do source ~/.zshrc
in the same tab or open a new tab
Shortcut to Navigation Bar is Ctrl+F2. Takes you to the types dropdown first. Press tab to go to method dropdown, and then enter on a method to go to that one.
This is the working code for your question.
Enjoy Coding....
<html>
<head>
<style>
.animated {
background-color: green;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;animation-duration: 10s;
-webkit-animation-fill-mode: both;animation-fill-mode: both;
}
@-webkit-keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
@keyframes fadeOut {
0% {opacity: 1;}
100% {opacity: 0;}
}
.fadeOut {
-webkit-animation-name: fadeOut;
animation-name: fadeOut;
}
</style>
</head>
<body>
<div id="animated-example" class="animated fadeOut"></div>
</body>
</html>
A really simple way to achieve this would be:
//instance variable
List<View>itemViewList = new ArrayList<>();
//OnCreateViewHolderMethod
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
final MyViewHolder myViewHolder = new MyViewHolder(itemView);
itemViewList.add(itemView); //to add all the 'list row item' views
//Set on click listener for each item view
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for(View tempItemView : itemViewList) {
/** navigate through all the itemViews and change color
of selected view to colorSelected and rest of the views to colorDefault **/
if(itemViewList.get(myViewHolder.getAdapterPosition()) == tempItemView) {
tempItemView.setBackgroundResource(R.color.colorSelected);
}
else{
tempItemView.setBackgroundResource(R.color.colorDefault);
}
}
}
});
return myViewHolder;
}
UPDATE
The method above may ruin some default attributes of the itemView, in my case, i was using CardView, and the corner radius of the card was getting removed on click.
Better solution:
//instance variable
List<CardView>cardViewList = new ArrayList<>();
public class MyViewHolder extends RecyclerView.ViewHolder {
CardView cardView; //THIS IS MY ROOT VIEW
...
public MyViewHolder(View view) {
super(view);
cardView = view.findViewById(R.id.row_item_card);
...
}
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final OurLocationObject locationObject = locationsList.get(position);
...
cardViewList.add(holder.cardView); //add all the cards to this list
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//All card color is set to colorDefault
for(CardView cardView : cardViewList){
cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorDefault));
}
//The selected card is set to colorSelected
holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorSelected));
}
});
}
UPDATE 2 - IMPORTANT
onBindViewHolder method is called multiple times, and also every time the user scrolls the view out of sight and back in sight! This will cause the same view to be added to the list multiple times which may cause problems and minor delay in code executions!
To fix this, change
cardViewList.add(holder.cardView);
to
if (!cardViewList.contains(holder.cardView)) {
cardViewList.add(holder.cardView);
}
If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//Raise the Volume Bar on the Screen
volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
+ AudioManager.ADJUST_RAISE);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
//Adjust the Volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//Lower the VOlume Bar on the Screen
volumeControl.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)
+ AudioManager.ADJUST_LOWER);
return true;
default:
return false;
}
var myVar = null;
if(myVar)
clearTimeout(myVar);
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column):
Pandas has a built in replace
method available on a dataframe object.
df.replace(',', '-', regex=True)
Source: Docs
add your default theme this line;
<item name="colorControlNormal">@color/my_color</item>
If you have MVC project with enabled views build, one of the solution is to delete obj folder before build. Add to project file:
<Target Name="BeforeBuild">
<!-- Remove obj folder -->
<RemoveDir Directories="$(BaseIntermediateOutputPath)" />
<!-- Remove bin folder -->
<RemoveDir Directories="$(BaseOutputPath)" />
</Target>
Here is article: How to remove bin and/or obj folder before the build or deploy
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...
echo f | xcopy /f /y srcfile destfile
or for those of us just copying large substructures/folders:
use /i which specifies destination must be a directory if copying more than one file
Yes dear,then you have to use Ajax technology. to changes contents of particular html tag:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Ajax Page</title>
<script>
setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds.
function autoloadpage() {
$.ajax({
url: "URL of the destination page",
type: "POST",
success: function(data) {
$("div#wrapper").html(data); // here the wrapper is main div
}
});
}
</script>
</head>
<body>
<div id="wrapper">
contents will be changed automatically.
</div>
</body>
</html>
- (void)viewDidLoad
{
[self.tableView setSeparatorColor:[UIColor myColor]];
}
I hope that helps - you'll need the self.
to access it, remember.
Swift 4.2
tableView.separatorColor = UIColor.red
If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.
First, the official document does NOT guarantee that the GetHashCode()
returns an unique identifier (see Object.GetHashCode Method ()):
You should not assume that equal hash codes imply object equality.
Second, assume you have a very small amount of objects so that GetHashCode()
will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode()
to always return 0. Then every object of C will get the same hash code.
Unfortunately, Dictionary
, HashTable
and some other associative containers will make use this method:
A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.
So, this approach has great limitations.
And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.
I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;
namespace ObjectSet
{
public interface IObjectSet
{
/// <summary> check the existence of an object. </summary>
/// <returns> true if object is exist, false otherwise. </returns>
bool IsExist(object obj);
/// <summary> if the object is not in the set, add it in. else do nothing. </summary>
/// <returns> true if successfully added, false otherwise. </returns>
bool Add(object obj);
}
public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
{
/// <summary> unit test on object set. </summary>
internal static void Main() {
Stopwatch sw = new Stopwatch();
sw.Start();
ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
for (int i = 0; i < 10000000; ++i) {
object obj = new object();
if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
public bool IsExist(object obj) {
return objectSet.TryGetValue(obj, out tryGetValue_out0);
}
public bool Add(object obj) {
if (IsExist(obj)) {
return false;
} else {
objectSet.Add(obj, null);
return true;
}
}
/// <summary> internal representation of the set. (only use the key) </summary>
private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();
/// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
private static object tryGetValue_out0 = null;
}
[Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
{
/// <summary> unit test on object set. </summary>
internal static void Main() {
Stopwatch sw = new Stopwatch();
sw.Start();
ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
for (int i = 0; i < 10000000; ++i) {
object obj = new object();
if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
public bool IsExist(object obj) {
bool firstTime;
idGenerator.HasId(obj, out firstTime);
return !firstTime;
}
public bool Add(object obj) {
bool firstTime;
idGenerator.GetId(obj, out firstTime);
return firstTime;
}
/// <summary> internal representation of the set. </summary>
private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
}
}
In my test, the ObjectIDGenerator
will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for
loop.
Also, the benchmark result is that the ConditionalWeakTable
implementation is 1.8x faster than the ObjectIDGenerator
implementation.
Use a lambda function.
Let's say you have an array:
nums = [0,1,5]
Check whether 5 is in nums
in Python 3.X:
(len(list(filter (lambda x : x == 5, nums))) > 0)
Check whether 5 is in nums
in Python 2.7:
(len(filter (lambda x : x == 5, nums)) > 0)
This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums
.
For example, check whether any number that is greater than or equal to 5 exists in nums
:
(len(filter (lambda x : x >= 5, nums)) > 0)
This Code May be Help you : [ Both maximizing and preventing resizing on a JFrame ]
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setResizable(false);
use this attribute in style
font-size: 11px !important;//your font size
by !important it override your css
Suppose there are 3 non-negative integers: a
, b
, and c
. Mathematically speaking, if we want to determine if c
is between a
and b
, inclusively, one can use this formula:
(c - a) * (b - c) >= 0
or in Python:
> print((c - a) * (b - c) >= 0)
True
In ASP.NET Core Razor Pages, you can combine C# and HTML in the function:
@model PagerModel
@{
}
@functions
{
void PagerNumber(int pageNumber, int currentPage)
{
if (pageNumber == currentPage)
{
<span class="page-number-current">@pageNumber</span>
}
else
{
<a class="page-number-other" href="/table/@pageNumber">@pageNumber</a>
}
}
}
<p>@PagerNumber(1,2) @PagerNumber(2,2) @PagerNumber(3,2)</p>
Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being
gradle :<subproject>:dependencies
so for me this was
gradle :master:dependencies
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {
Word of caution when coding with Visual Studio (2013)
I have wasted 4 to 5 hours trying to debug this error. I tried all the solutions that I found on StackOverflow by the letter and I still got this error: Can't bind to 'routerlink' since it isn't a known native property
Be aware, Visual Studio has the nasty habit of autoformatting text when you copy/paste code. I always got a small instantaneous adjustment from VS13 (camel case disappears).
This:
<div>
<a [routerLink]="['/catalog']">Catalog</a>
<a [routerLink]="['/summary']">Summary</a>
</div>
Becomes:
<div>
<a [routerlink]="['/catalog']">Catalog</a>
<a [routerlink]="['/summary']">Summary</a>
</div>
It's a small difference, but enough to trigger the error. The ugliest part is that this small difference just kept avoiding my attention every time I copied and pasted. By sheer chance, I saw this small difference and solved it.
String.Format also works in Razor:
String.Format("{0} - {1}", Model.address, Model.city)
Try the following code. It works on all platforms.
var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';
break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'
break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'
I think there is a very simple solution:
public boolean isPositive(int|float|double|long i){
return (((i-i)==0)? true : false);
}
tell me if I'm wrong!
I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.
Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.
You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.
Looks like PILlow may have changed tostring()
to tobytes()
. When trying to extract RGBA pixels to get them into an OpenGL texture, the following worked for me (within the glTexImage2D
call which I omit for brevity).
from PIL import Image
img = Image.open("mandrill.png").rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
# use img.convert("RGBA").tobytes() as texels
You can use the runOnUiThread()
method as follows. If you're not using a ListActivity
, just adapt the code to get a reference to your ArrayAdapter
.
final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.
However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.
The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:
ALTER USER xyz_user ACCOUNT UNLOCK;
However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:
ALTER USER xyz_user IDENTIFIED BY new_password;
Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.
EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.
REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY
REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE
REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'
REM Show the status of the account before reset.
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""
REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD
REM Select the old spare4 and password columns as delimited strings
SELECT
'''' || SPARE4 || '''' AS SPARE4HASH,
'''' || PASSWORD || '''' AS PWORDHASH
FROM
SYS.USER$
WHERE
NAME = '&USER_NAME';
REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD
REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older)
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;
REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer)
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;
REM Show the status of the account after reset
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
No internal means, AFAIK. Use this: memset(c, 0, length);
Thread
is a lower-level concept: if you're directly starting a thread, you know it will be a separate thread, rather than executing on the thread pool etc.
Task
is more than just an abstraction of "where to run some code" though - it's really just "the promise of a result in the future". So as some different examples:
Task.Delay
doesn't need any actual CPU time; it's just like setting a timer to go off in the futureWebClient.DownloadStringTaskAsync
won't take much CPU time locally; it's representing a result which is likely to spend most of its time in network latency or remote work (at the web server)Task.Run()
really is saying "I want you to execute this code separately"; the exact thread on which that code executes depends on a number of factors.Note that the Task<T>
abstraction is pivotal to the async support in C# 5.
In general, I'd recommend that you use the higher level abstraction wherever you can: in modern C# code you should rarely need to explicitly start your own thread.
To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:
selectFile(event) {
event.preventDefault();
file_input = document.createElement('input');
file_input.addEventListener("change", uploadFile, false);
file_input.type = 'file';
file_input.click();
},
uploadFile() {
let dataArray = new FormData();
dataArray.append('file', file_input.files[0]);
// Obviously, you can substitute with JQuery or whatever
axios.post('/your_super_special_url', dataArray).then(function() {
//
});
}
It is possible to explode a string in a MySQL SELECT statement.
Firstly generate a series of numbers up to the largest number of delimited values you wish to explode. Either from a table of integers, or by unioning numbers together. The following generates 100 rows giving the values 1 to 100. It can easily be expanded to give larger ranges (add another sub query giving the values 0 to 9 for hundreds - hence giving 0 to 999, etc).
SELECT 1 + units.i + tens.i * 10 AS aNum
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
This can be cross joined against your table to give you the values. Note that you use SUBSTRING_INDEX to get the delimited value up to a certain value, and then use SUBSTRING_INDEX to get that value, excluding previous ones.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name
FROM clients
CROSS JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
As you can see there is a slight issue here that the last delimited value is repeated many times. To get rid of this you need to limit the range of numbers based on how many delimiters there are. This can be done by taking the length of the delimited field and comparing it to the length of the delimited field with the delimiters changed to '' (to remove them). From this you can get the number of delimiters:-
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name
FROM clients
INNER JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(clients.courseNames) - LENGTH(REPLACE(clients.courseNames, ',', ''))) >= sub0.aNum
In the original example field you could (for example) count the number of students on each course based on this. Note that I have changed the sub query that gets the range of numbers to bring back 2 numbers, 1 is used to determine the course name (as these are based on starting at 1) and the other gets the subscript (as they are based starting at 0).
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name, COUNT(clientenrols.studentId)
FROM clients
INNER JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(clients.courseNames) - LENGTH(REPLACE(clients.courseNames, ',', ''))) >= sub0.aNum
LEFT OUTER JOIN clientenrols
ON clientenrols.courseId = sub0.aSubscript
GROUP BY a_course_name
As you can see, it is possible but quite messy. And with little opportunity to use indexes it is not going to be efficient. Further the range must cope with the greatest number of delimited values, and works by excluding lots of duplicates; if the max number of delimited values is very large then this will slow things down dramatically. Overall it is generally far better to just properly normalise the database.
I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID
Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example
imagename:buildID
once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as
imagename:env:buildID
here evn:buildid is the azure devops variable which having value of build ID.
so now every time I have new changes to build(CI) and deploy(CD).
please comment if you need build definition for CI/CD.
Make this changes in php file
<html>
<head>
<meta charset="utf-8">
<title>Answer</title>
</head>
<body>
<p>The answer is:
<?php
$first = $_POST['first'];
$second= $_POST['second'];
if($_POST['group1'] == 'add') {
echo $first + $second;
}
else if($_POST['group1'] == 'subtract') {
echo $first - $second;
}
else if($_POST['group1'] == 'times') {
echo $first * $second;
}
else if($_POST['group1'] == 'divide') {
echo $first / $second;
}
else {
echo "Enter the numbers properly";
}
?>
</p>
</body>
</html>
SELECT COUNT(1)
FROM FB
WHERE
Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'
Taken from this page:
Here's a quick cheat sheet of the JPA world:
You can use the following:
/// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
//Log exception here
}
}
/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }
T objectOut = default(T);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
//Log exception here
}
return objectOut;
}
The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.
> levels(data$Fireplace.Qu)
[1] "Ex" "Fa" "Gd" "Po" "TA"
> levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
[1] "Ex" "Fa" "Gd" "Po" " TA" "None"
For extra themes, including making VS 2012 look like VS 2010 see:
http://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05
Deleting and Recreating a project with same name is tricky. If you try to follow above suggested steps and try to create a project with same name as the one you just deleted, you will run into error like
'C:/xxxxxx/pom.xml' already exists in VFS
Here is what I found would work.
Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip
to text
.
Create proper gradient:
background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);
Then clip the backgroud with text:
background-clip: text;
color: transparent;
https://jsfiddle.net/simonmysun/2h61Ljbn/4/
Tested under Chrome 75 under Windows 10.
All these answers address the title question, but I wanted to propose some solutions for the problems presented in the body of the OP's question.
A quick way to calculate the size of the text inside the UITextView
is to use the NSLayoutManager
:
UITextView *textView;
CGSize textSize = [textView usedRectForTextContainer:textView.textContainer].size;
This gives the total scrollable content, which may be bigger than the UITextView
's frame. I found this to be much more accurate than textView.contentSize
since it actually calculates how much space the text takes up. For example, given an empty UITextView
:
textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)
UIFont
has a property that quickly allows you to get the line height for the given font. So you can quickly find the line height of the text in your UITextView
with:
UITextView *textView;
CGFloat lineHeight = textView.font.lineHeight;
Determining the amount of text that is actually visible is important for handling a "paging" effect. UITextView
has a property called textContainerInset
which actually is a margin between the actual UITextView.frame
and the text itself. To calculate the real height of the visible frame you can perform the following calculations:
UITextView *textView;
CGFloat textViewHeight = textView.frame.size.height;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textHeight = textViewHeight - textInsets.top - textInsets.bottom;
Lastly, now that you have the visible text size and the content, you can quickly determine what your offsets should be by subtracting the textHeight
from the textSize
:
// where n is the page number you want
CGFloat pageOffsetY = textSize - textHeight * (n - 1);
textView.contentOffset = CGPointMake(textView.contentOffset.x, pageOffsetY);
// examples
CGFloat page1Offset = 0;
CGFloat page2Offset = textSize - textHeight
CGFloat page3Offset = textSize - textHeight * 2
Using all of these methods, I didn't touch my insets and I was able to go to the caret or wherever in the text that I want.
A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access).
The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.
Furthermore, with a SqlDataReader, you deal with your data one record at a time, and don't hold any data in memory. Obviously with a DataTable or DataSet, you do have a memory allocation overhead.
If you don't need to keep your data in memory, so for rendering stuff only, go for the SqlDataReader. If you want to deal with your data in a disconnected fashion choose the DataAdapter to fill either a DataSet or DataTable.
You have to Select Build Tool Version from your project setting.
This will work on my side i hope it will help you.
With Anaconda 4.5+ and Python 3.6+ on Windows use
Ctrl+Z
or
exit()
In some cases, you might have to use
Ctrl+Break
If your computer doesn't have Break
key then see here.
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
You can try something like this:
def details_to_json
{
:id => self.id,
:credit_period_type => self.credit_period_type,
:credit_payment_period => self.credit_payment_period,
}.to_json
end
Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx
There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803
SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:
SELECT CAST(N'±' as varbinary(10)) AS Result
This will return 0xB100
which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.
If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.
You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY
instead of VARCHAR
so the SQL Server transformation is not invalidated by the client before it is presented:
SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName
This will get you 0xF1
or 0xB1
respectively if columnName
contains just the character '±'
You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.
Please double check the actual internal representation of your character by casting the query to VARBINARY
on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2
SELECT CAST(columnName as varbinary(10)) from tableName
Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.
All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.
When you are on a project page, you can press the 'Download ZIP' button which is located under the "Clone or Download" drop down:
This allows you to download the most recent version of the code as a zip archive.
If you aren't seeing that button, it is likely because you aren't on the main project page. To get there, click on the left-most tab labeled "<> Code".
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
ExecuteScalar();
will work, but an output parameter would be a superior solution.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});
And listen it in parent:
function listenMessage(msg) {
alert(msg);
}
if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
Try this code:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
replace 'MyClass
' with your class containing the main method.
Alternatively you can also use
System.getProperty("java.class.path")
Above mentioned System property provides
Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
Please use below command to change heap size to 6GB
export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
Check this http://en.wikipedia.org/wiki/Web_service
As the link mentioned then Web API is a development in Web services that most likely relates to Web 2.0, whereas SOAP based services are replaced by REST based communications. Note that REST services do not require XML, SOAP, or WSDL service-API definitions so this is major different to traditional web service.
Similar as they are, merge!
and store
treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!
's key: "value"
syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.
hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash
{:key=>"value"}
hash = {}
hash.store(:key, "value")
hash.store("key", "value")
puts hash
{:key=>"value", "key"=>"value"}
To get the shovel operator <<
working, I would advise using Mark Thomas's answer.
I don't see why you are grouping here.
Try this:
var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);
An alternate approach that would iterate table
only once would be this:
var result = table.OrderByDescending(x => x.Status).First();
This is helpful if table
is an IEnumerable<T>
that is not present in memory or that is calculated on the fly.
Here's a javascript implementation that works with web-kit:
var isHovering = false;
var el = $(".elem").mouseover(function(){
isHovering = true;
spin();
}).mouseout(function(){
isHovering = false;
});
var spin = function(){
if(isHovering){
el.removeClass("spin");
setTimeout(function(){
el.addClass("spin");
setTimeout(spin, 1500);
}, 0);
}
};
spin();
JSFiddle: http://jsfiddle.net/4Vz63/161/
Barf.
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
Read SVNBook | Client Credentials.
With modern SVN you can just run svn auth
to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth
was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth
on Windows and ~/.subversion/auth/
on Unix-like systems.
PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user
Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials
The simplest way is to drop the whole database and create it once again:
drop database db_name
create database db_name
That's all.
I've always used the SimpleXML functions built in to PHP to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will detect XML warnings and errors, and upon finding any you could simply run the source through something like HTML Tidy (as ceejayoz mentioned) to clean it up and attempt it again.
Consider this very rough, simple class using SimpleXML:
class BlogPost
{
var $date;
var $ts;
var $link;
var $title;
var $text;
}
class BlogFeed
{
var $posts = array();
function __construct($file_or_url)
{
$file_or_url = $this->resolveFile($file_or_url);
if (!($x = simplexml_load_file($file_or_url)))
return;
foreach ($x->channel->item as $item)
{
$post = new BlogPost();
$post->date = (string) $item->pubDate;
$post->ts = strtotime($item->pubDate);
$post->link = (string) $item->link;
$post->title = (string) $item->title;
$post->text = (string) $item->description;
// Create summary as a shortened body and remove images,
// extraneous line breaks, etc.
$post->summary = $this->summarizeText($post->text);
$this->posts[] = $post;
}
}
private function resolveFile($file_or_url) {
if (!preg_match('|^https?:|', $file_or_url))
$feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
else
$feed_uri = $file_or_url;
return $feed_uri;
}
private function summarizeText($summary) {
$summary = strip_tags($summary);
// Truncate summary line to 100 characters
$max_len = 100;
if (strlen($summary) > $max_len)
$summary = substr($summary, 0, $max_len) . '...';
return $summary;
}
}
You can do that like this:
INSERT INTO myTable (colum1, column2)
SELECT column1, column2 FROM OtherTable;
Just make sure the columns are matching, both in number as in datatype.
Sometimes frameworks (like $resource/AngularJS) require an array as a query result, and you can't really have a response like {count:10,items:[...]}
in this case I store "count" in responseHeaders.
P. S. Actually you can do that with $resource/AngularJS, but it needs some tweaks.
You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:
<?php
$string = 'Cién cañones por banda';
echo mb_strlen($string, '8bit');
?>
You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php
For trim the string by byte length without split in middle of a multibyte character you can use:
mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )
Following the useful comments, I've completely rebuilt the date formatter. Usage is supposed to:
If you consider this code useful, I may publish the source and a JAR in github.
// The problem - not UTC
Date.toString()
"Tue Jul 03 14:54:24 IDT 2012"
// ISO format, now
PrettyDate.now()
"2012-07-03T11:54:24.256 UTC"
// ISO format, specific date
PrettyDate.toString(new Date())
"2012-07-03T11:54:24.256 UTC"
// Legacy format, specific date
PrettyDate.toLegacyString(new Date())
"Tue Jul 03 11:54:24 UTC 2012"
// ISO, specific date and time zone
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST")
"1969-07-20 03:17:40 CDT"
// Specific format and date
PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
"1969-07-20"
// ISO, specific date
PrettyDate.toString(moonLandingDate)
"1969-07-20T20:17:40.234 UTC"
// Legacy, specific date
PrettyDate.toLegacyString(moonLandingDate)
"Wed Jul 20 08:17:40 UTC 1969"
(This code is also the subject of a question on Code Review stackexchange)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Formats dates to sortable UTC strings in compliance with ISO-8601.
*
* @author Adam Matan <[email protected]>
* @see http://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string/11294308
*/
public class PrettyDate {
public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy";
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT);
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
static {
legacyFormatter.setTimeZone(utc);
isoFormatter.setTimeZone(utc);
}
/**
* Formats the current time in a sortable ISO-8601 UTC format.
*
* @return Current time in ISO-8601 format, e.g. :
* "2012-07-03T07:59:09.206 UTC"
*/
public static String now() {
return PrettyDate.toString(new Date());
}
/**
* Formats a given date in a sortable ISO-8601 UTC format.
*
* <pre>
* <code>
* final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
* moonLandingCalendar.set(1969, 7, 20, 20, 18, 0);
* final Date moonLandingDate = moonLandingCalendar.getTime();
* System.out.println("UTCDate.toString moon: " + PrettyDate.toString(moonLandingDate));
* >>> UTCDate.toString moon: 1969-08-20T20:18:00.209 UTC
* </code>
* </pre>
*
* @param date
* Valid Date object.
* @return The given date in ISO-8601 format.
*
*/
public static String toString(final Date date) {
return isoFormatter.format(date);
}
/**
* Formats a given date in the standard Java Date.toString(), using UTC
* instead of locale time zone.
*
* <pre>
* <code>
* System.out.println(UTCDate.toLegacyString(new Date()));
* >>> "Tue Jul 03 07:33:57 UTC 2012"
* </code>
* </pre>
*
* @param date
* Valid Date object.
* @return The given date in Legacy Date.toString() format, e.g.
* "Tue Jul 03 09:34:17 IDT 2012"
*/
public static String toLegacyString(final Date date) {
return legacyFormatter.format(date);
}
/**
* Formats a date in any given format at UTC.
*
* <pre>
* <code>
* final Calendar moonLandingCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
* moonLandingCalendar.set(1969, 7, 20, 20, 17, 40);
* final Date moonLandingDate = moonLandingCalendar.getTime();
* PrettyDate.toString(moonLandingDate, "yyyy-MM-dd")
* >>> "1969-08-20"
* </code>
* </pre>
*
*
* @param date
* Valid Date object.
* @param format
* String representation of the format, e.g. "yyyy-MM-dd"
* @return The given date formatted in the given format.
*/
public static String toString(final Date date, final String format) {
return toString(date, format, "UTC");
}
/**
* Formats a date at any given format String, at any given Timezone String.
*
*
* @param date
* Valid Date object
* @param format
* String representation of the format, e.g. "yyyy-MM-dd HH:mm"
* @param timezone
* String representation of the time zone, e.g. "CST"
* @return The formatted date in the given time zone.
*/
public static String toString(final Date date, final String format, final String timezone) {
final TimeZone tz = TimeZone.getTimeZone(timezone);
final SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.setTimeZone(tz);
return formatter.format(date);
}
}
Use following class directly to read word document
class DocxConversion{
private $filename;
public function __construct($filePath) {
$this->filename = $filePath;
}
private function read_doc() {
$fileHandle = fopen($this->filename, "r");
$line = @fread($fileHandle, filesize($this->filename));
$lines = explode(chr(0x0D),$line);
$outtext = "";
foreach($lines as $thisline)
{
$pos = strpos($thisline, chr(0x00));
if (($pos !== FALSE)||(strlen($thisline)==0))
{
} else {
$outtext .= $thisline." ";
}
}
$outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
return $outtext;
}
private function read_docx(){
$striped_content = '';
$content = '';
$zip = zip_open($this->filename);
if (!$zip || is_numeric($zip)) return false;
while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip, $zip_entry) == FALSE) continue;
if (zip_entry_name($zip_entry) != "word/document.xml") continue;
$content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
zip_entry_close($zip_entry);
}// end while
zip_close($zip);
$content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
$content = str_replace('</w:r></w:p>', "\r\n", $content);
$striped_content = strip_tags($content);
return $striped_content;
}
/************************excel sheet************************************/
function xlsx_to_text($input_file){
$xml_filename = "xl/sharedStrings.xml"; //content file name
$zip_handle = new ZipArchive;
$output_text = "";
if(true === $zip_handle->open($input_file)){
if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){
$xml_datas = $zip_handle->getFromIndex($xml_index);
$xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$output_text = strip_tags($xml_handle->saveXML());
}else{
$output_text .="";
}
$zip_handle->close();
}else{
$output_text .="";
}
return $output_text;
}
/*************************power point files*****************************/
function pptx_to_text($input_file){
$zip_handle = new ZipArchive;
$output_text = "";
if(true === $zip_handle->open($input_file)){
$slide_number = 1; //loop through slide files
while(($xml_index = $zip_handle->locateName("ppt/slides/slide".$slide_number.".xml")) !== false){
$xml_datas = $zip_handle->getFromIndex($xml_index);
$xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
$output_text .= strip_tags($xml_handle->saveXML());
$slide_number++;
}
if($slide_number == 1){
$output_text .="";
}
$zip_handle->close();
}else{
$output_text .="";
}
return $output_text;
}
public function convertToText() {
if(isset($this->filename) && !file_exists($this->filename)) {
return "File Not exists";
}
$fileArray = pathinfo($this->filename);
$file_ext = $fileArray['extension'];
if($file_ext == "doc" || $file_ext == "docx" || $file_ext == "xlsx" || $file_ext == "pptx")
{
if($file_ext == "doc") {
return $this->read_doc();
} elseif($file_ext == "docx") {
return $this->read_docx();
} elseif($file_ext == "xlsx") {
return $this->xlsx_to_text();
}elseif($file_ext == "pptx") {
return $this->pptx_to_text();
}
} else {
return "Invalid File Type";
}
}
}
$docObj = new DocxConversion("test.docx"); //replace your document name with correct extension doc or docx
echo $docText= $docObj->convertToText();
Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.
col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):
<div class="row">
<div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
<div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>
Choose
File > Switch Workspace> 'MyWorkSpace'
Eclipse restarts and if you are as lucky as me, the projects are mapped correctly.
In my case I have the developer environment on a shared server with about 10-15 users that may accidentally change things that affects other users.
Tip of the day: Don't do that...
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
Bullets take the color
property of the list:
.listStyle {
color: red;
}
Note if you want your list text to be a different colour, you have to wrap it in say, a p
, for example:
.listStyle p {
color: black;
}
<ul class="listStyle">
<li>
<p><strong>View :</strong> blah blah.</p>
</li>
<li>
<p><strong>View :</strong> blah blah.</p>
</li>
</ul>
if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
return true;
}
[function.fopen]: failed to open stream
If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :
allow_url_fopen = off
should bee this
allow_url_fopen = On
And add this line below it:
allow_url_include = off
should bee this
allow_url_include = on
mmap
has the advantage when you have random access on big files. Another advantage is that you access it with memory operations (memcpy, pointer arithmetic), without bothering with the buffering. Normal I/O can sometimes be quite difficult when using buffers when you have structures bigger than your buffer. The code to handle that is often difficult to get right, mmap is generally easier. This said, there are certain traps when working with mmap
.
As people have already mentioned, mmap
is quite costly to set up, so it is worth using only for a given size (varying from machine to machine).
For pure sequential accesses to the file, it is also not always the better solution, though an appropriate call to madvise
can mitigate the problem.
You have to be careful with alignment restrictions of your architecture(SPARC, itanium), with read/write IO the buffers are often properly aligned and do not trap when dereferencing a casted pointer.
You also have to be careful that you do not access outside of the map. It can easily happen if you use string functions on your map, and your file does not contain a \0 at the end. It will work most of the time when your file size is not a multiple of the page size as the last page is filled with 0 (the mapped area is always in the size of a multiple of your page size).
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl();
is toDataURL();
and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!
On iOS with Safari they expire whenever you switch apps!
On Android with Chrome they don't expire when you close the browser.
On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.
Two commands:
id
prints the user id along with the groups.
Format: uid=usernumber(username) ...
whoami
gives the current user name
I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp
line caused User Defined Type Not Defined
errors, but I found a solution that worked for me.
Update RE comments w/ @chrisneilsen :
I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp
library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.
Source: https://peltiertech.com/Excel/EarlyLateBinding.html
What you'll want to do is put an example string in cell A1
, then test your strPattern
. Once that's working adjust then rng
as desired.
Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
Dim regexp As Object
'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
Dim rng As Range, rcell As Range
Dim strInput As String, strPattern As String
Set regexp = CreateObject("vbscript.regexp")
Set rng = ActiveSheet.Range("A1:A1")
strPattern = "([a-z]{2})([0-9]{8})"
'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched
With regexp
.Global = False
.MultiLine = False
.ignoreCase = True
.Pattern = strPattern
End With
For Each rcell In rng.Cells
If strPattern <> "" Then
strInput = rcell.Value
If regexp.test(strInput) Then
MsgBox rcell & " Matched in Cell " & rcell.Address
Else
MsgBox "No Matches!"
End If
End If
Next
End Sub
if you have two divs, you can use this to align the divs next to each other in the same row:
#keyword {_x000D_
float:left;_x000D_
margin-left:250px;_x000D_
position:absolute;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
text-align:center;_x000D_
}
_x000D_
<div id="keyword">_x000D_
Keywords:_x000D_
</div>_x000D_
<div id="bar">_x000D_
<input type = textbox name ="keywords" value="" onSubmit="search()" maxlength=40>_x000D_
<input type = button name="go" Value="Go ahead and find" onClick="search()">_x000D_
</div>
_x000D_
I tweaked two previous answers to include multiple uploads. In this way the label shows the file name, if only one is selected, or x files
in the opposite case.
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(
(this.files.length > 1) ? this.files.length + ' files' : this.files[0].name)">
Files…
</label>
<span class='label label-info' id="upload-file-info"></span>
It may also apply to change the button text and class.
<label class="btn btn-primary" for="multfile">
<input id="multfile" type="file" multiple="multiple" style="display:none"
onchange="$('#multfile-label').html(
(this.files.length == 1) ? this.files[0].name : this.files.length + ' files');
$(this).parent().addClass('btn-success')">
<span id="multfile-label">Files…</span>
</label>
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
PageView::select('id','title', DB::raw('DATE(created_at) as date'))
->get()
->groupBy('date');
If one of the inserts fail, or any part of the command fails, does SQL server roll back the transaction?
No, it does not.
If it does not rollback, do I have to send a second command to roll it back?
Sure, you should issue ROLLBACK
instead of COMMIT
.
If you want to decide whether to commit or rollback the transaction, you should remove the COMMIT
sentence out of the statement, check the results of the inserts and then issue either COMMIT
or ROLLBACK
depending on the results of the check.
Enter this in the custom number format field:
[>=1000]#,##0,"K€";0"€"
What that means is that if the number is greater than 1,000, display at least one digit (indicated by the zero), but no digits after the thousands place, indicated by nothing coming after the comma. Then you follow the whole thing with the string "K".
Edited to add comma and euro.
use this concept this will help you, After that set the imagebitmap on image view
public static Bitmap convertBitmap(String path) {
Bitmap bitmap=null;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
File file=new File(path);
FileInputStream fs=null;
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
if(fs!=null)
{
bitmap=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}
If you want to make a small image from large image with height and width like 60 and 60 and scroll the listview fast then use this concept
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
I hope it will help you much.
You can take help from developer site Here
To push branches and tags (but not remotes):
git push origin 'refs/tags/*' 'refs/heads/*'
This would be equivalent to combining the --tags
and --all
options for git push
, which git does not seem to allow.
the same solution as Basit .. but the version 3.0 doesn't work for me try this .. it works for me to integrate struts 2.x
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>blabla</display-name>
...
</web-app>
We offer a tool called DocFlex/XML XSDDoc that allows you to enjoy both things at once:
The diagrams in fact are generated not by us, but by Altova XMLSpy. We implemented an Integration with XMLSpy (with the full support of all diagram hyperlinks):
Here you can see the full this doc: http://www.filigris.com/docflex-xml/xsddoc/examples/html/XMLSchema/index.html
The whole thing provides a functionality not offered by any single vendor right now on the market!
Some our customers were so impressed that they purchased an extra license for XMLSpy only because of our tool. (That's no joke!)
Currently, we've also implemented similar integrations with other XML editors:
See: http://www.filigris.com/docflex-xml/OxygenXML/demo/html/xslt20/index.html
See: http://www.filigris.com/docflex-xml/LiquidXML/demo/html/XMLSchema/index.html
Concerning what all those diagrams depict... Essentially, they are all about content model of XSD elements (as well as other XSD components that lead to elements: complexTypes, element/attribute groups). It seems, there are two approaches here:
I personally believe that the diagrams generated by XMLSpy are more useful.
Yet, there were no attempts so far (at least known to me) to depict graphically anything else contained in XML schemas, although one can imagine many...
Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:
select *
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc
For fullscreen of browser rendering area there is a simple solution supported by all modern browsers.
div#placeholder {
height: 100vh;
}
The only notable exception is the Android below 4.3 - but ofc only in the system browser/webview element (Chrome works ok).
Browser support chart: http://caniuse.com/viewport-units
For fullscreen of monitor please use HTML5 Fullscreen API
I come back to this answer fairly often, though none of these are quite right for me. That said, the right answer for me is a mixture of the others.
What I find works is the following:
git config --global core.eol lf
git config --global core.autocrlf input
For repos that were checked out after those global settings were set, everything will be checked out as whatever it is in the repo – hopefully LF
(\n
). Any CRLF
will be converted to just LF
on checkin.
With an existing repo that you have already checked out – that has the correct line endings in the repo but not your working copy – you can run the following commands to fix it:
git rm -rf --cached .
git reset --hard HEAD
This will delete (rm
) recursively (r
) without prompt (-f
), all files except those that you have edited (--cached
), from the current directory (.
). The reset
then returns all of those files to a state where they have their true line endings (matching what's in the repo).
If you need to fix the line endings of files in a repo, I recommend grabbing an editor that will let you do that in bulk like IntelliJ or Sublime Text, but I'm sure any good one will likely support this.