You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:
use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;
$domain = (new DomainConfiguration('example.com'))
->setUsername('username') # A separate AD service account used by your app
->setPassword('password')
->setServers(['dc1', 'dc2', 'dc3'])
->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);
if (!$ldap->authenticate($username, $password, $message)) {
echo "Error: $message";
} else {
// Do something...
}
The authenticate call above will:
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
Yes, that's possible, albeit not literally the <td>
, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).
As already explained, this isn't semantically correct. An a
element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:
<td>
<a href="http://example.com">
<div style="height:100%;width:100%">
hello world
</div>
</a>
</td>
PS: it's actually neater to change a
in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)
If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.
<table>
<tr>
<a href="http://example.com"><td width="200">hello world</td></a>
</tr>
</table>
which(df==my.val, arr.ind=TRUE)
COPY table_name FROM 'path/to/data.csv' DELIMITER ',' CSV HEADER;
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.
Here is a quite clean way to end edition with the Return Key or a touch in the background.
In Interface builder, embed your fields in a view of class UIFormView
What does this class :
Here is the code :
Interface
#import <UIKit/UIKit.h>
@interface UIFormView : UIView<UITextFieldDelegate>
-(BOOL)textFieldValueIsValid:(UITextField*)textField;
-(void)endEdit;
@end
Implementation
#import "UIFormView.h"
@implementation UIFormView
{
UITextField* currentEditingTextField;
}
// Automatically register fields
-(void)addSubview:(UIView *)view
{
[super addSubview:view];
if ([view isKindOfClass:[UITextField class]]) {
if ( ![(UITextField*)view delegate] ) [(UITextField*)view setDelegate:self];
}
}
// UITextField Protocol
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
currentEditingTextField = textField;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
currentEditingTextField = NULL;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self endEdit];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([self textFieldValueIsValid:textField]) {
[self endEdit];
return YES;
} else {
return NO;
}
}
// Own functions
-(void)endEdit
{
if (currentEditingTextField) {
[currentEditingTextField endEditing:YES];
currentEditingTextField = NULL;
}
}
// Override this in your subclass to handle eventual values that may prevent validation.
-(BOOL)textFieldValueIsValid:(UITextField*)textField
{
return YES;
}
@end
By subclassing the form and overriding the
textFieldValueIsValid:
method, you
can avoid end of edition if the value is not correct for the given
field.
If a field has a delegate set in Interface Builder, then the form does not change it. I don't see many reasons to set a different delegate to a particular field, but why not…
There is many ways to improve this form view class - Attach a delegate, do some layout, handle when the keyboards covers a field ( using the currentEditingTextField frame ), automatically start edition for the next field, ...
I personally keep it in my framework, and always subclass it to add features, it is quite often useful "as-is".
I hope it will helps. Cheers all
That's a simple one
UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);
From django docs:
render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.
direct_to_template
is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here
Nope, switch statement requires compile time constants. The statement message.Contains("test")
can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.
The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.
To find out if ANY content of the array of needles exists in the string, and quickly return true or false:
$string = 'abcdefg';
if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
echo 'at least one of the needles where found';
};
If, so, please give @Leon credit for that.
To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b'
and 'c'
MUST be present, like you mention as your "for example"
echo 'All the letters are found in the string!';
Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of
$array = array('burger', 'melon', 'cheese', 'milk');
What if all those words MUST be found in the string?
Then you try out some "not accepted answers"
on this page.
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* @param url
* @return String
* @throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* @param URL
* @param paramenter
* @return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}
To remove pods from a project completely you need to install two thing first...those are follows(Assuming you have already cocoa-pods installed in your system.)...
Installation
Cocoapods-Deintegrate Plugin
Use this following command on your terminal to install it.
sudo gem install cocoapods-deintegrate
Cocoapods-Clean Plugin
Use this following command on your terminal to install it.
sudo gem install cocoapods-clean
Usage
First of all goto your project folder by using the as usual command like..
cd (path of the project) //Remove the braces after cd
Now use those two plugins to remove it completely as follows..
Cocoapods-Deintegrate Plugin
Use this following command on your terminal to deintegrate the pods from your project first.
pod deintegrate
Cocoapods-Clean Plugin
After deintegration of pod from your project use this following command on your terminal to clean it completely.
pod clean
After completing the above tasks there should be the Podfile still remaining on your project directory..Just delete that manually or use this following command on the terminal..
rm Podfile
Thats it...Now you have your project free from pods...Cleaned.
Removing Cocoapods from the system.
Any way try to use the following command on your terminal to uninstall/remove the coca-pods from your system.
sudo gem uninstall cocoapods
It will remove the coca-pods automatically.
Thanks. Hope this helped.
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
Set PYTHONPATH
environment variable in root project directory.
Considering UNIX-like:
export PYTHONPATH=.
Maximum is 2097151, If you try set more error occurred.
this solved my problem
android:adjustViewBounds="true"
android:scaleType="fitXY"
Descending:
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});
We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).
My fingers have memorized our process:
git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>
A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
Try using the wget library for python. You can find the documentation for it here.
import wget
link = 'ftp://example.com/foo.txt'
wget.download(link)
I had same issue with F-secure, DeepGuard was blocking the Docker service. My solution was:
Open F-secure client and click "Tasks"
Choose "Allow a program to start"
Choose from list "com.docker.service" and press "Remove"
After that restart Docker client and try to apply for file share.
Also very good troubleshoot guide here: Error: A firewall is blocking file sharing between Windows and the containers
I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.
Inside "page1.php" or "page1.html":
// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a>
//or as I needed it.
<a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>
Inside "page2c.php":
<?php
// Retrieve the URL variables (using PHP).
$num = $_GET['myNumber'];
$fruit = $_GET['myFruit'];
echo "Number: ".$num." Fruit: ".$fruit;
?>
Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.
Using urllib, you can get this done instantly.
import urllib.request
opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(URL, "images/0.jpg")
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
The documentation for this is good if not a little difficult to find.
Facebook Graph API - Page Tokens
After initializing node's fbgraph, you can run:
var facebookAccountID = yourAccountIdHere
graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
console.log(res);
});
and receive a JSON response with the token you want to grab, located at:
res.data[0].access_token
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
1. See information about the SQL server
tsql -LH SERVER_IP_ADDRESS
locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query
2. Set your freetds.conf
tsql -C
freetds.conf directory: /usr/local/etc
[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2
3 Try
tsql -S TITAN -U user -P password
OR
'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',
See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)
If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.
You can use a switch:
switch (foobar) {
case foo:
case bar:
// do something
}
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
For me, the server was expect HTTPS requests, but I didn't specify that in the URL. The hook would reach the server, but the body would be empty.
The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Which I got from https://stackoverflow.com/a/8412989/1232175.
A simple server side include directive to include another file found in the same folder looks like this:
<!--#include virtual="a.html" -->
Create a new addHostEntry.bat file with the following content in it:
@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.
:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"
IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop
:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END
:ACCEPTED
SET NEWLINE=^& echo.
ECHO Carrying out requested modifications to your HOSTS file
FIND /C /I "mydomain.com" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1 mydomain.com>>%WINDIR%\system32\drivers\etc\hosts
ECHO Finished
GOTO END
:END
ECHO.
ping -n 11 127.0.0.1 > nul
EXIT
Hope this helps!
just define a destructor inside a class and execute your code with both syntax
delete pointer
delete [] pointer
according to the output u can find the solutions
Try choosing project -> clean. A simple clean may fix it up.
The accepted answer suggests to modify the raw data for presentation purposes, something you generally do not want. Imagine you need to make further analyses with these columns and you need the precision you lost with rounding.
You can modify the formatting of individual columns in data frames, in your case:
output = df.to_string(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
print(output)
For your information '{:,.2%}'.format(0.214)
yields 21.40%
, so no need for multiplying by 100.
You don't have a nice HTML table anymore but a text representation. If you need to stay with HTML use the to_html
function instead.
from IPython.core.display import display, HTML
output = df.to_html(formatters={
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format
})
display(HTML(output))
Update
As of pandas 0.17.1, life got easier and we can get a beautiful html table right away:
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> **$dte = Get-Date**
PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
PS C:\Windows\system32> **$PastDueDate**
Sunday, March 1, 2020 12:00:00 AM
PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
PS C:\Windows\system32> **$NewDateFormat 03012020**
There're few additional methods available as well e.g.: $dte.AddDays(-45).Day
if you use docker-compose, maybe it can work:
iptables -I INPUT ! -i eth0 -p tcp --dport 8001 -j ACCEPT
the eth0
is your network interface that connect internet, and 8081
the host server port
the best way for iptables rule is iptables TRACE
I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.
The :query_string_normalizer
option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.
If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.
Any double quote characters in the value should be escaped with another double quote.
If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.
Try CSS Generator.
You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:
text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);
You're looking for dir to return the directory contents.
To loop over the results, you can simply do the following:
dirlist = dir('.');
for i = 1:length(dirlist)
dirlist(i)
end
This should give you output in the following format, e.g.:
name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []
You typically want to render templates like this:
app.get('/', function(req, res){
res.render('index.ejs');
});
However you can also deliver static content - to do so use:
app.use(express.static(__dirname + '/public'));
Now everything in the /public
directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm
in the public folder if will be available by visiting /default.htm
Take a look through the express API and Connect Static middleware docs for more info.
As a recorded macro.
range("A:A, B:B, D:D, E:E, G:G, H:H").select
limit
option, e.g.:
svn log --limit 4
svn log -l 4
Only the last 4 entries
There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc
The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.
I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.
Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.
// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots
// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');
// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';
// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'
// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />
For e.g. here's a full height screenshot of this very page:
In general, a developer should never throw a NullPointerException. This exception is thrown by the runtime when code attempts to dereference a variable who's value is null. Therefore, if your method wants to explicitly disallow null, as opposed to just happening to have a null value raise a NullPointerException, you should throw an IllegalArgumentException.
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
This is what I use to clone a table structure (columns only)...
SELECT TOP 0 *
INTO NewTable
FROM TableStructureIWishToClone
Instead of trying to modify the $scope
within the service, you can implement a $watch
within your controller to watch a property on your service for changes and then update a property on the $scope
. Here is an example you might try in a controller:
angular.module('cfd')
.controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.students = null;
(function () {
$scope.$watch(function () {
return StudentService.students;
}, function (newVal, oldVal) {
if ( newValue !== oldValue ) {
$scope.students = newVal;
}
});
}());
}]);
One thing to note is that within your service, in order for the students
property to be visible, it needs to be on the Service object or this
like so:
this.students = $http.get(path).then(function (resp) {
return resp.data;
});
From command prompt as admin run:
netsh interface ip delete destinationcache
Works on Win7.
CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).
Now we can do this with:
<style type="text/css" media="print">
@page {
size: auto; /* auto is the initial value */
margin: 0; /* this affects the margin in the printer settings */
}
</style>
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
Yes, you can like this:
mailto: [email protected]?subject=something
Google has introduced in-app updates API
The API currently supports two flows:
class Countries < ActiveRecord::Base
self.table_name = "cc"
end
class Countries < ActiveRecord::Base
self.set_table_name "cc"
...
end
You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add
.
Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d
.
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
So you want to avoid loops?
Here you have it:
public static String repeat(String s, int times) {
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
(of course I know this is ugly and inefficient, but it doesn't have loops :-p)
You want it simpler and prettier? use jython:
s * 3
Edit: let's optimize it a little bit :-D
public static String repeat(String s, int times) {
if (times <= 0) return "";
else if (times % 2 == 0) return repeat(s+s, times/2);
else return s + repeat(s+s, times/2);
}
Edit2: I've done a quick and dirty benchmark for the 4 main alternatives, but I don't have time to run it several times to get the means and plot the times for several inputs... So here's the code if anybody wants to try it:
public class Repeat {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String s = args[1];
int l = s.length();
long start, end;
start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
if(repeatLog2(s,i).length()!=i*l) throw new RuntimeException();
}
end = System.currentTimeMillis();
System.out.println("RecLog2Concat: " + (end-start) + "ms");
start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
if(repeatR(s,i).length()!=i*l) throw new RuntimeException();
}
end = System.currentTimeMillis();
System.out.println("RecLinConcat: " + (end-start) + "ms");
start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
if(repeatIc(s,i).length()!=i*l) throw new RuntimeException();
}
end = System.currentTimeMillis();
System.out.println("IterConcat: " + (end-start) + "ms");
start = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
if(repeatSb(s,i).length()!=i*l) throw new RuntimeException();
}
end = System.currentTimeMillis();
System.out.println("IterStrB: " + (end-start) + "ms");
}
public static String repeatLog2(String s, int times) {
if (times <= 0) {
return "";
}
else if (times % 2 == 0) {
return repeatLog2(s+s, times/2);
}
else {
return s + repeatLog2(s+s, times/2);
}
}
public static String repeatR(String s, int times) {
if (times <= 0) {
return "";
}
else {
return s + repeatR(s, times-1);
}
}
public static String repeatIc(String s, int times) {
String tmp = "";
for (int i = 0; i < times; i++) {
tmp += s;
}
return tmp;
}
public static String repeatSb(String s, int n) {
final StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
}
It takes 2 arguments, the first is the number of iterations (each function run with repeat times arg from 1..n) and the second is the string to repeat.
So far, a quick inspection of the times running with different inputs leaves the ranking something like this (better to worse):
I wouldn't ever guessed that the recursive function was faster than the for
loop :-o
Have fun(ctional xD).
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
Contents of table cell, variable height, could be more than 60px;
<div style="position: absolute; bottom: 0px;">
Notice
</div>
Seems user has declined the permission and app tries to write to external disk, causing error.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Check https://developer.android.com/training/permissions/requesting.html
This video will give you a better idea about UX, handling Runtime permissions https://www.youtube.com/watch?v=iZqDdvhTZj0
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c+=1
set OUTPUT_FILE_NAME=output_%c%.txt
echo Output file is %OUTPUT_FILE_NAME%
echo %%i, %c%
)
You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.
For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.
In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2);
operation.
In regards to multiple arrays in an object. For instance, you want to record modules for different courses
var course = {
InfoTech:["Information Systems","Internet Programming","Software Eng"],
BusComm:["Commercial Law","Accounting","Financial Mng"],
Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);
I faced this problem once. It was because i was still developing the interface that uses WCF service. I configured test application and continued development. Then in development, i changed some of the services' namespaces. So i double checked "system.serviceModel -> client -> endpoint -> contract" in web.config to match WCF class. Then problem is solved.
If you wanted to change the title from a child view controller of a Page View Controller that's embedded in a navigation controller, it would look like this:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.parent?.title = "some title"
}
This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/
I am the developer of SymbolHound.
You should add that you have to add an extra ' to escape an exising ' in SQL Server:
smith's -> smith''s
Use above method for pretty print and then add this in any div by using jquery text() method. for example id of div is xmldiv
then use :
$("#xmldiv").text(formatXml(youXmlString));
Anon's answer works great for me, but I just need to modify the statement for days
from:
days = dates - dates.astype('datetime64[M]') + 1
to:
days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1
JDK 8 makes this easy and elegant:
public class AgeCalculator {
public static int calculateAge(LocalDate birthDate, LocalDate currentDate) {
if ((birthDate != null) && (currentDate != null)) {
return Period.between(birthDate, currentDate).getYears();
} else {
return 0;
}
}
}
A JUnit test to demonstrate its use:
public class AgeCalculatorTest {
@Test
public void testCalculateAge_Success() {
// setup
LocalDate birthDate = LocalDate.of(1961, 5, 17);
// exercise
int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12));
// assert
Assert.assertEquals(55, actual);
}
}
Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.
Up to Xcode 5 the preprocessor directive #pragma mark
existed.
From Xcode 6 on, you have to use // MARK:
These preprocessor features allow to bring some structure to the function drop down box of the source code editor.
some examples :
// MARK:
-> will be preceded by a horizontal divider
// MARK: your text goes here
-> puts 'your text goes here' in bold in the drop down list
// MARK: - your text goes here
-> puts 'your text goes here' in bold in the drop down list, preceded by a horizontal divider
update : added screenshot 'cause some people still seem to have issues with this :
I'd this issue on Linux Mint (Maya) 13, And I fixed it by Installing postgresql and postgresql-server :
apt-get install postgresql-9.1
sudo apt-get install postgresql-server-dev-9.1
I did another thing: delete a sheet only if it's exists - not to get an error if it doesn't:
Excel.DisplayAlerts = False
Dim WS
For Each WS In Excel.Worksheets
If WS.name = "Sheet2" Then
Excel.sheets("Sheet2").Delete
Exit For
End If
Next
Excel.DisplayAlerts = True
In vba the function is MOD. e.g
5 MOD 2
Here is a useful link.
ARIA does not change functionality, it only changes the presented roles/properties to screen reader users. WebAIM’s WAVE toolbar identifies ARIA roles on the page.
Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:
Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state
(I spent a few minutes working this out, so hopefully this speeds someone else up),
- stat:
path: "/etc/nologin"
register: p
- name: create fake 'nologin' shell
file:
path: "/etc/nologin"
owner: root
group: sys
mode: 0555
state: '{{ "file" if p.stat.exists else "touch" }}'
pd.read_excel(file_name)
sometimes this code gives an error for xlsx files as: XLRDError:Excel xlsx file; not supported
instead , you can use openpyxl
engine to read excel file.
df_samples = pd.read_excel(r'filename.xlsx', engine='openpyxl')
It worked for me
I had the same issue I have resolved by adding a media query for @screen-xs-min in less version under Modals.less
@media (max-width: @screen-xs-min) {
.modal-xs { width: @modal-sm; }
}
There are two options to load animated gifs into our Android apps
1)Using Glide to load the gif into an ImageView
.
String urlGif = "https://cdn.dribbble.com/users/263558/screenshots/1337078/dvsd.gif";
//add Glide implementation into the build.gradle file.
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Uri uri = Uri.parse(urlGif);
Glide.with(getApplicationContext()).load(uri).into(imageView);
2) Using an html to load the gif into a WebView
Create the html with the address to the .gif file:
<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>
store this file into the assets directory:
The load this html into the WebView of your application:
WebView webView = (WebView)findViewById(R.id.webView);
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/html/webpage_gif.html");
Heres is a complete example of this two options.
Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).
You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).
Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of #ifdefs for various OSes.
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
There are many cases in which gaps are desired in a chart.
I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.
Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.
The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.
Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).
If you do a straight git pull
then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}
. This means that you can do:
git diff HEAD@{1}
However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch
and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:
git fetch
git log HEAD..origin/master
# looks good, lets merge
git merge origin/master
For me, using Anaconda Prompt instead of cmd or PowerShell is the key.
In Anaconda Prompt, all I need to do is activate XXX
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
you can use crypto-js javaScript library of crypto standards, there is easiest way to generate sha256
or sha512
const SHA256 = require("crypto-js/sha256");
const SHA512 = require("crypto-js/sha512");
let password = "hello"
let hash_256 = SHA256 (password).toString();
let hash_512 = SHA512 (password).toString();
you just need to divide the Date Time stamp by 1000 like:
var a = 1437203995000;
a = (a)/1000;
Here's an implementation that uses a lockfile and echoes a PID into it. This serves as a protection if the process is killed before removing the pidfile:
LOCKFILE=/tmp/lock.txt
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
echo "already running"
exit
fi
# make sure the lockfile is removed when we exit and then claim it
trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT
echo $$ > ${LOCKFILE}
# do stuff
sleep 1000
rm -f ${LOCKFILE}
The trick here is the kill -0
which doesn't deliver any signal but just checks if a process with the given PID exists. Also the call to trap
will ensure that the lockfile is removed even when your process is killed (except kill -9
).
Views are not currently supported by Entity Framework Core. See https://github.com/aspnet/EntityFramework/issues/827.
That said, you can trick EF into using a view by mapping your entity to the view as if it were a table. This approach comes with limitations. e.g. you can't use migrations, you need to manually specific a key for EF to use, and some queries may not work correctly. To get around this last part, you can write SQL queries by hand
context.Images.FromSql("SELECT * FROM dbo.ImageView")
The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.
UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
Add reference to Microsoft.VisualBasic
and use this function:
string response = Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);
The last 2 number is an X/Y position to display the input dialog.
In Java 8, it's now as simple as:
movieItems.sort(Comparator.comparing(Movie::getDate));
Assuming your row number is in B1
, you can use INDIRECT
:
=INDIRECT("A" & B1)
This takes a cell reference as a string (in this case, the concatenation of A
and the value of B1
- 5), and returns the value at that cell.
You can use the folowing code:
def float_range(initVal, itemCount, step):
for x in xrange(itemCount):
yield initVal
initVal += step
[x for x in float_range(1, 3, 0.1)]
Have you seen this one? From http://www.aspspider.com/resources/Resource510.aspx:
public DataTable Import(String path)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
object rowIndex = 2;
DataTable dt = new DataTable();
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Mobile");
dt.Columns.Add("Landline");
dt.Columns.Add("Email");
dt.Columns.Add("ID");
DataRow row;
while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
{
row = dt.NewRow();
row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2);
row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 2]).Value2);
row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 3]).Value2);
row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 4]).Value2);
row[4] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 5]).Value2);
index++;
rowIndex = 2 + index;
dt.Rows.Add(row);
}
app.Workbooks.Close();
return dt;
}
You can use the angular-cli as the comments in @brendon's answer suggest.
You might also want to try:
ng g class modelsDirectoy/modelName --type=model
/* will create
src/app/modelsDirectoy
+-- modelName.model.ts
+-- ...
...
*/
Bear in mind:
ng g class
!== ng g c
However, you can use ng g cl
as shortcut depending on your angular-cli version.
With the latest update to the extension all you need to do is just specify the "python.pythonPath"
as follows.
The values for "python.autoComplete.extraPaths"
will be determined during runtime, but you are still free to specify custom paths in there.
Please, remember to restart Visual Studio Code once the necessary changes have been made.
{
"editor.rulers": [80,100],
"python.pythonPath":"~/dev/venvs/proj/bin/python"
}
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
In C99(ISO/IEC 9899:TC3)
which seems absent from this discussion thus far the following steteents are made regarding order of evaluaiton.
[...]the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. (Section 6.5 pp 67)
The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior[sic] is undefined.(Section 6.5.16 pp 91)
You can use
app:cardBackgroundColor="@color/red"
or
android:backgroundTint="@color/red"
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Just an update since I was trying all this stuff today in response to a customer issue
Easiest way would be to use the serialize
function.
It serializes any variable for storage or transfer. You can read about it in the php manual - serialize
The variable can be restored by using unserialize
So in the passing to the URL you use:
$url = urlencode(serialize($array))
and to restore the variable you use
$var = unserialize(urldecode($_GET['array']))
Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.
Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.
The best way to get the text value from a <label>
element is as follows.
if you will be getting element ids frequently it's best to have a function to return the ids:
function id(e){return document.getElementById(e)}
Assume the following structure:
<label for='phone'>Phone number</label>
<input type='text' id='phone' placeholder='Mobile or landline numbers...'>
This code will extract the text value 'Phone number' from the<label>:
var text = id('phone').previousElementSibling.innerHTML;
This code works on all browsers, and you don't have to give each<label>
element a unique id.
You could use FileAPI, but it's pretty much unsupported.
you can use the following to find the posted data.
data = json.loads(request.raw_post_data)
if the document.domain property is set in the parent page, Internet Explorer gives me an "Access is denied"
Sigh. Yeah, it's an IE issue (bug? difficult to say as there is no documented standard for this kind of unpleasantness). When you create a srcless iframe it receives a document.domain
from the parent document's location.host
instead of its document.domain
. At that point you've pretty much lost as you can't change it.
A horrendous workaround is to set src
to a javascript: URL (urgh!):
iframe.src= "javascript:'<html><body><p>Hello<\/p><script>do things;<\/script>'";
But for some reason, such a document is unable to set its own document.domain
from script in IE (good old “unspecified error”), so you can't use that to regain a bridge between the parent(*). You could use it to write the whole document HTML, assuming the widget doesn't need to talk to its parent document once it's instantiated.
However iframe JavaScript URLs don't work in Safari, so you'd still need some kind of browser-sniffing to choose which method to use.
*: For some other reason, you can, in IE, set document.domain
from a second document, document.written by the first document. So this works:
if (isIE)
iframe.src= "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\""+document.domain+"\\\";<\\\\/script>\\');document.close();};<\/script>'";
At this point the hideousness level is too high for me, I'm out. I'd do the external HTML like David said.
var find = function(root, path) {
var segments = path.split('.'),
cursor = root,
target;
for (var i = 0; i < segments.length; ++i) {
target = cursor[segments[i]];
if (typeof target == "undefined") return void 0;
cursor = target;
}
return cursor;
};
var obj = { a: { b: '1', c: '2' } }
find(obj, "a.b"); // 1
var set = function (root, path, value) {
var segments = path.split('.'),
cursor = root,
target;
for (var i = 0; i < segments.length - 1; ++i) {
cursor = cursor[segments[i]] || { };
}
cursor[segments[segments.length - 1]] = value;
};
set(obj, "a.k", function () { console.log("hello world"); });
find(obj, "a.k")(); // hello world
AFAIK there's no built in method in the framework that will allow you to do this. You could check this post for a suggestion on determining framework version by reading windows registry values.
If you are on Linux:
git fetch
for file in `git diff origin/master..HEAD --name-only`; do rm -f "$file"; done
git pull
The for loop will delete all tracked files which are changed in the local repo, so git pull
will work without any problems.
The nicest thing about this is that only the tracked files will be overwritten by the files in the repo, all other files will be left untouched.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
You can make PHP and JavaScript work together by generating the following line in each page template:
<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>
Then you can refer to document.mybaseurl anywhere in your JavaScript. This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.
If you are using Eclipse and this problem appeared out of nowhere after everything worked fine beforehand, try going to Project - Clean - Clean
.
There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:
From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
pip can install a package ignoring the cache, like this
pip --no-cache-dir install scipy
Simple, without any other API:
To add 8 days:
Date today=new Date();
long ltime=today.getTime()+8*24*60*60*1000;
Date today8=new Date(ltime);
Sounds like you should stay with the defaults ;-)
Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.
See here how to configure...
Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html
Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html
Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html
Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html
You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.
In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:
const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
// ...
new FileManagerPlugin({
onEnd: {
copy: [{
source: './dist/*.*',
destination: './public/',
}],
},
}),
],
The following will order your data depending on both column in descending order.
ORDER BY article_rating DESC, article_time DESC
I'm having a similar issue, code got really unreadable using multilines, I came out with something like
print("""aaaa
""" """bbb
""")
yes, at beginning could look terrible but the embedded syntax was quite complex and adding something at the end (like '\n"') was not a solution
You got an answer but in your case you can use
return empty($input);
or
return is_string($input);
just give rowId and type of data that is going to be update in ContentValues.
public void updateStatus(String id , int status){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("status", status);
db.update(TableName, data, "columnName" + " = "+id , null);
}
for new version of Wamp
<VirtualHost *:80>
ServerName domain.local
DocumentRoot C:/wamp/www/domain/
<Directory "C:/wamp/www/domain/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
You can accomplish what you want with either:
docker run -t -d <image-name>
or
docker run -i -d <image-name>
or
docker run -it -d <image-name>
The command parameter as suggested by other answers (i.e. tail -f /dev/null) is completely optional, and is NOT required to get your container to stay running in the background.
Also note the Docker documentation suggests that combining -i and -t options will cause it to behave like a shell.
See:
You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.
I found a solution wich is to do:
<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>
It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...
Try this:
git fetch --all
git reset --hard origin/master
Explanation:
git fetch
downloads the latest from remote without trying to merge or rebase anything.
Please let me know if you have any questions!
Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check
Languages -> Visual C++ -> Common tools for Visual C++
Windows and web development -> Tools for universal windows apps -> Tools (1.4.1)
and Windows 10 SDK ([version])
Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])
and install. Then right click on solution -> Re-target and it will compile
Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)
.profile-header > div {
display: inline-block;
vertical-align: bottom;
float: none;
margin: -2px;
}
.profile-header {
margin-bottom:20px;
border:2px solid green;
display: table-cell;
}
.profile-pic {
height:300px;
border:2px solid red;
}
.profile-about {
border:2px solid blue;
}
.profile-about2 {
border:2px solid pink;
}
Example here: http://www.bootply.com/125740#
The alpha channel defines the transparency value of a color, so any color is 100% transparent as long as the alpha value is 0. Typically this four-channel color type is known as RGBA.
You can specify RGBA in CSS like so:
div {
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
Note that not all browsers support RGBA, in which case you can specify a fallback:
div {
background: rgb(200, 54, 54); /* fallback */
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
More information regarding browser support and workarounds can be found here.
This should do it:
[^a-zA-Z0-9]
Basically it matches all non-alphanumeric characters.
Try restoring the default options in 'Windows > Preferences > Java > Editor > Content Assist > Advanced
'
An example of the kind of data you see in this preference screen, however not necessarily what you currently have.
(From Vadim in this blog post " Content Assist Duplicates in Eclipse (Mylyn)":
if have duplicate Mylyn entries, uncheck the duplicate entries that do not contain "(Mylyn)
" in their name)
The Eclipse help page defines the default list to restore:
Select the proposal kinds contained in the 'default' content assist list:
- Other Java Proposals,
- SWT Template Proposals,
- Template Proposals,
- Type Proposals
If you're not concerned about the exact formatting however you do want something simple but without the line breaks of print_r
you can also use json_encode($value)
for a quick and simple formatted output. (note it works well on other data types too)
$str = json_encode($arr);
//output...
[{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]
For a matrix you can use this:
[M,I] = max(A(:))
I is the index of A(:) containing the largest element.
Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.
[I_row, I_col] = ind2sub(size(A),I)
Check if there is a file called maintenance.flag and if so delete it.
Magento 1.x : maintenance.flag file is in : magento root directory
Magento 2.x : maintenance.flag file is in : var folder
When Magento is performing certain tasks it temporarily creates this file. Magento checks for its existence and if it's there will send users to the page you described.
It's supposed to automatically delete this file when done processing whatever task it was doing, but I've experienced occasions where something went wrong and it failed to delete it.
You can use str.contains
alone with a regex pattern using OR (|)
:
s[s.str.contains('og|at')]
Or you could add the series to a dataframe
then use str.contains
:
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
Output:
0 cat
1 hat
2 dog
3 fog
alternatively you can perform a fast export without using Office dll, as Excel can parse csv files without problems.
Doing something like this (for less than 65.536 rows with titles):
Try
If (p_oGrid.RowCount = 0) Then
MsgBox("No data", MsgBoxStyle.Information, "App")
Exit Sub
End If
Cursor.Current = Cursors.WaitCursor
Dim sText As New System.Text.StringBuilder
Dim sTmp As String
Dim aVisibleData As New List(Of String)
For iAuxRow As Integer = 0 To p_oGrid.Columns.Count - 1
If p_oGrid.Columns(iAuxRow).Visible Then
aVisibleData.Add(p_oGrid.Columns(iAuxRow).Name)
sText.Append(p_oGrid.Columns(iAuxRow).HeaderText.ToUpper)
sText.Append(";")
End If
Next
sText.AppendLine()
For iAuxRow As Integer = 0 To p_oGrid.RowCount - 1
Dim oRow As DataGridViewRow = p_oGrid.Rows(iAuxRow)
For Each sCol As String In aVisibleData
Dim sVal As String
sVal = oRow.Cells(sCol).Value.ToString()
sText.Append(sVal.Replace(";", ",").Replace(vbCrLf, " ; "))
sText.Append(";")
Next
sText.AppendLine()
Next
sTmp = IO.Path.GetTempFileName & ".csv"
IO.File.WriteAllText(sTmp, sText.ToString, System.Text.Encoding.UTF8)
sText = Nothing
Process.Start(sTmp)
Catch ex As Exception
process_error(ex)
Finally
Cursor.Current = Cursors.Default
End Try
You can get this error even with all the correct MapRoutes in your area registration. Try adding this line to your controller action:
If Not ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
ControllerContext.RouteData.DataTokens.Add("area", "MyAreaName")
End If
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.
Rounding a number
towards 0
can be done by subtracting its signed fractional part number % 1
:
rounded = number - number % 1;
Like Math.floor
(rounds towards -Infinity
) this method is perfectly accurate.
There are differences in the handling of -0
, +Infinity
and -Infinity
though:
Math.floor(-0) => -0
-0 - -0 % 1 => +0
Math.floor(Infinity) => Infinity
Infinity - Infinity % 1 => NaN
Math.floor(-Infinity) => -Infinity
-Infinity - -Infinity % 1 => NaN
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>
in this case as question Josh Stodola answer is correct Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
but if element have multiple classes like this
<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>
then Josh Stodola's solution will do not work
for this have to do some thing like this
$('.some-parent-class div').filter(function () {
return this.className.match(/\bapple-/);// this is for start with
//return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");
may be it helps some one else thanks
Seeing as everyone else has already listed most of the other ways to say not equal I will just add:
if not (1) == (1): # This will eval true then false
# (ie: 1 == 1 is true but the opposite(not) is false)
print "the world is ending" # This will only run on a if true
elif (1+1) != (2): #second if
print "the world is ending"
# This will only run if the first if is false and the second if is true
else: # this will only run if the if both if's are false
print "you are good for another day"
in this case it is simple switching the check of positive == (true) to negative and vise versa...
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index
.
The second problem you have is that you don't have the variable index
.
What you can do is a loop with 12 iterations to fill all your arrays. (and index
will be your iteration variable)
1.Rename the old UDT,
2.Execute query ,
3.Drop the old UDT.
I had this concern when working on a Rails application with Docker.
My most preferred approach is to generally not use quotes. This includes not using quotes for:
${RAILS_ENV}
postgres-log:/var/log/postgresql
I, however, use double-quotes for integer
values that need to be converted to strings like:
version: "3.8"
"8080:8080"
However, for special cases like booleans
, floats
, integers
, and other cases, where using double-quotes for the entry values could be interpreted as strings
, please do not use double-quotes.
Here's a sample docker-compose.yml
file to explain this concept:
version: "3"
services:
traefik:
image: traefik:v2.2.1
command:
- --api.insecure=true # Don't do that in production
- --providers.docker=true
- --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
That's all.
I hope this helps
A 'button' is just that, a button, to which you can add additional functionality using Javascript. A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript).
require
is part of the Asynchronous Module Definition (AMD) API.
A browser implementation can be found via require.js and native support can be found in node.js.
The documentation for the library you are using should tell you what you need to use it, I suspect that it is intended to run under Node.js and not in browsers.
since python 3.5 you can use *
iterable unpacking operator:
user_list = [*your_iterator]
but the pythonic way to do it is:
user_list = list(your_iterator)
Set the application pool to 2.0, I did it and worked.
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
month Integer value representing the month, beginning with 0 for January to 11 for December.
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
The Uri class is generally your best bet for manipulating Urls.
In ExtJs, you can use
xtype: 'image'
to render a image.
Here is a fiddle showing rendering of binary data with extjs.
atob -- > converts ascii to binary
btoa -- > converts binary to ascii
Ext.application({
name: 'Fiddle',
launch: function () {
var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));
Ext.create("Ext.panel.Panel", {
title: "Test",
renderTo: Ext.getBody(),
height: 400,
items: [{
xtype: 'image',
width: 100,
height: 100,
src: srcBase64
}]
})
}
});
As noted by S.Lott,
Variable set outside init belong to the class. They're shared by all instances.
Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.
However, Note that class variables can be accessed via self.<var> until they are masked by an object variable with a similar name This means that reading self.<var> before assigning it a value will return the value of Class.<var> but afterwards it will return obj.<var> . Here is an example
In [20]: class MyClass:
...: elem = 123
...:
...: def update(self,i):
...: self.elem=i
...: def print(self):
...: print (MyClass.elem, self.elem)
...:
...: c1 = MyClass()
...: c2 = MyClass()
...: c1.print()
...: c2.print()
123 123
123 123
In [21]: c1.update(1)
...: c2.update(42)
...: c1.print()
...: c2.print()
123 1
123 42
In [22]: MyClass.elem=22
...: c1.print()
...: c2.print()
22 1
22 42
Second note: Consider slots. They may offer a better way to implement object variables.
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause()
is called when another activity gains focus, and onStop()
is called when the activity is no longer visible.
From what I have learned yet, you can call finish()
only from the activity which is active and/or has the focus. If you're calling finish()
from the onPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.
When you're calling finish()
from onStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.
When you press the back
button, onStop()
is called.
Most probably, Android will automatically do for you what you are currently wanting to do.
git branch | grep "*" | sed "s/* //" | awk '{printf $0}' | pbcopy
To directly copy the result to the pasteboard. Thanks to @olivier-refalo for the start…
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
Check the .gitignore
file, if the subdirectory is ignored.
Then try again
git add --all
git commit -am "<commit message>"
git push
With Swift 1.2 (and maybe earlier) you now need to use:
let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, combine: { max($0, $1) })
For working with Double values I used something like this:
let nums = [1.3, 6.2, 3.6, 9.7, 4.9, 6.3];
let numMax = nums.reduce(-Double.infinity, combine: { max($0, $1) })
The relationship Room
to Class
is considered weak (non-identifying) because the primary key components CID
and DATE
of entity Class
doesn't contain the primary key RID
of entity Room
(in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).
However, for instance, in the case of the relationship Class
and Class_Ins
we see that is a strong (identifying) relationship because the primary key components EmpID
and CID
and DATE
of Class_Ins
contains a component of the primary key Class
(in this case it contains both components CID
and DATE
).
Using FileProvider
from support library you have to manually grant and revoke permissions(at runtime) for other apps to read specific Uri. Use Context.grantUriPermission and Context.revokeUriPermission methods.
For example:
//grant permision for app with package "packegeName", eg. before starting other app via intent
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//revoke permisions
context.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
As a last resort, if you can't provide package name you can grant the permission to all apps that can handle specific intent:
//grant permisions for all apps that can handle given intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
...
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
Alternative method according to the documentation:
- Put the content URI in an Intent by calling setData().
- Next, call the method Intent.setFlags() with either FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION or both.
Finally, send the Intent to another app. Most often, you do this by calling setResult().
Permissions granted in an Intent remain in effect while the stack of the receiving Activity is active. When the stack finishes, the
permissions are automatically removed. Permissions granted to one
Activity in a client app are automatically extended to other
components of that app.
Btw. if you need to, you can copy source of FileProvider and change attachInfo
method to prevent provider from checking if it is exported.
Simple, use static.
In activity you have the method you want to call:
private static String name = "Robert";
...
public static String getData() {
return name;
}
And in your activity where you make the call:
private static String name;
...
name = SplashActivity.getData();
The scenario I most find myself using it is for defaulting values and especially in returns
return someIndex < maxIndex ? someIndex : maxIndex;
Those are really the only places I find it nice, but for them I do.
Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:
bool hey = whatever < whatever_else ? true : false;
Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:
bool hey = (whatever < whatever_else);
Following code worked for me:
git fetch
git checkout <branch from which file needs to be fetched> <filepath>
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
The error means the OS of the listening socket recognized the inbound connection request but chose to intentionally reject it.
Assuming an intermediate firewall is not getting in the way, there are only two reasons (that I know of) for the OS to reject an inbound connection request. One reason has already been mentioned several times - the listening port being connected to is not open.
There is another reason that has not been mentioned yet - the listening port is actually open and actively being used, but its backlog of queued inbound connection requests has reached its maximum so there is no room available for the inbound connection request to be queued at that moment. The server code has not called accept() enough times yet to finish clearing out available slots for new queue items.
Wait a moment or so and try the connection again. Unfortunately, there is no way to differentiate between "the port is not open at all" and "the port is open but too busy right now". They both use the same generic error code.
Try replacing the appropriate lines with:
myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";
Your code is incorrect because the sub-arrays have a length of y
, and indexing starts at 0. So setting to myStringArray[0][y]
or myStringArray[0][x]
will fail because the indices x
and y
are out of bounds.
String[][] myStringArray = new String [x][y];
is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.
# gen the pub and priv keys
# use "strange" naming convention, because those WILL BE more than 10 ...
ssh-keygen -t rsa -b 4096 -C "[email protected]" -f ~/.ssh/[email protected]@`hostname -s`
# set the git alias ONLY this shell session
alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/[email protected].`hostname -s`" git'
# who did what when and why
git log --pretty --format='%h %ai %<(15)%ae ::: %s'
# set the git msg
export git_msg='issue-123 my important commit msg'
# add all files ( danger !!! ) and commit them with the msg
git add --all ; git commit -m "$git_msg" --author "Me <[email protected]"
# finally
git push
In this case I like to use the exists?
method provided by ActiveRecord:
Business.exists? user_id: current_user.id
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
With EL 2 (Expression Language 2) you can use this type of construct for your question:
#{formatBean.format(myBean.birthdate)}
Or you can add an alternate getter in your bean resulting in
#{myBean.birthdateString}
where getBirthdateString returns the proper text representation. Remember to annotate the get method as @Transient if it is an Entity.
Ignore XAK. Do not explore any private methods if you want your app to have the chance of being accepted by apple.
This is easiest if you are using Interface Builder. You would add a UIView at the top of the view (where the images will go), then add your tableview below that. IB should size it accordingly; that is, the top of the tableview touches the bottom of the UIView you've just added and it's height covers the rest of the screen.
The thinking here is that if that UIView is not actually part of the table view, it will not scroll with the tableview. i.e. ignore the tableview header.
If you're not using interface builder, it's a little more complicated because you've got to get the positioning and height correct for the tableview.
To my knowledge, no.
Circumstantial indications from $LC_CTYPE
, locale
and such might seem alluring, but these are completely separated from the encoding the terminal application (actually an emulator) happens to be using when displaying characters on the screen.
They only way to detect encoding for sure is to output something only present in the encoding, e.g. ä
, take a screenshot, analyze that image and check if the output character is correct.
So no, it's not possible, sadly.
I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.
You can access this by
I have used the same instructions Stefan
used, taken from Tortoise website.
But it's important to click COMMIT right after. I was getting crazy until I realized that.
If you need to make an older revision your head revision do the following:
Select the file or folder in which you need to revert the changes. If you want to revert all changes, this should be the top level folder.
Select TortoiseSVN ? Show Log to display a list of revisions. You may need to use Show All or Next 100 to show the revision(s) you are interested in.
Right click on the selected revision, then select Context Menu ? Revert to this revision. This will discard all changes after the selected revision.
Make a commit.
Set Clickable as false and change the backgroung color as:
callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
Way more elegant solution than $parent.$index
is using ng-init
:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
static mySingleton *obj=nil;
@implementation mySingleton
-(id) init {
if(obj != nil){
[self release];
return obj;
} else if(self = [super init]) {
obj = self;
}
return obj;
}
+(mySingleton*) getSharedInstance {
@synchronized(self){
if(obj == nil) {
obj = [[mySingleton alloc] init];
}
}
return obj;
}
- (id)retain {
return self;
}
- (id)copy {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
if(obj != self){
[super release];
}
//do nothing
}
- (id)autorelease {
return self;
}
-(void) dealloc {
[super dealloc];
}
@end
You DO NOT NEED to replace the comma and dot..
I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.
Here I made a complete example to make the difference clear.
string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}
double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}
The results is the following:
Play around with the culture and you will get the result you need.
I had a similar problem: a left-hand menu that, when it appears, prevents scrolling. As soon as height was set to 100vh, the scrollbar disappeared and the content jerked to the right.
So if you don't mind keeping the scrollbar enabled (but setting the window to full height so it won't actually scroll anywhere) then another possibility is setting a tiny bottom margin, which will keep the scroll bars showing:
body {
height: 100vh;
overflow: hidden;
margin: 0 0 1px;
}
Try using
FROM [TableX]
ORDER BY [FieldX]
OFFSET 500 ROWS
FETCH NEXT 100 ROWS ONLY
to get the rows from 501 to 600 in the SQL server, without loading them in memory. Note that this syntax has become available with SQL Server 2012 only
It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script
that calls tsc
in your package.json
file so that you can run:
npm run tsc
Include --
before you pass in options (or just include them in the script):
npm run tsc -- -v
Here's an example package.json
:
{
"name": "foo",
"scripts": {
"tsc": "tsc"
},
"dependencies": {
"typescript": "^1.8.10"
}
}
Another one answer
static class ImmutableArray<T> {
private final T[] array;
private ImmutableArray(T[] a){
array = Arrays.copyOf(a, a.length);
}
public static <T> ImmutableArray<T> from(T[] a){
return new ImmutableArray<T>(a);
}
public T get(int index){
return array[index];
}
}
{
final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}
Use modulo:
$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;
I noticed a couple of syntax errors, but other than that, it should work fine:
var arr = [
["Blankaholm", "Gamleby"],
["2012-10-23", "2012-10-22"],
["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har."], //<- syntax error here
["57.586174","16.521841"], ["57.893162","16.406090"]
];
console.log(arr[4]); //["57.893162","16.406090"]
console.log(arr[4][0]); //57.893162
Try the following statement:
select distinct A.[Tag],
count(A.[Tag]) as TAG_COUNT,
(SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
from [TagTbl] AS A GROUP BY A.[Tag]
The first field will be the tag the second will be the whole count the third will be the positive ones count.