Usually I prefer to use this extension:
Swift 3.x and Swift 4.0:
extension FileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
return paths[0]
}
}
Swift 2.x:
extension NSFileManager {
class func documentsDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
class func cachesDir() -> String {
var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
return paths[0]
}
}
One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:new_file_path_str error:&error];
if (error){
NSLog(@"%@", error);
}
Add this code ..It helped me
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:/org/springframework/context/config/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
classpath:/org/springframework/aop/config/spring-aop-3.0.xsd
">
</beans>
I had the same problem. I solved it by removing the line break from the xml file. I did
<operationBindings>
<OperationBinding>
<operationType>update</operationType>
<operationId>makePdf</operationId>
<serverObject>
<className>com.myclass</className>
<lookupStyle>new</lookupStyle>
</serverObject>
<serverMethod>makePdf</serverMethod>
</OperationBinding>
</operationBindings>
instead of ...
<serverObject>
<className>com.myclass
</className>
<lookupStyle>new</lookupStyle>
</serverObject>
Here's a useful little function, which makes using/creating iOS folders a little easier.
You pass it the name of a subfolder, it'll return the full path back to you, and make sure the directory exists.
(Personally, I stick this static function in my AppDelete class, but perhaps this isn't the smartest place to put it.)
Here's how you would call it, to get the "full path" of a MySavedImages subdirectory:
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
And here's the full function:
+(NSString*)getFullPath:(NSString*)folderName
{
// Check whether a subdirectory exists in our sandboxed Documents directory.
// Returns the full path of the directory.
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (paths.count < 1)
return nil;
NSString *rootFolder = [paths firstObject];
NSString* fullFolderPath = [rootFolder stringByAppendingPathComponent:folderName];
BOOL isDirectory;
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:fullFolderPath isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:fullFolderPath
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error) {
NSLog(@"Error creating directory path: %@", [error localizedDescription]);
return nil;
}
}
return fullFolderPath;
}
Using this little function, it's easy to create a directory in your app's Documents directory (if it doesn't already exist), and to write a file into it.
Here's how I would create the directory, and write the contents of one of my image files into it:
// Let's create a "MySavedImages" subdirectory (if it doesn't already exist)
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
// As an example, let's load the data in one of my images files
NSString* imageFilename = @"icnCross.png";
UIImage* image = [UIImage imageNamed:imageFilename];
NSData *imageData = UIImagePNGRepresentation(image);
// Obtain the full path+filename where we can write this .png to, in our new MySavedImages directory
NSString* imageFilePathname = [fullPath stringByAppendingPathComponent:imageFilename];
// Write the data
[imageData writeToFile:imageFilePathname atomically:YES];
Hope this helps !
Swift
func saveFile() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as! String
let fileName = "\(documentsDirectory)/textFile.txt"
let content = "Hello World"
content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
}
func loadFile() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as! String
let fileName = "\(documentsDirectory)/textFile.txt"
let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!
println(content)
}
Swift 2
func saveFile() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/textFile.txt"
let content = "Hello World"
do{
try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
}catch _ {
}
}
func loadFile()->String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/textFile.txt"
let content: String
do{
content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)
}catch _{
content=""
}
return content;
}
Swift 3
func saveFile() {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/textFile.txt"
let content = "Hello World"
do{
try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
}catch _ {
}
}
func loadFile()->String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(documentsDirectory)/textFile.txt"
let content: String
do{
content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)
} catch _{
content=""
}
return content;
}
Something like this worked for me.
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
classpath:org/springframework/beans/factory/xml/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
classpath:org/springframework/beans/factory/xml/spring-context-3.0.xsd"
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
This code should work for you
$("#intro").owlCarousel ({
slideSpeed : 800,
autoPlay: 6000,
items : 1,
stopOnHover : true,
itemsDesktop : [1199,1],
itemsDesktopSmall : [979,1],
itemsTablet : [768,1],
});
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
The simplest way is this:
while (cursor.moveToNext()) {
...
}
The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.
Of course, don't forget to close the cursor once you're done with it, preferably in a finally
clause.
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
If you target API 19+, you can use try-with-resources.
try (Cursor cursor = db.rawQuery(...)) {
while (cursor.moveToNext()) {
...
}
}
There is actually a truly invisible character: U+FEFF
.
This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM
for short is an invisible character that doesn't take up any space. You can copy the character bellow between the >
and <
.
Here is the character:
> <
How to catch this character in action:
>
and <
,You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!
EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php
Put this at the top of your .py file (for python 2.x)
#!/usr/bin/env python
or for python 3.x
#!/usr/bin/env python3
This should look up the python environment, without it, it will execute the code as if it were not python code, but straight to the CLI. If you need to specify a manual location of python environment put
#!/#path/#to/#python
I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):
weak
, because they are long lived. The view controller could close before
the request completes so self
no longer points to a valid object when the closure is called. If you have closure that handles an event on a button. This can be unowned
because as soon as the view controller goes away, the button and any other items it may be referencing from self
goes away at the same time. The closure block will also go away at the same time.
class MyViewController: UIViewController {
@IBOutlet weak var myButton: UIButton!
let networkManager = NetworkManager()
let buttonPressClosure: () -> Void // closure must be held in this class.
override func viewDidLoad() {
// use unowned here
buttonPressClosure = { [unowned self] in
self.changeDisplayViewMode() // won't happen after vc closes.
}
// use weak here
networkManager.fetch(query: query) { [weak self] (results, error) in
self?.updateUI() // could be called any time after vc closes
}
}
@IBAction func buttonPress(self: Any) {
buttonPressClosure()
}
// rest of class below.
}
I had the same problem on my mac and found it was because the Mac was replacing the standard quotes with curly quotes which are illegal javascript characters.
To fix this I had to change the settings on my mac System Preferences=>Keyboard=>Text(tab) uncheck use smart quotes and dashes (default was checked).
Using javascript seems to be unnecessary if you choose CSS3.
By using :before
selector, you can do this in two lines of CSS. (no script involved).
Another advantage of this approach is that it does not rely on <label>
tag and works even it is missing.
Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).
input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?
You can see a demo here: http://jsfiddle.net/hqZt6/1/
and this one with images:
You will need to add the jar to your local maven repository. Alternatively (better option) specify the proper repository (if one exists) so it can be automatically downloaded by maven
In either case, remove the <systemPath>
tag from the dependency
It should be simpler!
Duration.between(startLocalDateTime, endLocalDateTime).toMillis();
You can convert millis to whatever unit you like:
String.format("%d minutes %d seconds",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).
Hacakable URLs/REST API make the Web better.
To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():
import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)
index = np.searchsorted(data, values)
print data[index] == values
VCRUNTIME140.dll error
This error means you don't have required Visual C++ packages installed in your computer.
If you have installed wampserver then firstly uninstall wampserver.
Download the VC packages
Download all these VC packages and install all of them. You should install both 64 bit and 32 bit version.
-- VC9 Packages (Visual C++ 2008 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=5582
http://www.microsoft.com/en-us/download/details.aspx?id=2092
-- VC10 Packages (Visual C++ 2010 SP1)--
http://www.microsoft.com/en-us/download/details.aspx?id=8328
http://www.microsoft.com/en-us/download/details.aspx?id=13523
-- VC11 Packages (Visual C++ 2012 Update 4)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=30679
-- VC13 Packages] (Visual C++ 2013)--
The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page
https://www.microsoft.com/en-us/download/details.aspx?id=40784
-- VC14 Packages (Visual C++ 2015)--
The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page
http://www.microsoft.com/en-us/download/details.aspx?id=48145
install packages with admin priviliges
Right click->Run as Administrator
install wampserver again
After you installed both 64bits and 32 bits version of VC packages then install wampserver again.
Nothing elegant but this could be another satisfactory answer.
merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]
This will be useful especially when you don't need the keys that were used to join the tables in your results.
The best solution that worked great for me.
You have to: Copy this code to your main CSS file,
.responsive-video {
position: relative;
padding-bottom: 56.25%;
padding-top: 60px; overflow: hidden;
}
.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
and then put your embeded video to
<div class="responsive-video">
<iframe ></iframe>
</div>
That’s it! Now you can use responsive videos on your site.
For those of you getting here looking to remove from an array of objects and using lodash you can do something like this:
const objects = [{ a: 'string', b: false, c: 'string', d: undefined }]
const result = objects.map(({ a, b, c, d }) => _.pickBy({ a,b,c,d }, _.identity))
// [{ a: 'string', c: 'string' }]
Note: You don't have to destruct if you don't want to.
The API only works during user interaction, so it cannot be used maliciously. Try the following code:
addEventListener("click", function() {
var el = document.documentElement,
rfs = el.requestFullscreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
|| el.msRequestFullscreen
;
rfs.call(el);
});
Try:
git config --global credential.helper cache
This command prevents git to ask username and password, not forever but with a default limit to 15 minutes.
git config --global credential.helper 'cache --timeout=3600'
This moves the default limit to 1 hour.
Your query is very close. You should be able to use the following which includes the subject
in the final select list:
select u.name, u.subject, u.marks
from student s
unpivot
(
marks
for subject in (Maths, Science, English)
) u;
I know this question is a couple years old, but I am surprised to find that no one suggested:
text-align: center;
this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.
Functional Approach for ES6+
If you want to take a more functional approach to iterating over the Map
object, you can do something like this
const myMap = new Map()
myMap.forEach((value, key) => {
console.log(value, key)
})
guys try this is a perfect answer for this question:
<script>
$(function(){
$('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
$('.nav li a').click(function(){
$(this).parent().addClass('active').siblings().removeClass('active')
})
})
</script>
_x000D_
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.
If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.
Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:
You can also set the rule using T-SQL:
ALTER TABLE YourTable
DROP Constraint Your_FK
GO
ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO
Hope this helps
If you want to make a change global to the whole notebook:
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]
In Debian Jessie, this works nice:
ls -lah --group-directories-first
# l=use a long listing format
# a=do not ignore entries starting with .
# h=human readable
# --group-directories-first=(obvious)
# Note: add -r for reverse alpha
# You might consider using lh by appending to ~/.bashrc as the alias:
~$ echo "alias lh='ls -lah --group-directories-first'" >>~/.bashrc
# -- restart your terminal before using lh command --
You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.
You could set
table tr ul.actions {margin: 0; white-space:nowrap;}
(or set this for the last TD as Sander suggested instead).
This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.
This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space
-property is applied, stretching its content beyond the calculated boundaries.
So I guess it's not possible without having an element within the last TD with a specific width.
use simplejson or cjson for speedups
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
You can get column type of DataTable with DataType attribute of datatable column like below:
var type = dt.Columns[0].DataType
dt : DataTable object.
0 : DataTable column index.
Hope It Helps
Ty :)
If you use use the Jquery from Google CDN, seriously it will improve the performance by 5 to 10 times the one which you add into your page, which gets downloaded. And also, you will get the latest version of the Jquery files.
The difference between both files i.e. jquery.js and jquery.min.js is just the file size, due to this the files are getting downloaded faster. :)
No one says anything about php-doc, but for me that is also a very significant argument for the preference of const
:
/**
* My foo-bar const
* @var string
*/
const FOO = 'BAR';
hashmap.put(key, hashmap.get(key) + 1);
The method put
will replace the value of an existing key and will create it if doesn't exist.
This will be helpful link:
http://graph.facebook.com/893914824028397/picture?type=large&redirect=true&width=500&height=500
You can set height and width as you needed
893914824028397 is facebookid
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
Put your TableLayout inside a ScrollView Layout.That will solve your problem.
function give_array(){
$a = "abc";
$b = "def";
$c = "ghi";
return compact('a','b','c');
}
$my_array = give_array();
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
This seem to work for me in Bootstrap v5 alpha 3
_variables-overrides.scss
$primary: #00adef;
$theme-colors: (
"primary": $primary,
);
main.scss
// Overrides
@import "variables-overrides";
// Required - Configuration
@import "@/node_modules/bootstrap/scss/functions";
@import "@/node_modules/bootstrap/scss/variables";
@import "@/node_modules/bootstrap/scss/mixins";
@import "@/node_modules/bootstrap/scss/utilities";
// Optional - Layout & components
@import "@/node_modules/bootstrap/scss/root";
@import "@/node_modules/bootstrap/scss/reboot";
@import "@/node_modules/bootstrap/scss/type";
@import "@/node_modules/bootstrap/scss/images";
@import "@/node_modules/bootstrap/scss/containers";
@import "@/node_modules/bootstrap/scss/grid";
@import "@/node_modules/bootstrap/scss/tables";
@import "@/node_modules/bootstrap/scss/forms";
@import "@/node_modules/bootstrap/scss/buttons";
@import "@/node_modules/bootstrap/scss/transitions";
@import "@/node_modules/bootstrap/scss/dropdown";
@import "@/node_modules/bootstrap/scss/button-group";
@import "@/node_modules/bootstrap/scss/nav";
@import "@/node_modules/bootstrap/scss/navbar";
@import "@/node_modules/bootstrap/scss/card";
@import "@/node_modules/bootstrap/scss/accordion";
@import "@/node_modules/bootstrap/scss/breadcrumb";
@import "@/node_modules/bootstrap/scss/pagination";
@import "@/node_modules/bootstrap/scss/badge";
@import "@/node_modules/bootstrap/scss/alert";
@import "@/node_modules/bootstrap/scss/progress";
@import "@/node_modules/bootstrap/scss/list-group";
@import "@/node_modules/bootstrap/scss/close";
@import "@/node_modules/bootstrap/scss/toasts";
@import "@/node_modules/bootstrap/scss/modal";
@import "@/node_modules/bootstrap/scss/tooltip";
@import "@/node_modules/bootstrap/scss/popover";
@import "@/node_modules/bootstrap/scss/carousel";
@import "@/node_modules/bootstrap/scss/spinners";
// Helpers
@import "@/node_modules/bootstrap/scss/helpers";
// Utilities
@import "@/node_modules/bootstrap/scss/utilities/api";
@import "custom";
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
The element has both an attribute and a property named checked
. The property determines the current state.
The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.
If there is no value for the attribute in the markup, the attribute becomes null
, but the property is always either true
or false
, so it becomes false
.
When you set the property, you should use a boolean value:
document.getElementById('myRadio').checked = true;
If you set the attribute, you use a string:
document.getElementById('myRadio').setAttribute('checked', 'checked');
Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.
Note also that whatever value you set the attribute to, the property becomes true
. Even if you use an empty string or null
, setting the attribute means that it's checked. Use removeAttribute
to uncheck the element using the attribute:
document.getElementById('myRadio').removeAttribute('checked');
Check out the AsyncImageView
provided over here. Some good example code, and might even be usable right "out of the box" for you.
If using the docker-compose file, Based on docker compose version 2.x We can set like as below, by overriding the default config.
ulimits:
nproc: 65535
nofile:
soft: 26677
hard: 46677
I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.
The solution was as simple as closing the tab and opening a fresh one!
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:
result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
use the text and value attributes instead of the id
driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();
similarly for Next.
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:
cap = cv2.VideoCapture(camera_url)
while True:
ret, frame = cap.read()
if not ret:
cap = cv.VideoCapture(camera_url)
continue
# do your processing here
And it works perfectly!
Update (2019, latest)
Since Jan 2019, GitHub allows private repositories for up to three collaborators.
Previous answer:
Here is the comparison for free plans listed by tree main Git Cloud based solutions:
Here is the comparison for paid plans listed by tree main Git Cloud based solutions:
I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.
GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.
Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.
GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.
In my case, the request type was wrong. I was using GET(dumb) It must be PUT.
Although Jasons answer works, it does only work if one wants to add a function to a class. It did not work for me when I tried to reload an already existing method from the .py source code file.
It took me for ages to find a workaround, but the trick seems simple... 1.st import the code from the source code file 2.nd force a reload 3.rd use types.FunctionType(...) to convert the imported and bound method to a function you can also pass on the current global variables, as the reloaded method would be in a different namespace 4.th now you can continue as suggested by "Jason Pratt" using the types.MethodType(...)
Example:
# this class resides inside ReloadCodeDemo.py
class A:
def bar( self ):
print "bar1"
def reloadCode(self, methodName):
''' use this function to reload any function of class A'''
import types
import ReloadCodeDemo as ReloadMod # import the code as module
reload (ReloadMod) # force a reload of the module
myM = getattr(ReloadMod.A,methodName) #get reloaded Method
myTempFunc = types.FunctionType(# convert the method to a simple function
myM.im_func.func_code, #the methods code
globals(), # globals to use
argdefs=myM.im_func.func_defaults # default values for variables if any
)
myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method
setattr(self,methodName,myNewM) # add the method to the function
if __name__ == '__main__':
a = A()
a.bar()
# now change your code and save the file
a.reloadCode('bar') # reloads the file
a.bar() # now executes the reloaded code
Do you want to change database?
\l - to display databases
\c - connect to new database
Update.
I've read again your question. To display schemas
\dn - list of schemas
To change schema, you can try
SET search_path TO
If you want the biggest image from YouTube for a specific video ID, then the URL should be something like this:
http://i3.ytimg.com/vi/SomeVideoIDHere/0.jpg
Using the API, you can pick up default thumbnail image. Simple code should be something like this:
//Grab the default thumbnail image
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
$thumbnail = substr($thumbnail, 0, -5);
$thumb1 = $thumbnail."default.jpg";
// Grab the third thumbnail image
$thumb2 = $thumbnail."2.jpg";
// Grab the fourth thumbnail image.
$thumb3 = $thumbnail."3.jpg";
// Using simple cURL to save it your server.
// You can extend the cURL below if you want it as fancy, just like
// the rest of the folks here.
$ch = curl_init ("$thumb1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);
// Using fwrite to save the above
$fp = fopen("SomeLocationInReferenceToYourScript/AnyNameYouWant.jpg", 'w');
// Write the file
fwrite($fp, $rawdata);
// And then close it.
fclose($fp);
Note, that Dijkstra works even for negative weights, if the Graph has no negative cycles, i.e. cycles whose summed up weight is less than zero.
Of course one might ask, why in the example made by templatetypedef Dijkstra fails even though there are no negative cycles, infact not even cycles. That is because he is using another stop criterion, that holds the algorithm as soon as the target node is reached (or all nodes have been settled once, he did not specify that exactly). In a graph without negative weights this works fine.
If one is using the alternative stop criterion, which stops the algorithm when the priority-queue (heap) runs empty (this stop criterion was also used in the question), then dijkstra will find the correct distance even for graphs with negative weights but without negative cycles.
However, in this case, the asymptotic time bound of dijkstra for graphs without negative cycles is lost. This is because a previously settled node can be reinserted into the heap when a better distance is found due to negative weights. This property is called label correcting.
Let's say you're opening the file with a with
statement like you should be. Then you'd do something like this to read from your file:
with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
Note the f.seek(0)
-- if you forget this, the f.read()
call will try to read from the end of the file, and will return an empty string.
Firstly, I highly recommend you do your CSS styling in an external CSS file, rather than doing it inline. It's much easier to maintain and can be more reusable using classes.
Working off Alex's answer (& Garret's clearfix) of "adding an element at the end with clear: both", you can do it like so:
<div id='outerdiv' style='border: 1px solid black; background-color: black;'>
<div style='width: 300px; border: red 1px dashed; float: left;'>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div style='width: 300px; border: red 1px dashed; float: right;'>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
<div style='clear:both;'></div>
</div>
This works (but as you can see inline CSS isn't so pretty).
I had the same problem, two list boxes and two buttons.
The data in the list boxes was being loaded from a database and you could move items between boxes by clicking the buttons.
I was getting an invalid postback.
turns out that it was the data had carriage return line feeds in it which you cannot see when displayed in the list box.
worked fine in every browser except IE 10 and IE 11.
Remove the carriage return line feeds and all works fine.
This seems to be the issue:
An input that is received via Ajax websocket etc, and it will be in String format, but you need to know if it is JSON.parsable
. The touble is, if you always run it through JSON.parse
, the program MAY continue "successfully" but you'll still see an error thrown in the console with the dreaded "Error: unexpected token 'x'"
.
var data;
try {
data = JSON.parse(jqxhr.responseText);
} catch (_error) {}
data || (data = {
message: 'Server error, please retry'
});
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
Late reading this, but.. The way I read your question, you only need to change two lines of code:
Accept user input, function writes back on screen.
<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>
<!-- add this line for function to write into -->
<p id="demo"></p>
<script type="text/javascript">
function test(){
var userInput = document.getElementById("userInput").value;
document.getElementById("demo").innerHTML = userInput;
}
</script>
The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.
IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.
I would like to praise josh3736's answer for providing some excellent historical context. While it's well articulated, the CSS landscape has changed in the almost five years since this question was asked. When this question was asked, px
was the correct answer, but that no longer holds true today.
tl;dr: use rem
Historically px
units typically represented one device pixel. With devices having higher and higher pixel density this no longer holds for many devices, such as with Apple's Retina Display.
rem
units represent the root em size. It's the font-size
of whatever matches :root
. In the case of HTML, it's the <html>
element; for SVG, it's the <svg>
element. The default font-size
in every browser* is 16px
.
At the time of writing, rem
is supported by approximately 98% of users. If you're worried about that other 2%, I'll remind you that media queries are also supported by approximately 98% of users.
px
The majority of CSS examples on the internet use px
values because they were the de-facto standard. pt
, in
and a variety of other units could have been used in theory, but they didn't handle small values well as you'd quickly need to resort to fractions, which were longer to type, and harder to reason about.
If you wanted a thin border, with px
you could use 1px
, with pt
you'd need to use 0.75pt
for consistent results, and that's just not very convenient.
rem
rem
's default value of 16px
isn't a very strong argument for its use. Writing 0.0625rem
is worse than writing 0.75pt
, so why would anyone use rem
?
There are two parts to rem
's advantage over other units.
px
value of rem
to whatever you'd likeBrowser zoom has changed a lot over the years. Historically many browsers would only scale up font-size
, but that changed pretty rapidly when websites realized that their beautiful pixel-perfect designs were breaking any time someone zoomed in or out. At this point, browsers scale the entire page, so font-based zooming is out of the picture.
Respecting a user's wishes is not out of the picture. Just because a browser is set to 16px
by default, doesn't mean any user can't change their preferences to 24px
or 32px
to correct for low vision or poor visibility (e.x. screen glare). If you base your units off of rem
, any user at a higher font-size will see a proportionally larger site. Borders will be bigger, padding will be bigger, margins will be bigger, everything will scale up fluidly.
If you base your media queries on rem
, you can also make sure that the site your users see fits their screen. A user with font-size
set to 32px
on a 640px
wide browser, will effectively be seeing your site as shown to a user at 16px
on a 320px
wide browser. There's absolutely no loss for RWD in using rem
.
px
ValueBecause rem
is based on the font-size
of the :root
node, if you want to change what 1rem
represents, all you have to do is change the font-size
:
:root {_x000D_
font-size: 100px;_x000D_
}_x000D_
body {_x000D_
font-size: 1rem;_x000D_
}
_x000D_
<p>Don't ever actually do this, please</p>
_x000D_
Whatever you do, don't set the :root
element's font-size
to a px
value.
If you set the font-size
on html
to a px
value, you've blown away the user's preferences without a way to get them back.
If you want to change the apparent value of rem
, use %
units.
The math for this is reasonably straight-forward.
The apparent font-size of :root
is 16px
, but lets say we want to change it to 20px
. All we need to do is multiply 16
by some value to get 20
.
Set up your equation:
16 * X = 20
And solve for X
:
X = 20 / 16
X = 1.25
X = 125%
:root {_x000D_
font-size: 125%;_x000D_
}
_x000D_
<p>If you're using the default font-size, I'm 20px tall.</p>
_x000D_
Doing everything in multiples of 20
isn't all that great, but a common suggestion is to make the apparent size of rem
equal to 10px
. The magic number for that is 10/16
which is 0.625
, or 62.5%
.
:root {_x000D_
font-size: 62.5%;_x000D_
}
_x000D_
<p>If you're using the default font-size, I'm 10px tall.</p>
_x000D_
The problem now is that your default font-size
for the rest of the page is set way too small, but there's a simple fix for that: Set a font-size
on body
using rem
:
:root {_x000D_
font-size: 62.5%;_x000D_
}_x000D_
_x000D_
body {_x000D_
font-size: 1.6rem;_x000D_
}
_x000D_
<p>I'm the default font-size</p>
_x000D_
It's important to note, with this adjustment in place, the apparent value of rem
is 10px
which means any value you might have written in px
can be converted directly to rem
by bumping a decimal place.
padding: 20px;
turns into
padding: 2rem;
The apparent font-size you choose is up to you, so if you want there's no reason you can't use:
:root {
font-size: 6.25%;
}
body {
font-size: 16rem;
}
and have 1rem
equal 1px
.
So there you have it, a simple solution to respect user wishes while also avoiding over-complicating your CSS.
I was afraid you might ask that. As much as I'd like to pretend that rem
is magic and solves-all-things, there are still some issues of note. Nothing deal-breaking in my opinion, but I'm going to call them out so you can't say I didn't warn you.
em
)One of the first issues you'll run into with rem
involves media queries. Consider the following code:
:root {
font-size: 1000px;
}
@media (min-width: 1rem) {
:root {
font-size: 1px;
}
}
Here the value of rem
changes depending on whether the media-query applies, and the media query depends on the value of rem
, so what on earth is going on?
rem
in media queries uses the initial value of font-size
and should not (see Safari section) take into account any changes that may have happened to the font-size
of the :root
element. In other words, it's apparent value is always 16px
.
This is a bit annoying, because it means that you have to do some fractional calculations, but I have found that most common media queries already use values that are multiples of 16.
| px | rem |
+------+-----+
| 320 | 20 |
| 480 | 30 |
| 768 | 48 |
| 1024 | 64 |
| 1200 | 75 |
| 1600 | 100 |
Additionally if you're using a CSS preprocessor, you can use mixins or variables to manage your media queries, which will mask the issue entirely.
SafariUnfortunately there's a known bug with Safari where changes to the :root
font-size do actually change the calculated rem
values for media query ranges. This can cause some very strange behavior if the font-size of the :root
element is changed within a media query. Fortunately the fix is simple: use em
units for media queries.
If you switch between projects various different projects, it's quite possible that the apparent font-size of rem
will have different values. In one project, you might be using an apparent size of 10px
where in another project the apparent size might be 1px
. This can be confusing and cause issues.
My only recommendation here is to stick with 62.5%
to convert rem
to an apparent size of 10px
, because that has been more common in my experience.
If you're writing CSS that's going to be used on a site that you don't control, such as for an embedded widget, there's really no good way to know what apparent size rem
will have. If that's the case, feel free to keep using px
.
If you still want to use rem
though, consider releasing a Sass or LESS version of the stylesheet with a variable to override the scaling for the apparent size of rem
.
* I don't want to spook anyone away from using rem
, but I haven't been able to officially confirm that every browser uses 16px
by default. You see, there are a lot of browsers and it wouldn't be all that hard for one browser to have diverged ever so slightly to, say 15px
or 18px
. In testing, however I have not seen a single example where a browser using default settings in a system using default settings had any value other than 16px
. If you find such an example, please share it with me.
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
If you don't want to reinvent the wheel you may try plupload.com
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};
kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));
Using this code:
foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
the expected output should be:
Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3
The same will work with a KeyValuePair or whatever other type you want to use..
Edit -
To lookup by the key, you can do the following:
var result = stringList.Where(s => s == "Lookup");
You could do this with a KeyValuePair by doing the following:
var result = kvpList.Where (kvp => kvp.Value == "Lookup");
Last edit -
Made the answer specific to KeyValuePair rather than string.
You can store any kind of data in a session using:
Session["VariableName"]=value;
This variable will last 20 mins or so.
simply call the this extension and pass the color it will automatically change the color of nav bar
extension UINavigationController {
func setNavigationBarColor(color : UIColor){
self.navigationBar.barTintColor = color
}
}
in the view didload or in viewwill appear call
self.navigationController?.setNavigationBarColor(color: <#T##UIColor#>)
Do you want to roll back your repo to that state, or you just want your local repo to look like that?
If you reset --hard
, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:
git reset --hard c14809fa
And if you reset --soft
, it will move your HEAD to where they were , but leave your local files etc. the same:
git reset --soft c14809fa
So what exactly do you want to do with this reset?
Edit -
You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.
You can tag this as TAG1.. then a git reset --soft c14809fa
, git reset --soft TAG1
, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07
would all do the same thing.
Perhaps you have some very weird and restrictive SELinux rules in place?
If not, try strace -o /tmp/wtf -fF curl -v google.com
and try to spot from /tmp/wtf
output file what's going on.
Not as a command, but this information is in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion
REG_SZJava Runtime Environment
named with the CurrentVersion
valueJavaHome
REG_SZ to get the pathFor example on my workstation i have
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
JavaHome = "C:\Program Files\Java\jre6"
So my current JRE is in C:\Program Files\Java\jre6
For those looking to do this in VB, here's how I got mine to work with a checkbox.
Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.
<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />
Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).
Public Event OnCheckChanged As EventHandler
Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
RaiseEvent OnCheckChanged(Me, e)
End Sub
<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />
Note: myCheck_CheckChanged didn't fire until I added the Handles clause below
Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
'Do some page logic here
End Sub
According to Wikipedia, the new rupee sign hasn't been added to Unicode yet (U+20B9 ₹ was added to Unicode in late 2010), so you can't use it from HTML. The old (unofficial) symbol is ₨ — ₨.
In my case, some of my rows didn't have the same number of columns as the header. Example, Header has 10 columns, and one of your rows has 8 or 9 columns. (Columns = Count number of you delimiter characters in each line)
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Right click on the table and click on Design,then click on column that you want to set default value.
Then in bottom of page in column properties set Default value or binding to : 'getdate()'
If you are having trouble getting this working, you may need to add the IP address of your server. For example:
server {
listen XXX.XXX.XXX.XXX:80;
listen XXX.XXX.XXX.XXX:443 ssl;
ssl_certificate /var/www/example.com/web/ssl/example.com.crt;
ssl_certificate_key /var/www/example.com/web/ssl/example.com.key;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
where XXX.XXX.XXX.XXX is the IP address (obviously).
Note: ssl crt and key location must be defined to properly redirect https requests
Don't forget to restart nginx after making the changes:
service nginx restart
ArrayList get(int index)
method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.
public Element get(int index)
Example : In below example we are getting few elements of an arraylist by using get method.
package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
System.out.println("First element of the ArrayList: "+al.get(0));
System.out.println("Third element of the ArrayList: "+al.get(2));
System.out.println("Sixth element of the ArrayList: "+al.get(5));
System.out.println("Fourth element of the ArrayList: "+al.get(3));
}
}
Output:
First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook
In Java 8, I use simple helper methods like this:
public static <T> Collection<T> getIntersection(Collection<T> coll1, Collection<T> coll2){
return Stream.concat(coll1.stream(), coll2.stream())
.filter(coll1::contains)
.filter(coll2::contains)
.collect(Collectors.toSet());
}
public static <T> Collection<T> getMinus(Collection<T> coll1, Collection<T> coll2){
return coll1.stream().filter(not(coll2::contains)).collect(Collectors.toSet());
}
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
You could use a print stylesheet, but this will affect all print functions.
You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print()
, then after that remove it.
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array
)
CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$
DECLARE
ids INT[];
BEGIN
ids = string_to_array($1,',');
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 = '1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:
https://github.com/facebook/facebook-android-sdk.git
git://github.com/facebook/facebook-android-sdk.git
For someone who'd not prefer to handle UserDefaults for some reasons, there's another option - NSKeyedArchiver & NSKeyedUnarchiver. It helps save objects into a file using archiver, and load archived file to original objects.
// To archive object,
let mutableData: NSMutableData = NSMutableData()
let archiver: NSKeyedArchiver = NSKeyedArchiver(forWritingWith: mutableData)
archiver.encode(object, forKey: key)
archiver.finishEncoding()
return mutableData.write(toFile: path, atomically: true)
// To unarchive objects,
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
let object = unarchiver.decodeObject(forKey: key)
}
I've write an simple utility to save/load objects in local storage, used sample codes above. You might want to see this. https://github.com/DragonCherry/LocalStorage
The argument associated with the %n
will be treated as an int*
and is filled with the number of total characters printed at that point in the printf
.
I'm using Conda on Windows and this answer did not work for me. But I can suggest another solution:
rename enviroment folder (old_name
to new_name
)
open shell and activate env with custom folder:
conda.bat activate "C:\Users\USER_NAME\Miniconda3\envs\new_name"
now you can use this enviroment, but it's not on the enviroment list. Update\install\remove any package to fix it. For example, update numpy:
conda update numpy
after applying any action to package, the environment will show in env list. To check this, type:
conda env list
Use this:
strstr('filename.ext','.',true);
//result filename
If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc
file type
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc
If you need to do the filteration on multiple types, use the below command.
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf
Now $fileNames
variable act as an array from which you can loop and apply your business logic.
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
This is how Apple does it for classes like NSString:
In the header file:
enum {
PlayerStateOff,
PlayerStatePlaying,
PlayerStatePaused
};
typedef NSInteger PlayerState;
Refer to Coding Guidelines at http://developer.apple.com/
Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:
C:\> pip install modulename
Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:
.Where(y => y.ResponseId.Equals(item.ResponseId))
so you can't call
.First()
on it. Maybe try
.FirstOrDefault()
if it solves the issue.
Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.
Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:
java.util.Date dt = new java.util.Date();
whatever your code object may be
.setDateTime(dt);
important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.
Partial solution: for a single string column
tmp = df['A1'].fillna(''); isEmpty = tmp==''
gives boolean Series of True where there are empty strings or NaN values.
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
If you want Click event of recycle-View from activity/fragment instead of adapter then you can also use following short cut way.
recyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final TextView txtStatusChange = (TextView)v.findViewById(R.id.txt_key_status);
txtStatusChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "hello text " + txtStatusChange.getText().toString() + " TAG " + txtStatusChange.getTag().toString());
Util.showToast(CampaignLiveActivity.this,"hello");
}
});
return false;
}
});
You can also use other long ways like using interface
memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:
(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))
If you don't yet have the distinguished name, you can search for it with:
(&(objectCategory=group)(cn=myCustomGroup))
and return the attribute distinguishedName
. Case may matter.
It is not necessary that onRestoreInstanceState will always be called after onSaveInstanceState.
Note that : onRestoreInstanceState will always be called, when activity is rotated (when orientation is not handled) or open your activity and then open other apps so that your activity instance is cleared from memory by OS.
Give your button a custom background: @drawable/material_btn_blue
one thing I want to add , before you try to install
apt-get install php5-sqlite
or
apt-get install php5-sqlite3
search the given package is available or not :-
# apt-cache search 'php5'
After that you get :-
php5-rrd - rrd module for PHP 5
php5-sasl - Cyrus SASL extension for PHP 5
php5-snmp - SNMP module for php5
**php5-sqlite - SQLite module for php5**
php5-svn - PHP Bindings for the Subversion Revision control system
php5-sybase - Sybase / MS SQL Server module for php5
Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install
**apt-get install php5-sqlite**
You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.
Confirming I was able to use the answer posted by MadBoy and edited by Otiel on both MS SQL Server 2012 and 2014 in addition to the versions previously listed using varbinary(MAX) columns.
If you are wondering why you cannot "Filestream" (noted in a separate answer) as a datatype in the SQL Server table designer or why you cannot set a column's datatype to "Filestream" using T-SQL, it is because FILESTREAM is a storage attribute of the varbinary(MAX) datatype. It is not a datatype on its own.
See these articles on setting up and enabling FILESTREAM on a database: https://msdn.microsoft.com/en-us/library/cc645923(v=sql.120).aspx
http://www.kodyaz.com/t-sql/default-filestream-filegroup-is-not-available-in-database.aspx
Once configured, a filestream enabled varbinary(max) column can be added as so:
ALTER TABLE TableName
ADD ColumnName varbinary(max) FILESTREAM NULL
GO
It's not a jQuery feature but a feature for debugging purposes. You can for instance log something to the console when something happens. For instance:
$('#someButton').click(function() {
console.log('#someButton was clicked');
// do something
});
You'd then see #someButton was clicked
in Firebug’s “Console” tab (or another tool’s console — e.g. Chrome’s Web Inspector) when you would click the button.
For some reasons, the console object could be unavailable. Then you could check if it is - this is useful as you don't have to remove your debugging code when you deploy to production:
if (window.console && window.console.log) {
// console is available
}
Please use sorted() function in Python3
items = ["love", "like", "play", "cool", "my"]
sorted(items2)
Check this fiddle, and forgive me the overstyling: https://jsfiddle.net/dkellner/7ac9us70/
The trick behind: as soon as the <select> tag gets a property called "size", it will behave as a fixed-height list, and, suddenly, for some reason, allows you to style the hell out of it. Now strictly speaking, the fixed list is a side effect - but it just helps us more because we use it for the "dropped-down look".
A minimal example:
<style>
.stylish span {position:relative;}
.stylish select {position:absolute;left:0px;display:none}
</style>
...
<div class="stylish">
<label> Choose your superhero: </label>
<span>
<input onclick="$(this).closest('div').find('select').slideToggle(110)"><br>
<select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">
<optgroup label="Fantasy"></optgroup>
<option value="1"> Gandalf </option>
<option value="2"> Harry Potter </option>
<option value="3"> Jon Snow </option>
<!-- ... and so on -->
</select>
</span>
</div>
(to keep it simple I did it with jQuery - but you can do the same without it)
This solution gives you more than just a select: the value is also manually editable. Use the readonly property if you prefer the default select-restricted way.
To maximize styling possibilities, <optgroup> tags are not around their children, they're moved before them. It's intentional, it's visually clearer, and they're happy to work like this, don't worry.
Javascripts: yes I know the OP said "no Javascript" but I understood it as please don't bother with plugins, which is fine. You don't need any libraries for this one. Not even jQuery, as I said, it's only for the clarity of the example.
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :
String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String
this method :
str.getClass().getSimpleName();
value:String
now example:
Object o = 1;
o.getClass().getSimpleName();
value:Integer
When the workbook first opens, execute this code:
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
Then just have a macro in the workbook called "EventMacro" that will repeat it.
Public Sub EventMacro()
'... Execute your actions here'
alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"
End Sub
No need to use for loop. It can be directly applied to a column of a dataframe
sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)
If you are creating a div
and trying to add a title
to it.
Try
var myDiv= document.createElement("div");
myDiv.setAttribute('title','mytitle');
PEP 8 advises the first form for readability. You can find it here.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
I don't know what gives, but, hash_map takes more than 20 seconds to clear() 150K unsigned integer keys and float values. I am just running and reading someone else's code.
This is how it includes hash_map.
#include "StdAfx.h"
#include <hash_map>
I read this here https://bytes.com/topic/c/answers/570079-perfomance-clear-vs-swap
saying that clear() is order of O(N). That to me, is very strange, but, that's the way it is.
You can at least stop the query from breaking with an error and return NULL
if there is a division by zero:
SELECT a / NULLIF(b, 0) FROM t
However, I would NEVER convert this to Zero with coalesce
like it is shown in that other answer which got many upvotes. This is completely wrong in a mathematical sense, and it is even dangerous as your application will likely return wrong and misleading results.
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
console.log(params['type'])
}); }
This works for me!
\n
is used for Unix systems (including Linux, and OSX).
\r\n
is mainly used on Windows.
\r
is used on really old Macs.
PHP_EOL
constant is used instead of these characters for portability between platforms.
If anyone has similar issue of having a phone with a cracked screen and has a need to access adb:
If you forgot to enable developers mode and your adb isn't running, then do the following:
adb devices
you should see the device in the list.If so, type:
adb shell mount /system
abd shell
echo "persist.service.adb.enable=1" >> default.prop
echo "persist.service.debuggable=1" >> default.prop
echo "persist.sys.usb.config=mtp,adb" >> default.prop
echo "persist.service.adb.enable=1" >> /system/build.prop
echo "persist.service.debuggable=1" >> /system/build.prop
echo "persist.sys.usb.config=mtp,adb" >> /system/build.prop
Now if you are going to reboot into your phone android will tell you "oh your adb is working but please tap on this OK button, so we can trust your PC". And obviously if we can't tap on the phone stay in the recovery mode and do the following (assuming you are not in the adb shell mode, if so first type exit
):
cd ~/.android
adb push adbkey.pub /data/misc/adb/adb_keys
Hurray, it all should be hunky-dory now! Just reboot the phone and you should be able to access adb when the phone is running:
adb shell reboot
P.S. Was using OS X and Moto X Style that's with the cracked screen.
I found that AlertifyJS is a better alternative and have a Bootstrap theme.
alertify.alert('Alert Title', 'Alert Message!', function(){ alertify.success('Ok'); });
Also have a 4 components: Alert, Confirm, Prompt and Notifier.
Exmaple: JSFiddle
myClass.prototype.constructor.name
.myClass.constructor.name
, I had the TypeScript error : error TS2339: Property 'name' does not exist on type 'Function'
.
Complementing the coment of @Mark Baker.
Do as follow:
$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
if($sheet > 0){
$objPHPExcel->createSheet();
$sheet = $objPHPExcel->setActiveSheetIndex($sheet);
$sheet->setTitle("$value");
//Do you want something more here
}else{
$objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
}
$sheet++;
}
This worked for me. And hope it works for those who need! :)
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Recompile without optimizations (-O0 on gcc).
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).
An example of its use:
li * {
display: initial;
}
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
Note that besides all other comments there is a small difference, which should be mentioned here for completeness!
With the empty catch clause you can catch non-CLSCompliant Exceptions when the assembly is marked with "RuntimeCompatibility(WrapNonExceptionThrows = false)" (which is true by default since CLR2). [1][2][3]
[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx
[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx
[3] Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?
If there is XML file with 2 different tables then will:
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2
work
If I understand you correctly you are asking about including nested properties. If so :
.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)
or
.Include("ApplicationsWithOverrideGroup.NestedProp")
or
.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")
I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it.
I tried compiling ffmpeg with the option --enable-encoders=libx264
and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).
Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:
wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
tar --bzip2 -xvf last_x264.tar.bz2
cd x264-snapshot-XXXXXXXX-XXXX/
./configure
make
sudo make install
And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":
wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install
Now finally you have the libx264 codec to encode, to check it you may run
ffmpeg -codecs | grep h264
and you'll see the options you have were the first D means decoding and the first E means encoding
I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.
public class WpfScreen
{
public static IEnumerable<WpfScreen> AllScreens()
{
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
{
yield return new WpfScreen(screen);
}
}
public static WpfScreen GetScreenFrom(Window window)
{
WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen GetScreenFrom(Point point)
{
int x = (int) Math.Round(point.X);
int y = (int) Math.Round(point.Y);
// are x,y device-independent-pixels ??
System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen Primary
{
get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
}
private readonly Screen screen;
internal WpfScreen(System.Windows.Forms.Screen screen)
{
this.screen = screen;
}
public Rect DeviceBounds
{
get { return this.GetRect(this.screen.Bounds); }
}
public Rect WorkingArea
{
get { return this.GetRect(this.screen.WorkingArea); }
}
private Rect GetRect(Rectangle value)
{
// should x, y, width, height be device-independent-pixels ??
return new Rect
{
X = value.X,
Y = value.Y,
Width = value.Width,
Height = value.Height
};
}
public bool IsPrimary
{
get { return this.screen.Primary; }
}
public string DeviceName
{
get { return this.screen.DeviceName; }
}
}
you need to call thread.isAlive()
to find out if the thread is still running
--The following may give you more of what you're looking for:
create Procedure spShowRelationShips
(
@Table varchar(250) = null,
@RelatedTable varchar(250) = null
)
as
begin
if @Table is null and @RelatedTable is null
select object_name(k.constraint_object_id) ForeginKeyName,
object_name(k.Parent_Object_id) TableName,
object_name(k.referenced_object_id) RelatedTable,
c.Name RelatedColumnName,
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
from sys.foreign_key_columns k
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
order by 2,3
if @Table is not null and @RelatedTable is null
select object_name(k.constraint_object_id) ForeginKeyName,
object_name(k.Parent_Object_id) TableName,
object_name(k.referenced_object_id) RelatedTable,
c.Name RelatedColumnName,
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
from sys.foreign_key_columns k
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
where object_name(k.Parent_Object_id) =@Table
order by 2,3
if @Table is null and @RelatedTable is not null
select object_name(k.constraint_object_id) ForeginKeyName,
object_name(k.Parent_Object_id) TableName,
object_name(k.referenced_object_id) RelatedTable,
c.Name RelatedColumnName,
object_name(rc.object_id) + '.' + rc.name RelatedKeyField
from sys.foreign_key_columns k
left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
where object_name(k.referenced_object_id) =@RelatedTable
order by 2,3
end
NETWORK SERVICE and LocalSystem will authenticate themselves always as the correpsonding account locally (builtin\network service and builtin\system) but both will authenticate as the machine account remotely.
If you see a failure like Login failed for user 'DOMAIN\MACHINENAME$'
it means that a process running as NETWORK SERVICE or as LocalSystem has accessed a remote resource, has authenticated itself as the machine account and was denied authorization.
Typical example would be an ASP application running in an app pool set to use NETWORK SERVICE credential and connecting to a remote SQL Server: the app pool will authenticate as the machine running the app pool, and is this machine account that needs to be granted access.
When access is denied to a machine account, then access must be granted to the machine account. If the server refuses to login 'DOMAIN\MACHINE$', then you must grant login rights to 'DOMAIN\MACHINE$' not to NETWORK SERVICE. Granting access to NETWORK SERVICE would allow a local process running as NETWORK SERVICE to connect, not a remote one, since the remote one will authenticate as, you guessed, DOMAIN\MACHINE$.
If you expect the asp application to connect to the remote SQL Server as a SQL login and you get exceptions about DOMAIN\MACHINE$ it means you use Integrated Security in the connection string. If this is unexpected, it means you screwed up the connection strings you use.
If you have a menu then changing ShortcutKeys
property of the ToolStripMenuItem
should do the trick.
If not, you could create one and set its visible
property to false.
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
at
is the correct way.
If you don't have the at
command in the machine and you also don't have install privilegies on it, you can put something like this on cron
(maybe with the crontab
command):
* * * 5 * /path/to/comand_to_execute; /usr/bin/crontab -l | /usr/bin/grep -iv command_to_execute | /usr/bin/crontab -
it will execute your command one time and remove it from cron
after that.
With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.
You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/
It is enough to use color property alongside with -webkit-text-fill-color this way:
input {_x000D_
color: red; /* color of caret */_x000D_
-webkit-text-fill-color: black; /* color of text */_x000D_
}
_x000D_
<input type="text"/>
_x000D_
Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.
The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN
So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.
Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split()
or separate it into two parts using indices:
a = "abc"
a, result = a[:-1], a[-1]
This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):
for result in reversed(a):
...
I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split
:
ans = "foo,blah,etc."
for a in ans.split(","):
...
We can add Unique key index by using fluent api. Below code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}
Get COLUMN INDEX on click:
$(this).closest("td").index();
Get ROW INDEX on click:
$(this).closest("tr").index();
There are different regex engines but I think most of them will work with this:
apple|banana
The below code disables the EditText in android
editText.setEnabled(false);
Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host')
is deprecated, that's why giving Undefined
.
Use,
req.header('Origin');
req.header('Host');
// this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.
I've used Francesco Balena's HashTable class several times in the past when a Collection or Dictionary wasn't a perfect fit and i just needed a HashTable.
If you're looking to verify whether an email address is valid, then VRFY will get you some of the way. I've found it's useful for validating intranet addresses (that is, email addresses for internal sites). However it's less useful for internet mail servers (see the caveats at the top of this page)
Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.
If that's the case, there are several solutions:
If you want to generate the signal with the input of a button you could do the following
int speakerOut = A0;
int buttonPin = 13;
void setup() {
pinMode(speakerOut, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
int a = 0;
void loop() {
if(digitalRead(buttonPin) == LOW) {
a ++;
Serial.println(a);
analogWrite(speakerOut, NULL);
if(a > 50 && a < 300) {
analogWrite(speakerOut, 200);
}
if(a <= 49) {
analogWrite(speakerOut, NULL);
}
if(a >= 300 && a <= 2499) {
analogWrite(speakerOut, NULL);
}
}
}
In this case we're using a button pin as an INPUT_PULLUP
. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors.
Note: This will invert the levels of the button, LOW
will be pressed and HIGH
will be released.
The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.
It is called the Conditional Operator (which is a ternary operator).
It has the form of: condition
? value-if-true
: value-if-false
Think of the ?
as "then" and :
as "else".
Your code is equivalent to
if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = {height: props.height};
}
componentWillMount(){
this.setState({height: window.innerHeight + 'px'});
}
render() {
// render your component...
}
}
Set the props
AppComponent.propTypes = {
height:React.PropTypes.string
};
AppComponent.defaultProps = {
height:'500px'
};
viewport height is now available as {this.state.height} in rendering template
Recently I was helping a friend to find why their carousel was not working. Controls would not work and images were not transitioning. I had a working sample on a page I had used and we went through all the code including checking the items above in this post. We pasted the "good" carousel into the same page and it still worked. Now, all css and bootstrap files were the same for both. The code was now identical, so all we could try was the images.
So, we replaced the images with two that were working in my sample. It worked. We replaced the two images with the first two that were originally not working, and it worked. We added back each image (all jpegs) one-by-one, and when we got to the seventh image (of 18) and the carousel failed. Weird. We removed this one image and continued to add the remaining images until they were all added and the carousel worked.
for reference, we were using jquery-3.3.1.slim.min.js and bootstrap/4.3.1/js/bootstrap.min.js on this site.
I do not know why an image would or could cause a carousel to malfunction, but it did. I couldn't find a reference to this cause elsewhere either, so I'm posting here for posterity in the hope that it might help someone else when other solutions fail.
Test carousel with limited set of "known-to-be-good" images.
I suspect you're building a .war/.jar and consequently it's no longer a file, but a resource within that package. Try ClassLoader.getResourceAsStream(String path) instead.
This my actually working solution
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<!-- The fill color -->
<solid android:color="#ffff" />
<!-- Just to add a border -->
<stroke
android:color="#8000"
android:width="2dp"
/>
</shape>
Make sure your TextView width and height match (be the same in dp), if you want a perfect (unstretched) circle.
Make sure that the text fits into a circle, by either shortening your text OR enlarging your circle OR making your text size smaller OR reduce your padding/s, if any. OR a combination of the above suggestions.
[EDIT]
For what I can see in your pictures, you want to add too much text on a line, for pure circles.
Consider that the text should have a square aspect, so you can either wrap it (use \n
) or just put the numbers inside the circles and put the writings above or uder the corresponding circle.
You can add the collapse
component to the links like this..
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#home" data-toggle="collapse" data-target=".navbar-collapse.show">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#pricing" data-toggle="collapse" data-target=".navbar-collapse.show">Pricing</a>
</li>
</ul>
BS3 demo using 'data-toggle' method
Or, (perhaps a better way) use jQuery like this..
$('.navbar-nav>li>a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
Update 2019 - Bootstrap 4
The navbar has changed, but the "close after click" method is still the same:
BS4 demo jQuery method
BS4 demo data-toggle
method
Update 2021 - Bootstrap 5 (beta)
Use javascript to add a click event listener on the menu items to close the Collapse navbar..
const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle)
navLinks.forEach((l) => {
l.addEventListener('click', () => { bsCollapse.toggle() })
})
Or, Use the data-bs-toggle
and data-bs-target
data attributes in the markup on each link to toggle the Collapse navbar...
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="nav-item active">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Disabled</a>
</li>
</ul>
<form class="d-flex my-2 my-lg-0">
<input class="form-control me-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</div>
</nav>
I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified
can be misleading in some special cases.
In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.
So in fact the message The system cannot find the file specified
was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.
One thing I can suggest you is to extend the storage object to handle objects and arrays.
LocalStorage can handle only strings so you can achieve that using these methods
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
Using it every values will be converted to json string on set and parsed on get
An easy way to do this with some jQuery and straight JavaScript, just view your console in Chrome or Firefox to see the output...
var queries = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
queries[i[0].toString()] = i[1].toString();
});
console.log(queries);
I faced the same problem. Follow these steps:
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
java.util.StringJoiner
Java 8 has got a StringJoiner
class. But you still need to write a bit of boilerplate, because it's Java.
StringJoiner sj = new StringJoiner(" and ", "" , "");
String[] names = {"Bill", "Bob", "Steve"};
for (String name : names) {
sj.add(name);
}
System.out.println(sj);
Bootstrap 4 Solution
<div class="btn-group w-100">
<button type="button" class="btn">One</button>
<button type="button" class="btn">Two</button>
<button type="button" class="btn">Three</button>
</div>
You basically tell the btn-group
container to have width 100% by adding w-100
class to it. The buttons inside will fill in the whole space automatically.
When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
If your problem is org.springframework.web.bind.missingservletrequestparameterexception
you have to change your code to
@RequestMapping(value = "/byName", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
String getUserByName(
@RequestParam( value="firstName",required = false) String firstName,
@RequestParam(value="lastName",required = false) String lastName,
@ModelAttribute("userClientObject") UserClient userClient)
{
return client.getUserByName(userClient, firstName, lastName);
}
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:
http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html
has worked fine for me and not mentioned so far.
git update-index --assume-unchanged <file>
To remove the file you're interested in from version control, then use all your other commands as normal.
git update-index --no-assume-unchanged <file>
If you ever wanted to put it back in.
Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:
Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.
As the Pawan mentioned in the comment about that IDE warning about not to using that fixed position, I have just modified my code as below. The click listener is moved to
ViewHolder
, and there I am getting the position usinggetAdapterPosition()
method
int selected_position = 0; // You have to set this globally in the Adapter class
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Item item = items.get(position);
// Here I am just highlighting the background
holder.itemView.setBackgroundColor(selected_position == position ? Color.GREEN : Color.TRANSPARENT);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Below line is just like a safety check, because sometimes holder could be null,
// in that case, getAdapterPosition() will return RecyclerView.NO_POSITION
if (getAdapterPosition() == RecyclerView.NO_POSITION) return;
// Updating old as well as new positions
notifyItemChanged(selected_position);
selected_position = getAdapterPosition();
notifyItemChanged(selected_position);
// Do your another stuff for your onClick
}
}
hope this'll help.
You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)
Directions:
On the Installation Type screen, select the appropriate SQL Server instance.
Advance through the rest of the wizard.
Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546
Verify this code : It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}
It is not mandatory to write that. It worked fine for me without (%matplotlib
) magic function.
I am using Sypder compiler, one that comes with in Anaconda.
Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)
Here are a couple examples that use define which cannot be replaced by a variable:
#define min(i, j) (((i) < (j)) ? (i) : (j))
note this is evaluated by the pre-processor, not during runtime
It worked like this for me:
document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";
Change the
getElementById("theElementID")
for your element locator (name, css, xpath...)
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
Hi Here is my code to find the longest palindrome in the string. Kindly refer to the following link to understand the algorithm http://stevekrenzel.com/articles/longest-palnidrome
Test data used is HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE
//Function GetPalindromeString
public static string GetPalindromeString(string theInputString)
{
int j = 0;
int k = 0;
string aPalindrome = string.Empty;
string aLongestPalindrome = string.Empty ;
for (int i = 1; i < theInputString.Length; i++)
{
k = i + 1;
j = i - 1;
while (j >= 0 && k < theInputString.Length)
{
if (theInputString[j] != theInputString[k])
{
break;
}
else
{
j--;
k++;
}
aPalindrome = theInputString.Substring(j + 1, k - j - 1);
if (aPalindrome.Length > aLongestPalindrome.Length)
{
aLongestPalindrome = aPalindrome;
}
}
}
return aLongestPalindrome;
}
The behaviour comes from the fact that in Python prior to version 3 bytes
was just an alias for str
. In Python3.x bytes
is an immutable version of bytearray
- completely new type, not backwards compatible.
If you have thousands of untracked files (ugh, don't ask) then git add -i
will not work when adding *
. You will get an error stating Argument list too long
.
If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:
git ls-files -o --exclude-standard | select | foreach { git add $_ }
If you are trying to install matplotlib in order to work with graphs on python. Try this link. https://github.com/jbmohler/matplotlib-winbuild. This is a set of scripts to build matplotlib from source on the MS Windows platform.
To build & install matplotlib in your Python, do:
git clone https://github.com/matplotlib/matplotlib
git clone https://github.com/jbmohler/matplotlib-winbuild
$ python matplotlib-winbuild\buildall.py
The build script will auto-detect Python version & 32/64 bit automatically.
Following points really helped me a lot. There might be other points too, but these are very crucial:
I use a Dictionary and because of the repetetiveness and possible missing keys, I quickly patched together a small method:
private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
{
return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
}
Calling it:
var entry = GetKey(dictList,"KeyValue1");
Gets the job done.
$.fn.rightclick = function(func){
$(this).mousedown(function(event){
if(event.button == 2) {
var oncontextmenu = document.oncontextmenu;
document.oncontextmenu = function(){return false;};
setTimeout(function(){document.oncontextmenu = oncontextmenu;},300);
func(event);
return false;
}
});
};
$('.item').rightclick(function(e){
alert("item");
});
I desperately wanted to test my front-end(React/Angular/VUE) code locally with the REST API provided by the client with no access to the server config.
After trying all the steps above that didn't work I was forced to disable web security and site isolation trials on chrome along with specifying the user data directory(tried skipping this, didn't work).
cd C:\Program Files\Google\Chrome\Application
chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="PATH_TO_PROJECT_DIRECTORY"
This finally worked! Hope this helps!
Run following command in the Terminal to connect to the DBMS (you need root access):
sudo mysql -u root -p;
run update password of the target user (for my example username is mousavi
and it's password must be 123456
):
UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi';
at this point you need to do a flush to apply changes:
FLUSH PRIVILEGES;
Done! You did it without any stop or restart mysql service.
I know the question is about GCC, but for people looking for how to do this in other and/or multiple compilers…
You might want to take a look at Hedley, which is a public-domain single C/C++ header I wrote which does a lot of this stuff for you. I'll put a quick section about how to use Hedley for all this at the end of this post.
#pragma warning (disable: …)
has equivalents in most compilers:
#pragma warning(disable:4996)
#pragma GCC diagnostic ignored "-W…"
where the ellipsis is the name of the warning; e.g., #pragma GCC diagnostic ignored "-Wdeprecated-declarations
.#pragma clang diagnostic ignored "-W…"
. The syntax is basically the same as GCC's, and many of the warning names are the same (though many aren't).#pragma warning(disable:1478 1786)
.diag_suppress
pragma: #pragma diag_suppress 1215,1444
. Note that all warning numbers increased by one in 20.7 (the first NV HPC release).diag_suppress
pragma with the same syntax (but different warning numbers!) as PGI: pragma diag_suppress 1291,1718
error_messages
pragma. Annoyingly, the warnings are different for the C and C++ compilers. Both of these disable basically the same warnings:
#pragma error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)
#pragma error_messages(off,symdeprecated,symdeprecated2)
diag_suppress
like PGI and TI, but the syntax is different. Some of the warning numbers are the same, but I others have diverged: #pragma diag_suppress=Pe1444,Pe1215
#pragma warn(disable:2241)
For most compilers it is often a good idea to check the compiler version before trying to disable it, otherwise you'll just end up triggering another warning. For example, GCC 7 added support for the -Wimplicit-fallthrough
warning, so if you care about GCC before 7 you should do something like
#if defined(__GNUC__) && (__GNUC__ >= 7)
# pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif
For clang and compilers based on clang such as newer versions of XL C/C++ and armclang, you can check to see if the compiler knows about a particular warning using the __has_warning()
macro.
#if __has_warning("-Wimplicit-fallthrough")
# pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#endif
Of course you also have to check to see if the __has_warning()
macro exists:
#if defined(__has_warning)
# if __has_warning("-Wimplicit-fallthrough")
# pragma clang diagnostic ignored "-Wimplicit-fallthrough"
# endif
#endif
You may be tempted to do something like
#if !defined(__has_warning)
# define __has_warning(warning)
#endif
So you can use __has_warning
a bit more easily. Clang even suggests something similar for the __has_builtin()
macro in their manual. Do not do this. Other code may check for __has_warning
and fall back on checking compiler versions if it doesn't exist, and if you define __has_warning
you'll break their code. The right way to do this is to create a macro in your namespace. For example:
#if defined(__has_warning)
# define MY_HAS_WARNING(warning) __has_warning(warning)
#else
# define MY_HAS_WARNING(warning) (0)
#endif
Then you can do stuff like
#if MY_HAS_WARNING(warning)
# pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#elif defined(__GNUC__) && (__GNUC__ >= 7)
# pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif
Many compilers also support a way to push and pop warnings onto a stack. For example, this will disable a warning on GCC for one line of code, then return it to its previous state:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
call_deprecated_function();
#pragma GCC diagnostic pop
Of course there isn't a lot of agreement across compilers about the syntax:
#pragma GCC diagnostic push
/ #pragma GCC diagnostic pop
#pragma clang diagnostic push
/ #pragma diagnostic pop
#pragma warning(push)
/ #pragma warning(pop)
#pragma warning(push)
/ #pragma warning(pop)
#pragma push
/ #pragma pop
#pragma diag_push
/ #pragma diag_pop
#pragma warning(push)
/ #pragma warning(pop)
If memory serves, for some very old versions of GCC (like 3.x, IIRC) the push/pop pragmas had to be outside of the function.
For most compilers it's possible to hide the logic behind macros using _Pragma
, which was introduced in C99. Even in non-C99 mode, most compilers support _Pragma
; the big exception is MSVC, which has its own __pragma
keyword with a different syntax. The standard _Pragma
takes a string, Microsoft's version doesn't:
#if defined(_MSC_VER)
# define PRAGMA_FOO __pragma(foo)
#else
# define PRAGMA_FOO _Pragma("foo")
#endif
PRAGMA_FOO
Is roughly equivalent, once preprocessed, to
#pragma foo
This lets us create macros so we can write code like
MY_DIAGNOSTIC_PUSH
MY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated_function();
MY_DIAGNOSTIC_POP
And hide away all the ugly version checks in the macro definitions.
Now that you understand the mechanics of how to do stuff like this portably while keeping your code clean, you understand what one of my projects, Hedley does. Instead of digging through tons of documentation and/or installing as many versions of as many compilers as you can to test with, you can just include Hedley (it is a single public domain C/C++ header) and be done with it. For example:
#include "hedley.h"
HEDLEY_DIAGNOSTIC_PUSH
HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
call_deprecated();
HEDLEY_DIAGNOSTIC_POP
Will disable the warning about calling a deprecated function on GCC, clang, ICC, PGI, MSVC, TI, IAR, ODS, Pelles, and possibly others (I probably won't bother updating this answer as I update Hedley). And, on compilers which aren't known to work, the macros will be preprocessed away to nothing, so your code will continue to work with any compiler. Of course HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
isn't the only warning Hedley knows about, nor is disabling warnings all Hedley can do, but hopefully you get the idea.
To use requests (or any other blocking libraries) with asyncio, you can use BaseEventLoop.run_in_executor to run a function in another thread and yield from it to get the result. For example:
import asyncio
import requests
@asyncio.coroutine
def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
response1 = yield from future1
response2 = yield from future2
print(response1.text)
print(response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
This will get both responses in parallel.
With python 3.5 you can use the new await
/async
syntax:
import asyncio
import requests
async def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
response1 = await future1
response2 = await future2
print(response1.text)
print(response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
See PEP0492 for more.
Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);
If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
Even I had faced a similar problem. Reason was some garbage character at the beginning of the file.
Fix : Just open the file in a text editor(tested on Sublime text) remove any indent if any in the file and copy paste all the content of the file in a new file and save it. Thats it!. When I ran the new file it ran without any parsing errors.
FOR XLSX USE
SET IN $xlsName name from XLSX with extension. Example: $xlsName = 'teste.xlsx';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
FOR XLS USE
SET IN $xlsName name from XLS with extension. Example: $xlsName = 'teste.xls';
$objPHPExcel = new PHPExcel();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$xlsName.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
cd /driveName driveName:\pathNamw
dir /s /b /a:d>output.txt
will port it to a text file
To change DatePicker
colors (calendar mode) at application level define below properties.
<style name="MyAppTheme" parent="Theme.AppCompat.Light">
<item name="colorAccent">#ff6d00</item>
<item name="colorControlActivated">#33691e</item>
<item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
<item name="colorControlHighlight">#d50000</item>
</style>
See http://www.zoftino.com/android-datepicker-example for other DatePicker
custom styles
Stumbled upon this question/answer while seeking how to compute the row sums of a matrix.
I would just like to add that Matlab's SUM function actually has support for summing for a given dimension, i.e a standard matrix with two dimensions.
So to calculate the column sums do:
colsum = sum(M) % or sum(M, 1)
and for the row sums, simply do
rowsum = sum(M, 2)
My bet is that this is faster than both programming a for loop and converting to cells :)
All this can be found in the matlab help for SUM.
$('input[type=text],select', '.sys');
for looping:
$('input[type=text],select', '.sys').each(function() {
// code
});
We Can override the blue color in to our custom color It works for Internet Explorer, Firefox and Chrome:
By using this below following CSS:
option: checked, option: hover {
Color: #ffffff;
background: #614767 repeat url("data:image/gif;base64,R0lGODlh8ACgAPAAAGFGZQAAACH5BAAAAAAALAAAAADwAKAAAAL+hI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIhRVgEAOw");
}
You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload
event.target
to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
Use a Regular Expression:
string test = "(test)";
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);