Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
_x000D_
If your float is always expressed in decimal notation something like
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']
may suffice.
A more robust version would be:
>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']
If you want to validate user input, you could alternatively also check for a float by stepping to it directly:
user_input = "Current Level: 1e100 db"
for token in user_input.split():
try:
# if this succeeds, you have your (first) float
print float(token), "is a float"
except ValueError:
print token, "is something else"
# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else
If you look at the output you receive from print()
and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b
):
b'{\n "note":"This file .....
If you fetch the URL using a tool such as curl -v
, you will see that the content type is
Content-Type: application/json; charset=utf-8
So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.
Change the last line of code to this:
info = json.loads(js.decode("utf-8"))
There is a similar problem.it is a tomcat digital signature.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows-
x64.zip
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key
but then I use the RSA key it provided to receive the public key to verify.
$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
Then successfully.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987 5A51 10C0 1C5A 2F60 59E7
Try swapping your colon :
for a bar |
. that should do it
<a href="file://C|/path/to/file/file.html">Link Anchor</a>
For Eclipse Mars the following worked
I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that exel cannot open the file bcz file might be coruupted or extension of the file is not compatible. but if i used .xls for file it work fines
for (int i = 0; i < TotalFile; i++)
{
Contact.Clear();
if (innerloop == SplitSize)
{
for (int j = 0; j < SplitSize; j++)
{
string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();
Contact.Add(strContact);
}
string strExcel = strFileName + "_" + i.ToString() + ".xlsx";
File.WriteAllLines(strExcel, Contact.ToArray());
}
}
also refer link
http://dotnet-magic.blogspot.in/2011/10/createformat-excel-file-from-cnet.html
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php
. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
Swift 3+ & Swift 4 version:
DispatchQueue.main.async {
print("Hello")
}
Swift 3 and Xcode 9.2:
dispatch_async_on_main_queue {
print("Hello")
}
I am trying to detect the chrome and safari browser using jquery or javascript.
Use jQuery.browser
I thought we are not supposed to use jQuery.browser.
That's because detecting browsers is a bad idea. It is still the best way to detect the browser (when jQuery is involved) if you really intend to do that.
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/"
for the "-"
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
From the asar documentation
(the use of npx
here is to avoid to install the asar
tool globally with npm install -g asar
)
npx asar extract app.asar destfolder
npx asar extract-file app.asar main.js
The other answers either present a manual string replacement, URLEncoder which actually encodes for HTML format, Apache's abandoned URIUtil, or using Guava's UrlEscapers. The last one is fine, except it doesn't provide a decoder.
Apache Commons Lang provides the URLCodec, which encodes and decodes according to URL format rfc3986.
String encoded = new URLCodec().encode(str);
String decoded = new URLCodec().decode(str);
If you are already using Spring, you can also opt to use its UriUtils class as well.
I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.
@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.
You can force an implicit conversion by using a string in an arithmetic operations as in a= "10" + 0
, but this is not quite as clear or as clean as using tonumber
explicitly.
I don't think this is OP's problem, but if you're like me, you ran into this error while you were trying to play around with git plumbing commands (update-index
& cat-file
) without ever actually committing anything in the first place. So try committing something (git commit -am 'First commit'
) and your problem should be solved.
Alternative approach if you want to add a class to an existing list of classes of an element:
element.Attributes["class"] += " myCssClass";
Cheap and cheerful answer:
<textarea>Some raw content</textarea>
The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim. It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box. You don't need any CSS, JS, escaping, encoding.
You can alter the appearance and behaviour as well. Here's a monospace font, editing disabled, smaller font, no border:
<textarea
style="width:100%; font-family: Monospace; font-size:10px; border:0;"
rows="30" disabled
>Some raw content</textarea>
This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.
I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
I agree that a zip file is a neater solution... But if you have to push multiple file, here's the solution I came up with. It works in IE 9 and up (possibly lower version too - I haven't tested it), Firefox, Safari and Chrome. Chrome will display a message to user to obtain his agreement to download multiple files the first time your site use it.
function deleteIframe (iframe) {
iframe.remove();
}
function createIFrame (fileURL) {
var iframe = $('<iframe style="display:none"></iframe>');
iframe[0].src= fileURL;
$('body').append(iframe);
timeout(deleteIframe, 60000, iframe);
}
// This function allows to pass parameters to the function in a timeout that are
// frozen and that works in IE9
function timeout(func, time) {
var args = [];
if (arguments.length >2) {
args = Array.prototype.slice.call(arguments, 2);
}
return setTimeout(function(){ return func.apply(null, args); }, time);
}
// IE will process only the first one if we put no delay
var wait = (isIE ? 1000 : 0);
for (var i = 0; i < files.length; i++) {
timeout(createIFrame, wait*i, files[i]);
}
The only side effect of this technique, is that user will see a delay between submit and the download dialog showing. To minimize this effect, I suggest you use the technique describe here and on this question Detect when browser receives file download that consist of setting a cookie with your file to know it has started download. You will have to check for this cookie on client side and to send it on server side. Don't forget to set the proper path for your cookie or you might not see it. You will also have to adapt the solution for multiple file download.
Here's one more solution:
for PUSH : -Add first element in queue 1. -When adding second element and so on, Enqueue the element in queue 2 first and then copy all the element from queue 1 to queue2. -for POP just dequeue the element from the queue from you inserted the last element.
So,
public void push(int data){
if (queue1.isEmpty()){
queue1.enqueue(data);
} else {
queue2.enqueue(data);
while(!queue1.isEmpty())
Queue2.enqueue(queue1.dequeue());
//EXCHANGE THE NAMES OF QUEUE 1 and QUEUE2
} }
public int pop(){
int popItem=queue2.dequeue();
return popItem;
}'
There is one problem, I am not able to figure out, how to rename the queues???
Just in case you were wondering how to rename columns during aggregation, here's how for
df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')
Or,
df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))
MySum MyCount
Company Name
Vifor Pharma UK Ltd 4207.93 5
One is a column (aka Series), while the other is a DataFrame:
In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2
1 3 4
The column 'b' (aka Series):
In [3]: df['b']
Out[3]:
0 2
1 4
Name: b, dtype: int64
The subdataframe with columns (position) in [1]:
In [4]: df[[1]]
Out[4]:
b
0 2
1 4
Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:
In [5]: df.iloc[:, [1]]
Out[5]:
b
0 2
1 4
In [6]: df.loc[:, ['b']]
Out[6]:
b
0 2
1 4
In [7]: df.loc[:, 'b']
Out[7]:
0 2
1 4
Name: b, dtype: int64
@property (nonatomic, copy) void (^simpleBlock)(void);
@property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);
If you are going to be repeating the same block in several places use a type def
typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
@property (nonatomic) MyCompletionBlock completion;
clean and simple ES6 (Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
The second parameter should ensure a default value if arrayToSearchIn
is empty.
If you want to keep with the Pandas syntex this worked for me.
df = df[df.dt_mvmt.isNotNull()]
Make sure that the string is in the following JSON format which is something like this:
{"result":"success","testid":"1"} (with " ") .
If not, then you can add "responsetype => json"
in your request params.
Then use json_decode($response,true)
to convert it into an array.
Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
Searched several houres before I found there were some linebreaks in the included files.
There is a way to perform the string search faster. Assumptions: since we are talking about a switch statement, I can assume that the values won't be changing during runtime.
The idea is to use the C stdlib's qsort and bsearch.
I'll be working on xtofl's code.
struct stringcase { char* string; void (*func)(void); };
void funcB1();
void funcAzA();
struct stringcase cases [] =
{ { "B1", funcB1 }
, { "AzA", funcAzA }
};
struct stringcase work_cases* = NULL;
int work_cases_cnt = 0;
// prepare the data for searching
void prepare() {
// allocate the work_cases and copy cases values from it to work_cases
qsort( cases, i, sizeof( struct stringcase ), stringcase_cmp );
}
// comparator function
int stringcase_cmp( const void *p1, const void *p2 )
{
return strcasecmp( ((struct stringcase*)p1)->string, ((struct stringcase*)p2)->string);
}
// perform the switching
void myswitch( char* token ) {
struct stringcase val;
val.string=token;
void* strptr = bsearch( &val, work_cases, work_cases_cnt, sizeof( struct stringcase), stringcase_cmp );
if (strptr) {
struct stringcase* foundVal = (struct stringcase*)strptr;
(*foundVal->func)();
return OK;
}
return NOT_FOUND;
}
Just add below line in application.properties
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false
You can use inline css :
<td style = "text-align: center;">
In case the tables are in a different databases. (MSSQL)
update database1..Ciudad
set CiudadDistrito=c2.CiudadDistrito
FROM database1..Ciudad c1
inner join
database2..Ciudad c2 on c2.CiudadID=c1.CiudadID
"crypto/rand" is cross platform pkg for random bytes generattion
package main
import (
"crypto/rand"
"fmt"
)
// Note - NOT RFC4122 compliant
func pseudo_uuid() (uuid string) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println("Error: ", err)
return
}
uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return
}
It works on either option tag or text field:
$("#idname option[value='option1']").remove();
I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
onclick="history.go(-1)"
Simply
You could also stick something like this in the bottom of your SVG (right before the closing </svg>
tag):
<a xmlns="http://www.w3.org/2000/svg" id="anchor" xlink:href="/" xmlns:xlink="http://www.w3.org/1999/xlink" target="_top">
<rect x="0" y="0" width="100%" height="100%" fill-opacity="0"/>
</a>
Then just amend the link to suit. I have used 100% width and height to cover the SVG it sits in. Credit for the technique goes to the smart folks at Clearleft.com - that's where I first saw it used.
Suppose you wanted to cast a String
to a File
(yes it does not make any sense), you cannot cast it directly because the File
class is not a child and not a parent of the String
class (and the compiler complains).
But you could cast your String
to Object
, because a String
is an Object
(Object
is parent). Then you could cast this object to a File
, because a File is an Object
.
So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !
File f = (File)(Object) "Stupid cast";
The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.io.File
In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:
Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:
Now when this task runs it will pass the SSIS variables to the stored proc.
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
You can solve this issue by calling a:link
and a:visited
selectors together. And follow it with a:hover
selector.
a:link, a:visited
{color: gray;}
a:hover
{color: skyblue;}
another alternative is to use a form replacement script/library. They usually hide the original element and replace them with a div or span, which you can style in whatever way you like.
Examples are:
http://customformelements.net (based on mootools) http://www.htmldrive.net/items/show/481/jQuery-UI-Radiobutton-und-Checkbox-Replacement.html
I've been happy with Stack Overflow.
I listen to / watch a few others:
But the constant MS/Google/Apple/Yahoo fluff of these is getting really old.
I've listened to a couple Hanselminutes and might start listening more regularly.
I'd like to find some that deal with actual software engineering issues and not just "tech gossip".
Constructor: The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component. JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created. Bearing this in mind, there is a suitable scenario for using the constructor. This is when we want to utilise dependency injection - essentially for “wiring up” dependencies into the component.
As the constructor is initialised by the JavaScript engine, and TypeScript allows us to tell Angular what dependencies we require to be mapped against a specific property.
ngOnInit is purely there to give us a signal that Angular has finished initialising the component.
This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.
Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor, by design
Follow the below steps in Eclipse.
Check here for more information : How to use web camera in android emulator to capture a live image?
I have used
But none beats google's own tools
For an iPhone 7/7 Plus or newer, use these three Haptic feedback APIs.
let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)
Available styles are .error
, .success
, and .warning
. Each has its own distinctive feel.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to communicate successes, failures, and warnings.
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()
Available styles are .heavy
, .medium
, and .light
. These are simple vibrations with varying degrees of "hardness".
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to simulate physical impacts
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
This is the least noticeable of all the haptics, and so is the most suitable for when haptics should not be taking over the app experience.
From the docs:
A concrete
UIFeedbackGenerator
subclass that creates haptics to indicate a change in selection.
There are a couple of things worth remembering when using these APIs.
You do not actually create the haptic. You request the system generate a haptic. The system will decide based on the below:
Therefore, the system will silently ignore your request for a haptic if it is not possible. If this is due to an unsupported device, you could try this:
func haptic() {
// Get whether the device can generate haptics or not
// If feedbackSupportLevel is nil, will assign 0
let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0
switch feedbackSupportLevel {
case 2:
// 2 means the device has a Taptic Engine
// Put Taptic Engine code here, using the APIs explained above
case 1:
// 1 means no Taptic Engine, but will support AudioToolbox
// AudioToolbox code from the myriad of other answers!
default: // 0
// No haptic support
// Do something else, like a beeping noise or LED flash instead of haptics
}
Substitute the comments in the switch
-case
statements, and this haptic generation code will be portable to other iOS devices. It will generate the highest level of haptic possible.
prepare()
method, to put it in a state of readiness. Using your Game Over example: You may know that the game is about to end, by the user having very low HP, or a dangerous monster being near them.
In this case, preparing the Taptic Engine would create a higher-quality, more responsive experience.
For example, let's say your app uses a pan gesture recogniser to change the portion of the world visible. You want a haptic to generate when the user 'looks' round 360 degrees. Here is how you could use prepare()
:
@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {
haptic = UIImpactFeedbackGenerator(style: .heavy)
switch gesture.state {
case .began:
// The user started dragging the screen.
haptic.prepare()
case .changed:
// The user trying to 'look' in another direction
// Code to change viewable portion of the virtual world
if virtualWorldViewpointDegreeMiddle = 360.0 {
haptic.impactOccured()
}
default:
break
}
This is very nice:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7)
.
There are 10^7 equiprobable (if java.util.Random
is not broken) distinct values so uniqueness may be a concern.
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
Just match /^index\.php/
then reject whatever matches it.
If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:
string s = "Hello There";
bool fHasSpace = s.Contains(" ");
If you're looking for ways to detect whitespace, there's several great options below.
Code Snippet1:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];
Code Snippet2: If you want to add further
[array addObject:value1];
[array addObject:value2];
[array addObject:value3];
And so on
Also you can store key values of dictionary to array
NSArray *keys = [dictionary allKeys];
Use compiler's flag, e.g. flag for GCC:
-Wno-unused-variable
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that play with hour/minutes/seconds/milliseconds are wrong.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {_x000D_
_x000D_
const dayOfWeek = dateObject.getDay(),_x000D_
firstDayOfWeek = new Date(dateObject),_x000D_
diff = dayOfWeek >= firstDayOfWeekIndex ?_x000D_
dayOfWeek - firstDayOfWeekIndex :_x000D_
6 - dayOfWeek_x000D_
_x000D_
firstDayOfWeek.setDate(dateObject.getDate() - diff)_x000D_
firstDayOfWeek.setHours(0,0,0,0)_x000D_
_x000D_
return firstDayOfWeek_x000D_
}_x000D_
_x000D_
// August 18th was a Saturday_x000D_
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)_x000D_
_x000D_
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"_x000D_
// (may vary according to your time zone)_x000D_
document.write(lastMonday)
_x000D_
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
Their synchronization semantics are very different:
As such one can see a mutex as a token passed from task to tasks and a semaphore as traffic red-light (it signals someone that it can proceed).
Make checks if the result of the compilation, e.g. somefile.o, is older than the source, e.g. somefile.c. The warning above means that something about the timestaps of the files is strange. Probably the system clocks of the University server differs from your clock and you e.g. push at 1 pm a file with modification date 2 pm. You can see the time at the console by typing date.
This is for swift 2.3 Version. You can get the width of string.
var sizeOfString = CGSize()
if let font = UIFont(name: "Helvetica", size: 14.0)
{
let finalDate = "Your Text Here"
let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works
sizeOfString = (finalDate as NSString).sizeWithAttributes(fontAttributes)
}
If you have just a pair of brackets ( []
) in your string, you can use indexOf()
:
String str = "ABC[ This is the text to be extracted ]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
What about:
PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;
This woks for me.
import time
def timer(n):
while n!=0:
n=n-1
time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
print "00 : ",n
timer(30) #here you can change n according to your requirement.
According to this answer to a similar question, it should be enough:
rvmsudo gem install bundler.
Cheers
You can combine strings using stream string like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string name = "Bill";
stringstream ss;
ss << "Your name is: " << name;
string info = ss.str();
cout << info << endl;
return 0;
}
// This is for normal triangle
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
// This is for left triangle, just removed space before printing *
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
do it with a loop:
function randomWithLength($length){
$number = '';
for ($i = 0; $i < $length; $i++){
$number .= rand(0,9);
}
return (int)$number;
}
As explain by the JLS, integer operation are quite simple.
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
So to make it short, an operation would always result in a int
at the only exception that there is a long
value in it.
int = int + int
long = int + long
int = short + short
Note that the priority of the operator is important, so if you have
long = int * int + long
the int * int
operation would result in an int
, it would be promote into a long
during the operation int + long
If your stored procedure uses linked servers or openquery, they may run quickly by themselves but take a long time to render in SSRS. Some general suggestions:
I see that the question has been answered, I'm just adding this in case someone has this same issue.
As has already been shown here, there are many ways of declaring multiple
constructors in PHP, but none of them are the correct
way of doing so (since PHP technically doesn't allow it).
But it doesn't stop us from hacking this functionality...
Here's another example:
<?php
class myClass {
public function __construct() {
$get_arguments = func_get_args();
$number_of_arguments = func_num_args();
if (method_exists($this, $method_name = '__construct'.$number_of_arguments)) {
call_user_func_array(array($this, $method_name), $get_arguments);
}
}
public function __construct1($argument1) {
echo 'constructor with 1 parameter ' . $argument1 . "\n";
}
public function __construct2($argument1, $argument2) {
echo 'constructor with 2 parameter ' . $argument1 . ' ' . $argument2 . "\n";
}
public function __construct3($argument1, $argument2, $argument3) {
echo 'constructor with 3 parameter ' . $argument1 . ' ' . $argument2 . ' ' . $argument3 . "\n";
}
}
$object1 = new myClass('BUET');
$object2 = new myClass('BUET', 'is');
$object3 = new myClass('BUET', 'is', 'Best.');
Source: The easiest way to use and understand multiple constructors:
Hope this helps. :)
You can try also a tidyverse
library(tidyverse)
dummyData %>%
as.tibble() %>%
count(value)
# A tibble: 2 x 2
value n
<dbl> <int>
1 1 25
2 2 75
NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
Or a little more readable:
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):
OldRange = (OldMax - OldMin)
if (OldRange == 0)
NewValue = NewMin
else
{
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}
Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: NewMin
(see sample), NewMax
or (NewMin + NewMax) / 2
I'm just reposting what others have said, in a simple to follow list of instructions.
Move the repository: Simply login to the new server, cd
to the parent directory where you now want to hold the repository, and use rsync
to copy from the old server:
new.server> rsync -a -v -e ssh [email protected]:path/to/repository.git .
Make clients point to the new repository: Now on each client using the repository, just remove the pointer to the old origin, and add one to the new one.
client> git remote rm origin
client> git remote add origin [email protected]:path/to/repository.git
I would just loop through your JRadioButtons
and call isSelected()
. If you really want to go from the ButtonGroup
you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?
I would use this query:
SELECT
user_id
FROM
wp_usermeta
WHERE
(meta_key = 'first_name' AND meta_value = '$us_name') OR
(meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') OR
(meta_key = 'u_city' AND meta_value = '$us_reg') OR
(meta_key = 'us_course' AND meta_value = '$us_course')
GROUP BY
user_id
HAVING
COUNT(DISTINCT meta_key)=4
this will select all user_id
that meets all four conditions.
The 'mangler' in the above code sample was doing the equivalent of this:
bytesThing = stringThing.encode(encoding='UTF-8')
There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8')
, but the above syntax makes it obvious what is going on, and also what to do to recover the string:
newStringThing = bytesThing.decode(encoding='UTF-8')
When we do this, the original string is recovered.
Note, using str(bytesThing)
just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8')
. No error is reported if the encoding is not specified.
Without using max-width
, or percentage column widths, or table-layout: fixed
etc.
https://jsfiddle.net/tturadqq/
How it works:
Step 1: Just let the table auto-layout do its thing.
When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:
Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em
(the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')
Step 3: Set title
on the divs
This is good for accessibility, and is necessary for the little trick we'll use in a moment.
Step 4: Add a CSS ::after
on the div
This is the tricky bit. We set a CSS ::after
, with content: attr(title)
, then position that on top of the div and set text-overflow: ellipsis
. I've coloured it red here to make it clear.
(Note how the long column now has a tailing ellipsis)
Step 5: Set the colour of the div text to transparent
And we're done!
As all others said before you can use $_SERVER['REMOTE_ADDR'];
to get the client IP address.
Also, if you need more information about a user, you can use this:
<?php
$ip = '0.0.0.0';
$ip = $_SERVER['REMOTE_ADDR'];
$clientDetails = json_decode(file_get_contents("http://ipinfo.io/$ip/json"));
echo "You're logged in from: <b>" . $clientDetails->country . "</b>";
?>
Client's more specific information goes in $clientDetails.
You can fetch JSON items stored in $clientDetails variable this way: $clientDetails->PostalCode/hostname/region/loc...
I'm using ipinfo.io to get extra information.
You need also to set .min-height: 0px;
please see bellow:
.navbar-inner {
min-height: 0px;
}
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
If you set .min-height: 0px;
then you can choose any height you want!
Good Luck!
This is the result from
library(scales)
show_col(hue_pal()(4))
show_col(hue_pal()(3))
I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean
<fieldset [disabled]="isAnonymous">
<label class="control-label" for="firstName">FirstName</label>
<input class="form-control" id="firstName" type="text" formControlName="firstName" />
</fieldset>
Add this key in plist file...Everything will be alright..
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Just paste before </dict></plist>
if your android version is below Android - 6 then you need to add this line otherwise it will work above Android - 6.
...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
Like others have said, it's not possible with just JavaScript due to the security model of such.
If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.
My problem was executing the command (npm audit fix all). I solved it when closing VSCODE and re-executed the command without problems.
Alert will block the program flow so you can just write the following.
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='http://someplace.com';
</script>");
Trigger function from jQuery could be your answer.
jQuery docs says: Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user
Thus best one line solution should be:
$('.selector_class').trigger('click');
//or
$('#foo').click();
If you know the (maximum) number of rows and columns beforehand, you can use resize()
to initialize a vector of vectors and then modify (and access) elements with operator[]
. Example:
int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;
std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));
// Read from matrix.
int value = matrix[1][2];
// Save to matrix.
matrix[3][1] = 5;
Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column]
.
For conda virtual environments on Windows, make sure your batch file is NOT named activate.bat
as this will cause a conflict with the conda activate
command, resulting in a recursive calling of the batch file.
What works for me is the following Shell path:
"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""
And in the activate-env.bat file:
call activate myenvname
Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...
The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll
and I updated the answer to include VC15 even it's beyond scope of the original question.
On http://windows.php.net/ you can read:
VC9, VC11 and VC15
More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.
The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.
This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)
For example, archive name php-5.6.4-nts-Win32-VC11-x86
tells us the following
Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.
Download links
Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!
If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.
SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
| 17 |
+------+
The -maxdepth
option should be before the -name
option, like below.,
find . -maxdepth 1 -name "string" -print
Try this. It always works for me
wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL
You can find the last day of the month by a single line of code:
int maxdt = (new DateTime(dtfrom.Year, dtfrom.Month, 1).AddMonths(1).AddDays(-1)).Day;
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
You can simply write
new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));
I want to control the height of the border. How could I do this?
You can't. CSS borders will always span across the full height / width of the element.
One workaround idea would be to use absolute positioning (which can accept percent values) to place the border-carrying element inside one of the two divs. For that, you would have to make the element position: relative
.
You should use Console.ReadLine() if you want to read some input from the console.
To see your code running in Console:
In Solution Explorer (View - Solution Explorer from the menu), right click on your project, select Open Folder in File Explorer, to find where your project path is.
Supposedly the path is C:\code\myProj .
Open the Command Prompt app in Windows.
Change to your folder path. cd C:\code\myProj
Change to the debug folder, where you should find your program executable. cd bin\debug
Run your program executable, it should end in .exe extension.
Example:
myproj.exe
You should see what you output in Console.Out.WriteLine() .
In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.
Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db
and no longer by its IP.
An easier alternative to solve this problem is to return an string, and format that string to json with JavaScriptSerializer.
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
It is important the "Select" part, which choose the properties you want in your view. Some object have a reference for the parent. If you do not choose the attributes, the circular reference may appear, if you just take the tables as a whole.
Do not do this:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.toList();
return j.Serialize(entityList );
}
Do this instead if you don't want the whole table:
public string GetEntityInJson()
{
JavaScriptSerializer j = new JavaScriptSerializer();
var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
return j.Serialize(entityList );
}
This helps render a view with less data, just with the attributes you need, and makes your web run faster.
Alternatively, by changing a line of the above code:
# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))
It should also work.
From docs TWIG docs:
Unlike in PHP, it's not possible to break or continue in a loop.
But still:
You can however filter the sequence during iteration which allows you to skip items.
Example 1 (for huge lists you can filter posts using slice, slice(start, length)
):
{% for post in posts|slice(0,10) %}
<h2>{{ post.heading }}</h2>
{% endfor %}
Example 2:
{% for post in posts if post.id < 10 %}
<h2>{{ post.heading }}</h2>
{% endfor %}
You can even use own TWIG filters for more complexed conditions, like:
{% for post in posts|onlySuperPosts %}
<h2>{{ post.heading }}</h2>
{% endfor %}
Why don't you guys try SSEventListener?
You don't need to create any gesture recognizer and separate your logic apart to another method. SSEventListener
supports setting listener blocks on a view to listen for single tap gesture, double tap gesture and N-tap gesture if you like, and long press gesture. Setting a single tap gesture listener becomes this way:
[view ss_addTapViewEventListener:^(UITapGestureRecognizer *recognizer) { ... } numberOfTapsRequired:1];
This picture will remove everyone's confusion hopefully which is collected from there.
It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.
Se e.g. GCC 4.8.0 /bits/stdc++.h source.
Using it would include a lot of unnecessary stuff and increases compilation time.
Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.
`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`
simply write the above code after your actual code. for eg. am taking input from user and print on console hence my code will be look like this -->
`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`
You can adjust the pane title by setting the pane border in the tmux.conf for example like this:
###############
# pane border #
###############
set -g pane-border-status bottom
#colors for pane borders
setw -g pane-border-style fg=green,bg=black
setw -g pane-active-border-style fg=colour118,bg=black
setw -g automatic-rename off
setw -g pane-border-format ' #{pane_index} #{pane_title} : #{pane_current_path} '
# active pane normal, other shaded out?
setw -g window-style fg=colour28,bg=colour16
setw -g window-active-style fg=colour46,bg=colour16
Where pane_index, pane_title and pane_current_path are variables provided by tmux itself.
After reloading the config or starting a new tmux session, you can then set the title of the current pane like this:
tmux select-pane -T "fancy pane title";
#or
tmux select-pane -t paneIndexInteger -T "fancy pane title";
If all panes have some processes running, so you can't use the command line, you can also type the commands after pressing the prefix bind (C-b by default) and a colon (:) without having "tmux" in the front of the command:
select-pane -T "fancy pane title"
#or:
select-pane -t paneIndexInteger -T "fancy pane title"
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data . As per your data it should be
<table id="datatable">
<thead>
<tr>
<th>Subscriber ID</th>
<th>Install Location</th>
<th>Subscriber Name</th>
<th>some data</th>
</tr>
</thead>
</table>
I add the changes directly to my virtualhost instead the global config of nginx, like this:
server {
client_max_body_size 100M;
...
}
And then I change the params in php.ini, like the comments above:
max_input_time = 24000
max_execution_time = 24000
upload_max_filesize = 12000M
post_max_size = 24000M
memory_limit = 12000M
and what you can not forget is to restart nginx and php-fpm, in centos 7 is like this:
systemctl restart nginx
systemctl restart php-fpm
You need to turn on Show All Files
option on solution pane toolbar and include this file manually.
It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit()
instead of QApplication.closeAllWindows()
for closing a Java application it generates an error log.
In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:
# An error report file with more information is saved as hs_err_pid24139.log.
The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:
Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
It needs to set same Security level in all zones. To do that follow the steps below:
1.Open IE
2.Go to Tools -> Internet Options -> Security
3.Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.
Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.
const
is like let
, it is a LexicalDeclaration (VariableStatement, Declaration) used to define an identifier in your block.
You are trying to mix this with the default
keyword, which expects a HoistableDeclaration, ClassDeclaration or AssignmentExpression to follow it.
Therefore it is a SyntaxError.
If you want to const
something you need to provide the identifier and not use default
.
export
by itself accepts a VariableStatement or Declaration to its right.
AFAIK the export in itself should not add anything to your current scope.
The following is fine
export default Tab;
Tab
becomes an AssignmentExpression as it's given the name default ?
export default Tab = connect( mapState, mapDispatch )( Tabs );
is fine
Here Tab = connect( mapState, mapDispatch )( Tabs );
is an AssignmentExpression.
Using the TextBox.ReadOnly
property
TextBox.ReadOnly = true;
For a Non-Grey background you can change the TextBox.BackColor
property to SystemColors.Window
Color
textBox.BackColor = System.Drawing.SystemColors.Window;
When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.
To those looking for a coffeescript version of the accepted answer:
$(".typeahead").typeahead source: (query, process) ->
$.get "/typeahead",
query: query
, (data) ->
process data.options
For what is worth:
the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer
+-------+--------+
| input | output |
+-------+--------+
| 1 | 0 |
| 2 | 0 |
| 3 | 5 |
| 4 | 5 |
| 5 | 5 |
| 6 | 5 |
| 7 | 5 |
| 8 | 10 |
| 9 | 10 |
+-------+--------+
private int roundClosest(final int i, final int k) {
int deic = (i % k);
if (deic <= (k / 2.0)) {
return (int) (Math.floor(i / (double) k) * k);
} else {
return (int) (Math.ceil(i / (double) k) * k);
}
}
A Simple way is
UPDATE tbl_name SET fild_name = value WHERE fild_name IS NULL
To set align text in dataGridCell you have two ways:
Set the align for a specific cell or set for each cell of row.
For one column go to Columns->DataGridViewCellStyle
or
For each column go to RowDefaultCellStyle
The control panel is the same as the follow:
Here is a simple generic C++11 function contains
which works for both arrays and containers:
using namespace std;
template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Simple usage contains(arr, el)
is somewhat similar to in
keyword semantics in Python.
Here is a complete demo:
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>
template<typename C, typename T>
bool contains(C&& c, T e) {
return std::find(std::begin(c), std::end(c), e) != std::end(c);
};
template<typename C, typename T>
void check(C&& c, T e) {
std::cout << e << (contains(c,e) ? "" : " not") << " found\n";
}
int main() {
int a[] = { 10, 15, 20 };
std::array<int, 3> b { 10, 10, 10 };
std::vector<int> v { 10, 20, 30 };
std::string s { "Hello, Stack Overflow" };
check(a, 10);
check(b, 15);
check(v, 20);
check(s, 'Z');
return 0;
}
Output:
10 found
15 not found
20 found
Z not found
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List and Map.
ListX<Choices> choices;
Map<String, Choice> map = choices.toMap(c-> c.getName(),c->c);
There's a trick you can do with the pre-processor.
It has the potential down sides that it will collapse white-space, and could be confusing for people reading the code.
But, it has the up side that you don't need to escape quote characters inside it.
#define QUOTE(...) #__VA_ARGS__
const char *sql_query = QUOTE(
SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC
);
the preprocessor turns this into:
const char *sql_query = "SELECT word_id FROM table1, table2 WHERE table2.word_id = table1.word_id ORDER BY table1.word ASC";
I've used this trick when I was writing some unit tests that had large literal strings containing JSON. It meant that I didn't have to escape every quote character \".
We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.
var Head = [[_x000D_
'Heading 1',_x000D_
'Heading 2', _x000D_
'Heading 3', _x000D_
'Heading 4'_x000D_
]];_x000D_
_x000D_
var row = [_x000D_
{key1:1,key2:2, key3:3, key4:4},_x000D_
{key1:2,key2:5, key3:6, key4:7},_x000D_
{key1:3,key2:2, key3:3, key4:4},_x000D_
{key1:4,key2:2, key3:3, key4:4},_x000D_
{key1:5,key2:2, key3:3, key4:4}_x000D_
];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
Head.push([_x000D_
row[item].key1,_x000D_
row[item].key2,_x000D_
row[item].key3,_x000D_
row[item].key4_x000D_
]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
_x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print
is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map()
function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join()
. Then, the %
string formatting operator substitutes the string in instead of %s
in "[%s]"
.
OK I did it finally:
Sub CountUniqueRecords()
Dim Array() as variant, UniqueArray() as variant, UniqueNo as Integer,
Dim i as integer, j as integer, k as integer
Redim UnquiArray(1)
k= Upbound(array)
For i = 1 To k
For j = 1 To UniqueNo + 1
If Array(i) = UniqueArray(j) Then GoTo Nx
Next j
UniqueNo = UniqueNo + 1
ReDim Preserve UniqueArray(UniqueNo + 1)
UniqueArray(UniqueNo) = Array(i)
Nx:
Next i
MsgBox UniqueNo
End Sub
Adding to @Josh's example;
fName = [FILE TO OPEN]
if os.path.exists(fName):
with open(fName, 'rb') as f:
#add you code to handle the file contents here.
elif IOError:
print "Unable to open file: "+str(fName)
This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!
an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).
its mean miss match Android SDK version of cordova with the version you installed. For an example cordova support Android SDK 24 but you don't have Android sdk 24. it may be reverse.
You need to add the following line:
using FootballLeagueSystem;
into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login
.
At the moment the compiler can't find the Login
class.
An interface can extend multiple interfaces.
A class can implement multiple interfaces.
However, a class can only extend a single class.
Careful how you use the words extends
and implements
when talking about interface
and class
.
The accepted solution no longer seems to work for newer versions of mysql-python. The installer no longer provides a site.cfg
file to edit.
If you are installing mysql-python it'll look for C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include
. If you have a 64-bit installation of MySQL, you can simply invoke:
mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include"
pip install mysql-python
Better late than never - if you're looking for unnecessary clutter or overhead then it's hard to beat the following in terms of least code/fast execution at the same time.
Data class:
public class MyData {
int id;
boolean relevant;
String name;
float value;
}
Comparator:
public class MultiFieldComparator implements Comparator<MyData> {
@Override
public int compare(MyData dataA, MyData dataB) {
int result;
if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
(result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
(result = dataA.name.compareTo(dataB.name)) == 0)
result = Float.compare(dataA.value, dataB.value);
return result;
}
}
If you are just looking to sort a collection by a custom order then the following is even cleaner:
myDataList.sort((dataA, dataB) -> {
int result;
if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
(result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
(result = dataA.name.compareTo(dataB.name)) == 0)
result = Float.compare(dataA.value, dataB.value);
return result;
});
AppCompat
supportOther answers suspecting if android:tint
will work on only 21+ devices only, AppCompat(v23.2.0 and above) now provides a backward compatible handling of tint attribute.
So, the course of action would be to use AppCompatImageView
and app:srcCompat
(in AppCompat namespace) instead of android:src
(Android namespace).
Here is an example(AndroidX: This is androidx.appcompat.widget.AppCompatImageView ;)):
<android.support.v7.widget.AppCompatImageView
android:id="@+id/credits_material_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:scaleType="fitCenter"
android:tint="#ffd2ee"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/ic_dollar_coin_stack" />
And don't forget to enable vector drawable support in gradle:
vectorDrawables.useSupportLibrary = true
Try
import sys
fn_name = sys._getframe().f_code.co_name
further reference https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
If you still don't know, you can get back the original object by:
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
because $("#deviceTypeRoot")
also returns an array of objects which the selector has selected.
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
I know that due to this ugly anonymous inner class usage of TransactionTemplate
doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.
In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional
on the test methods. Why? Because @Transactional
may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate
can be perfect for controlling transaction boundries when we want that control.
$song = DB::table('songs')->find($id);
here you use method find($id)
for Laravel, if you use this method, you should have column named 'id' and set it as primary key, so then you'll be able to use method find()
otherwise use where('SongID', $id)
instead of find($id)
With an Excel vba script to provision and create accounts. I was needing to grant full rights permissions to the folder and subfolders that were created by the tool using our administrators 'x' account to our new user.
cacls looked something like this: cacls \FileServer\Users\Username /e /g Domain\Username:C
I needed to migrate this code to Windows 7 and beyond. My solution turned out to be:
icacls \FileServer\Users\Username /grant:r Domain\Username:(OI)(CI)F /t
/grant:r - Grants specified user access rights. Permissions replace previously granted explicit permissions. Without :r, permissions are added to any previously granted explicit permissions
(OI)(CI) - This folder, subfolders, and files.
F - Full Access
/t - Traverse all subfolders to match files/directories.
What this gave me was a folder on this server that the user could only see that folder and created subfolders, that they could read and write files. As well as create new folders.
While rather late to the game, I'll give another solution here as this is still one of the first links to show up on google. Using matplotlib 2.2.2, this can be achieved using the gridspec feature. In the example below the aim is to have four subplots arranged in a 2x2 fashion with the legend shown at the bottom. A 'faux' axis is created at the bottom to place the legend in a fixed spot. The 'faux' axis is then turned off so only the legend shows. Result: https://i.stack.imgur.com/5LUWM.png.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#Gridspec demo
fig = plt.figure()
fig.set_size_inches(8,9)
fig.set_dpi(100)
rows = 17 #the larger the number here, the smaller the spacing around the legend
start1 = 0
end1 = int((rows-1)/2)
start2 = end1
end2 = int(rows-1)
gspec = gridspec.GridSpec(ncols=4, nrows=rows)
axes = []
axes.append(fig.add_subplot(gspec[start1:end1,0:2]))
axes.append(fig.add_subplot(gspec[start2:end2,0:2]))
axes.append(fig.add_subplot(gspec[start1:end1,2:4]))
axes.append(fig.add_subplot(gspec[start2:end2,2:4]))
axes.append(fig.add_subplot(gspec[end2,0:4]))
line, = axes[0].plot([0,1],[0,1],'b') #add some data
axes[-1].legend((line,),('Test',),loc='center') #create legend on bottommost axis
axes[-1].set_axis_off() #don't show bottommost axis
fig.tight_layout()
plt.show()
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
(Note that upgrading pip
using pip
i.e pip install --upgrade pip
will also not upgrade it correctly. It's just a chicken-and-egg issue. pip
won't work unless using TLS >= 1.2.)
As mentioned in this detailed answer, this is due to the recent TLS deprecation for pip. Python.org sites have stopped support for TLS versions 1.0 and 1.1.
From the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
For PyCharm (virtualenv) users:
Run virtual environment with shell. (replace "./venv/bin/activate" to your own path)
source ./venv/bin/activate
Run upgrade
curl https://bootstrap.pypa.io/get-pip.py | python
Restart your PyCharm instance, and check your Python interpreter in Preference.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.
As the answers indicate (if you examine them carefully!), your question is ambiguous. What do you mean by "an A-z letter" or a digit?
If you want to know if a character is a Unicode letter or digit, then use the Character.isLetter
and Character.isDigit
methods.
If you want to know if a character is an ASCII letter or digit, then the best thing to do is to test by comparing with the character ranges 'a' to 'z', 'A' to 'Z' and '0' to '9'.
Note that all ASCII letters / digits are Unicode letters / digits ... but there are many Unicode letters / digits characters that are not ASCII. For example, accented letters, cyrillic, sanskrit, ...
The general solution is to do this:
Character.UnicodeBlock block = Character.UnicodeBlock.of(someCodePoint);
and then test to see if the block is one of the ones that you are interested in. In some cases you will need to test for multiple blocks. For example, there are (at least) 4 code blocks for Cyrillic characters and 7 for Latin. The Character.UnicodeBlock
class defines static constants for well-known blocks; see the javadocs.
Note that any code point will be in at most one block.
First of all, there are cases when object construction is a task complex enough to justify its extraction to another class.
I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.
Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!
There is an easy workaround for this:
struct Cartesian {
inline Cartesian(float x, float y): x(x), y(y) {}
float x, y;
};
struct Polar {
inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);
The only disadvantage is that it looks a bit verbose:
Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));
But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classes to avoid copying overhead.
As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically can be deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil? for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:
class Abstract {
public:
virtual void do() = 0;
};
class Factory {
public:
Abstract *create();
};
Factory f;
Abstract *a = f.create();
a->do();
In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.
Here is a generic script you can use in SQL server. just amend the start and end dates:
IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END
CREATE TABLE [Calendar]
(
[CalendarDate] DATETIME
)
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)
WHILE @StartDate <= @EndDate
BEGIN
INSERT INTO [Calendar]
(
CalendarDate
)
SELECT
@StartDate
SET @StartDate = DATEADD(dd, 1, @StartDate)
END
If you want a more advanced calendar here is one I found on the net a while ago:
CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go
CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
@Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT
SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO
CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
[Date] datetime NOT NULL,
[Year] int NOT NULL,
[Quarter] int NOT NULL,
[Month] int NOT NULL,
[Week] int NOT NULL,
[Day] int NOT NULL,
[DayOfYear] int NOT NULL,
[Weekday] int NOT NULL,
[Fiscal_Year] int NOT NULL,
[Fiscal_Quarter] int NOT NULL,
[Fiscal_Month] int NOT NULL,
[KindOfDay] varchar(10) NOT NULL,
[Description] varchar(50) NULL,
PRIMARY KEY CLUSTERED ([Date])
)
GO
ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/
ADD CONSTRAINT [Calendar_ck] CHECK ( ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week] BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO
SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),
DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),
Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,
-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,
CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
WHEN (DATEPART(DayOfYear, d.Date) = 1) -- New Year's Day
OR (d.Date = Auxiliary.Computus(YEAR(Date))-7) -- Palm Sunday
OR (d.Date = Auxiliary.Computus(YEAR(Date))-3) -- Maundy Thursday
OR (d.Date = Auxiliary.Computus(YEAR(Date))-2) -- Good Friday
OR (d.Date = Auxiliary.Computus(YEAR(Date))) -- Easter Sunday
OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1) -- Labour day
OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17) -- Constitution day
OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25) -- Cristmas day
OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26) -- Boxing day
THEN 'HOLIDAY'
WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
WHEN (DATEPART(DayOfYear, d.Date) = 1) THEN 'New Year''s Day'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7) THEN 'Palm Sunday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3) THEN 'Maundy Thursday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2) THEN 'Good Friday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))) THEN 'Easter Sunday'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1) THEN 'Labour day'
WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17) THEN 'Constitution day'
WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25) THEN 'Cristmas day'
WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26) THEN 'Boxing day'
END Description
FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
inner join Weeks w
on d.Thursday = w.Thursday
OPTION(MAXRECURSION 0)
GO
CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO
CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO
Cast bare integer to decimal:
select cast(9 as decimal(4,2)); //prints 9.00
Cast Integers 8/5 to decimal:
select cast(8/5 as decimal(11,4)); //prints 1.6000
Cast string to decimal:
select cast(".885" as decimal(11,3)); //prints 0.885
Cast two int variables into a decimal
mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)
mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)
mysql> select @myvar1/@myvar2; //prints 0.6250
Cast decimal back to string:
select cast(1.552 as char(10)); //shows "1.552"
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
If you have a lot files to change in your projects you can create functions with the same names like mysql functions, and in the functions make the convert like this code:
$sql_host = "your host";
$sql_username = "username";
$sql_password = "password";
$sql_database = "database";
$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function mysql_query($query){
$result = $mysqli->query($query);
return $result;
}
function mysql_fetch_array($result){
if($result){
$row = $result->fetch_assoc();
return $row;
}
}
function mysql_num_rows($result){
if($result){
$row_cnt = $result->num_rows;;
return $row_cnt;
}
}
Here is a more complete example of an XML filter (the example above by itself will not work since it just shows a snippet and is missing the <FindBugsFilter>
begin and end tags):
<FindBugsFilter>
<Match>
<Class name="com.mycompany.foo" />
<Method name="bar" />
<Bug pattern="NP_BOOLEAN_RETURN_NULL" />
</Match>
</FindBugsFilter>
If you are using the Android Studio FindBugs plugin, browse to your XML filter file using File->Other Settings->Default Settings->Other Settings->FindBugs-IDEA->Filter->Exclude filter files->Add.
You should use some HTML parsing library like lxml
:
from lxml import etree
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
print dict(zip(headers, values))
prints
{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}
You don't need to add the columns manually. Just use a DataAdapter
and it's simple as:
DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(table);
}
Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter
.
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
Just npm install
to install node_modules
To limit the zoom on v.3+. in your map setting add default zoom level and minZoom or maxZoom (or both if required) zoom levels are 0 to 19. You must declare deafult zoom level if limitation is required. all are case sensitive!
function initialize() {
var mapOptions = {
maxZoom:17,
minZoom:15,
zoom:15,
....
Sortest one...
select top 0 * into #temptable from mytable
Note : This creates an empty copy of temp, But it doesn't create a primary key
<iframe style="display: block; margin: auto;" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen></iframe>
If you want to style the output of a data frame in a jupyter notebook cell, you can set the display style on a per-dataframe basis:
df = pd.DataFrame({'A': np.random.randn(4)*1e7})
df.style.format("{:.1f}")
See the documentation here.
The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?
Require all granted
is only in 2.4, but Allow all ...
stops working in 2.4, and we want to be able to rollout a config that works in both.
The only solution I found, which I am not sure is the proper one, is to use:
# backwards compatibility with apache 2.2
Order allow,deny
Allow from all
# forward compatibility with apache 2.4
Require all granted
Satisfy Any
This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...
See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.
Here is a solution that will automatically convert to tabs whenever you open a file.
Create this file: .../Packages/User/on_file_load.py
:
import sublime
import sublime_plugin
class OnFileLoadEventListener(sublime_plugin.EventListener):
def on_load_async(self, view):
view.run_command("unexpand_tabs")
NOTE. It causes the file to be in an unsaved state after opening it, even if no actual space-to-tab conversion took place... maybe some can help with a fix for that...
Solution can be done be this way:
Example:
public static final int cameraRequestCode = 999;
Hope this will help you.
In Java:
String regex = "[^-\\s]";
System.out.println("-".matches(regex)); // prints "false"
System.out.println(" ".matches(regex)); // prints "false"
System.out.println("+".matches(regex)); // prints "true"
The regex [^-\s]
works as expected. [^\s-]
also works.
The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret.
Improving whoami's answer. Since findFirst()
returns an Optional
, it is
a good practice to check if there is a value.
var optional = pair.keySet().stream().findFirst();
if (!optional.isPresent()) {
return;
}
var key = optional.get();
Also, some commented that finding first key of a HashSet
is unreliable. But sometimes we have HashMap
pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.
The I
attribute only exists on matrix
objects, not ndarray
s. You can use numpy.linalg.inv
to invert arrays:
inverse = numpy.linalg.inv(x)
Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.
try:
inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
# Not invertible. Skip this one.
pass
else:
# continue with what you were doing
Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:
for comb in itertools.product(range(10), repeat=9):
rather than combinations_with_replacement
, or you'll skip matrices like
numpy.array([[0, 1, 0],
[0, 0, 0],
[0, 0, 0]])
Don't hard code it: this is the sort of thing that can change. Many programs figure out what to bind to by reading in a config file, and doing whatever that says. This way, should your program sometime in the future need to bind to something that's not a public IP, it can do so.
This function splits float number into integers and returns it in array:
function splitNumber(num)
{
num = ("0" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
return [ ~~num[1], ~~num[3] ];
}
console.log(splitNumber(3.2)); // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789)); // [ 789, 0 ]
console.log(splitNumber("test")); // [ 0, 0 ]
_x000D_
You can extend it to only return existing numbers and null
if no number exists:
function splitNumber(num)
{
num = ("" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
return [num ? ~~num[1] : null, num && num[3] !== undefined ? ~~num[3] : null];
}
console.log(splitNumber(3.2)); // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789)); // [ 789, null ]
console.log(splitNumber("test")); // [ null, null ]
_x000D_
SUBSTITUTE()
in a string can be nasty, however, it's always possible to arrange it: You can read multiple variables from file like this:
for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H
where param.txt:
PARAM1=value1
PARAM2=value2
...
Luckily, it’s very easy to resolve. Run the follow command from an elevated command prompt:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If you’re on a 32-bit machine, you may have to use the following:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
The answer depends on specifically what you mean by the "top 1000 distinct" records.
If you mean that you want to return at most 1000 distinct records, regardless of how many duplicates are in the table, then write this:
SELECT DISTINCT TOP 1000 id, uname, tel
FROM Users
ORDER BY <sort_columns>
If you only want to search the first 1000 rows in the table, and potentially return much fewer than 1000 distinct rows, then you would write it with a subquery or CTE, like this:
SELECT DISTINCT *
FROM
(
SELECT TOP 1000 id, uname, tel
FROM Users
ORDER BY <sort_columns>
) u
The ORDER BY
is of course optional if you don't care about which records you return.
Do note that if you're adding stuff, you might always want to check that you're not going beyond the limits of int
(especially in homework exercises).
Also, int main ()
should return an int
.
Using a "do .. while" loop:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int previous = 0;
int number;
int numberitems;
int count = 0;
cout << "Enter number of items: ";
cin >> numberitems;
if ( numberitems <= 0 )
{
//no request to perform sum
cout << "Quitting without summing.\n\n";
return 0;
}
do
{
cout << "Enter number to add : ";
cin >> number;
sum+=number;
// check here that the addition didn't break anything.
// Negative + negative should stay negative, positive + postive should stay positive
if ((number > 0 && previous > 0 && sum < 0) || (number < 0 && previous < 0 && sum > 0))
{
cout << "Error: Beyond int limits !!";
return 1;
}
count++;
previous = sum;
}
while ( count < numberitems);
cout<<"sum is: "<< sum<<endl;
return 0;
}
size_t
is the result type of the sizeof
operator.
Use size_t
for variables that model size or index in an array. size_t
conveys semantics: you immediately know it represents a size in bytes or an index, rather than just another integer.
Also, using size_t
to represent a size in bytes helps making the code portable.
Hashes are a sequence of bits (128 bits, 160 bits, 256 bits, etc., depending on the algorithm). Your column should be binary-typed, not text/character-typed, if MySQL allows it (SQL Server datatype is binary(n)
or varbinary(n)
). You should also salt the hashes. Salts may be text or binary, and you will need a corresponding column.
In ascending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
or in descending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
As has been mentioned, as of PHP 5.6+ you can (should!) use the ...
token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:
<?php
function variadic($arg1, $arg2)
{
// Do stuff
echo $arg1.' '.$arg2;
}
$array = ['Hello', 'World'];
// 'Splat' the $array in the function call
variadic(...$array);
// 'Hello World'
Note: array items are mapped to arguments by their position in the array, not their keys.
As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array
.
Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.
(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)
This is great for making sure an array contains items of a specific type:
<?php
// Define the function...
function variadic($var, SomeClass ...$items)
{
// $items will be an array of objects of type `SomeClass`
}
// Then you can call...
variadic('Hello', new SomeClass, new SomeClass);
// or even splat both ways
$items = [
new SomeClass,
new SomeClass,
];
variadic('Hello', ...$items);
The only thing I would add to Mark Peters solution is that you don't need to iterate over the ArrayList - you should be able to use the addAll(Collection) method on the Set. You only need to iterate over the entire list to do the summations.
var ar = 'foo bar spam egg'.split(/\W/);
for(var i=0; i<ar.length; i++) {
ar[i] = ar[i].substr(0,1).toUpperCase() + ar[i].substr(1,ar[i].length-1)
}
ar.join(' '); // Foo Bar Spam Egg
This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt
located in the root of the local PC C: drive where <YYYYMMDD>
is the current date:
SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF
SET FEEDBACK OFF
SET TERMOUT OFF
column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
from dual
/
DBMS_OUTPUT.ENABLE(1000000);
SPOOL C:\output_&today_var..txt
DECLARE
ab varchar2(10) := 'Raj';
cd varchar2(10);
a number := 10;
c number;
d number;
BEGIN
c := a+10;
--
SELECT ab, c
INTO cd, d
FROM dual;
--
DBMS_OUTPUT.put_line('cd: '||cd);
DBMS_OUTPUT.put_line('d: '||d);
END;
SPOOL OFF
SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON
PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT
Hope it helps...
EDIT:
After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):
BEGIN
c := a+10;
--
FOR i IN 1 .. 10
LOOP
c := a+10;
-- Output the value of C
DBMS_OUTPUT.put_line('c: '||c);
END LOOP;
--
END;
Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.
import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3
unix_timestamp_plus_5_min = unix_timestamp + (5 * 60) # 5 min * 60 seconds
This will take care of the empty td:
<td style="min-width: 20px;"></td>
This:
print "\n"
is printing out two \n
characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a ,
like you use in print a,
. Simply use
print
instead.
According to Md. Sajedul Karim answer I wrote a similar one.
webView = (WebView) view.findViewById(R.id.web);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
webView.setWebChromeClient(new WebChromeClient());
setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarVisibility(View.GONE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(getActivity(), "Cannot load page", Toast.LENGTH_SHORT).show();
setProgressBarVisibility(View.GONE);
}
});
webView.loadUrl(url);
private void setProgressBarVisibility(int visibility) {
// If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
if (progressBar != null) {
progressBar.setVisibility(visibility);
}
}
As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc.
# JAVA_OPTS (Optional) Java runtime options used when any command
# is executed.
# Include here and not in CATALINA_OPTS all options, that
# should be used by Tomcat and also by the stop process,
# the version command etc.
# Most options should go into CATALINA_OPTS.
sudo yum install fontconfig freetype libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6
You have to update your app.config file manually
// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Do whatever you need, like modifying the appSettings section
// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
And then tell your application to reload any section you modified
ConfigurationManager.RefreshSection("appSettings");
However, if you have indented code, it doesn't work out so well:
echo "continuation \ lines" >continuation lines
Try with single quotes and concatenating the strings:
echo 'continuation' \
'lines'
>continuation lines
Note: the concatenation includes a whitespace.
When in doubt, follow MVC conventions.
Create a viewModel if you haven't already that contains a property for JobID
public class Model
{
public string JobId {get; set;}
public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
//...any other properties you may need
}
Strongly type your view
@model Fully.Qualified.Path.To.Model
Add a hidden field for JobId to the form
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{
//...
@Html.HiddenFor(m => m.JobId)
}
And accept the model as the parameter in your controller action:
[HttpPost]
public FileStreamResult myMethod(Model model)
{
sting str = model.JobId;
}
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
There are several ways you can achieve this based on the approach you take. For reactive approach, you can pass the default value to the constructor of the FormControl(import from @angular/forms)
this.randomForm = new FormGroup({
'amateur': new FormControl(false),
});
Instead of true or false value, yes you can send variable name as well like FormControl(this.booleanVariable)
In template driven approach you can use 1 way binding [ngModel]="this.booleanVariable"
or 2 way binding [(ngModel)]="this.booleanVariable"
like this
<mat-checkbox
name="controlName"
[(ngModel)]="booleanVariable">
{{col.title}}
</mat-checkbox>
You can also use the checked directive provided by angular material and bind in similar manner
For example,
package main
import "fmt"
func main() {
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", []byte(s), "a:", a)
}
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Does not seem like it, but android recognises a webcam as a device. Every time I run the emulator my webcam's active light comes on.