I didn't like the idea of creating a custom component, because if you have a different wrapping element you would have to create another custom component etc. Also, it is just overkill. So I just did it with css and activeClassName:
<li className="link-wrapper"> <!-- add a class to the wrapper -->
<Link to="something" activeClassName="active">Something</Link>
</li>
And then just add some css:
li.link-wrapper > a.active {
display: block;
width: 100%;
height:100%;
color: white;
background-color: blue;
}
Technically this doesn't style the li, but it makes the anchor fill the li and styles it.
As of this writing, it was necessary to:
I solved my problem simply using ng-init
for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
If the button tag is inside the div element who contains the modal, you can do something like:
<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>
<html>
<body>
<input id="mycheck" type="checkbox">
</body>
<script language="javascript">
var=check;
document.getElementById("mycheck");
check.checked="false";
</script>
</html>
wrap you shared code into another function:
<script>
function myFun () {
//do something
}
$(document).ready(function(){
//Load City by State
$(document).on('change', '#billing_state_id', function() {
myFun ();
});
$(document).on('click', '#click_me', function() {
//do something
myFun();
});
});
</script>
Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.
SELECT
tblMEP_Sites.Name AS SiteName,
convert(varchar(10),BillingMonth ,101) AS BillingMonth,
SUM(Consumption) AS Consumption
INTO
#MyTempTable
FROM
tblMEP_Projects
JOIN tblMEP_Sites
ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
JOIN tblMEP_Meters
ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
JOIN tblMEP_MonthlyData
ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
JOIN tblMEP_CustomerAccounts
ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
JOIN tblMEP_UtilityCompanies
ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
JOIN tblMEP_MeterTypes
ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE
tblMEP_Projects.ID = @ProjectID
AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY
BillingMonth, tblMEP_Sites.Name
DROP TABLE #MyTempTable
Fragment PHP (in console Cloud9):
echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";
resulting output:
1: first_srt=1
secnd_srt=2
2: first_srt=1\nsecnd_srt=2\n
==============
Difference between 1 and 2: " versus '
You can allow multiple POST parameters by using the MultiPostParameterBinding class from https://github.com/keith5000/MultiPostParameterBinding
To use it:
1) Download the code in the Source folder and add it to your Web API project or any other project in the solution.
2) Use attribute [MultiPostParameters] on the action methods that need to support multiple POST parameters.
[MultiPostParameters]
public string DoSomething(CustomType param1, CustomType param2, string param3) { ... }
3) Add this line in Global.asax.cs to the Application_Start method anywhere before the call to GlobalConfiguration.Configure(WebApiConfig.Register):
GlobalConfiguration.Configuration.ParameterBindingRules.Insert(0, MultiPostParameterBinding.CreateBindingForMarkedParameters);
4) Have your clients pass the parameters as properties of an object. An example JSON object for the DoSomething(param1, param2, param3)
method is:
{ param1:{ Text:"" }, param2:{ Text:"" }, param3:"" }
Example JQuery:
$.ajax({
data: JSON.stringify({ param1:{ Text:"" }, param2:{ Text:"" }, param3:"" }),
url: '/MyService/DoSomething',
contentType: "application/json", method: "POST", processData: false
})
.success(function (result) { ... });
Visit the link for more details.
Disclaimer: I am directly associated with the linked resource.
I've finally solved this problem. It was driving me nuts. From a PC, go to Google Play. In my case I had conflicting email accounts and had to create a new email account. Then go to your phone settings. Go to accounts and then Google. Remove your existing email there and add the new one.
The phone will then synchronise and then everything works again. You can then update and download apps; which is what I couldn't do before because of this problem.
and what about LibGDX from BadLogicGames?
Try this code,
SELECT
*
FROM
`customers`
WHERE
(
CONVERT
(`customer_code` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`customer_name` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`email_id` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`address1` USING utf8mb4) LIKE '%Mary%'
OR
CONVERT(`report_sorting` USING utf8mb4) LIKE '%Mary%'
)
This is help to solve your problem mysql version 5.7.21
Let me just add what happened with me, may help some one.
It was mainly due to signing.
Since I have added the signing details in the Project structure, I was thinking that every time when I run, expected signed apk is getting installed. But build type 'debug' was selected.
Below fix solved the problem for me.
Try this
load data infile 'datafile location' into table schema.tablename fields terminated by ',' optionally enclosed by '|' (field1,field2,field3....)
In command prompt:
sqlldr system@databasename/password control='control file location'
Spring Boot, v2.3.0.RELEASE
Recommended (In application.properties):
logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters
parameters
Note:
The above will not give you a pretty-print though.
You can add it as a configuration:
properties.put("hibernate.format_sql", "true");
or as per below.
Works but NOT recommended
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.
Cheers
even shorter:
echo $select->__toString()."\n";
and more shorter:
echo $select .""; die;
Java 1.8 (as well as Groovy and Scala) has a thing called "Interface Defender Methods", which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.
Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:
class Photo {
int width
int height
}
class Selection {
@Delegate Photo photo
String title
String caption
}
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"
assert selection.width == 640
assert selection.height == 480
I have recently ran across similar situation. To debug in any VS IDE version, open exceptions from Debug (Ctrl + D, E) - check all checkboxes against the column "Thrown", and run the application in debug mode. I have realized that one of the tables was not imported properly in the new database, so internal Sql Exception was killing the connection, thus results into this error.
Gist of the story is, If Previously working code returns this error on a new database, this could be database schema missing issue, realize by above debugging tip,
Hope It Helps, HydTechie
You can let PHP do a POST, but then your php will get the return, with all sorts of complications. I think the simplest would be to actually let the user do the POST.
So, kind-of what you suggested, you'll get indeed this part:
Customer fill detail in Page A, then in Page B we create another page show all the customer detail there, click a CONFIRM button then POST to Page C.
But you can actually do a javascript submit on page B, so there is no need for a click. Make it a "redirecting" page with a loading animation, and you're set.
Try something like this (should work for Apache and IIS):
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
@echo off
Setlocal enabledelayedexpansion
Set 1=%1
Set 1=!1:"=!
Echo !1!
Echo "!1!"
Set 1=
Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.
You can replace the jquery load function with a version that has cache set to false.
(function($) {
var _load = jQuery.fn.load;
$.fn.load = function(url, params, callback) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if (off > -1) {
selector = stripAndCollapse(url.slice(off));
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
cache: false,
data: params
}).done(function(responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
}).always(callback && function(jqXHR, status) {
self.each(function() {
callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
});
});
}
return this;
}
})(jQuery);
Place this somewhere global where it will run after jquery loads and you should be all set. Your existing load code will no longer be cached.
But, setting only that parameters, the authentication don't works.
Are necessary to add to that code the following:
final String authUser = "myuser";
final String authPassword = "secret";
System.setProperty("http.proxyHost", "hostAddress");
System.setProperty("http.proxyPort", "portNumber");
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
Authenticator.setDefault(
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
}
);
The best way would be to use .each()
var num = 0;
$('.className').each(function(){
num++;
});
Does your test require an Android device (emulator or hardware)?
If so, it's called an "instrumented test" and resides in "module-name/src/androidTest/java/".
If not, it's called a "local unit test" and resides in "module-name/src/test/java"
https://developer.android.com/training/testing/start/index.html
I got the same error because I had written a local unit test, but it was placed in the folder for instrumented tests. Moving the local unit test to the "src/test/java" folder fixed it for me.
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']
What you get from the url is a json string. And your can't parse it with index directly.
You should convert it to a dict by json.loads
and then you can parse it with index.
Instead of using .read()
to intermediately save it to memory and then read it to json
, allow json
to load it directly from the file:
wjdata = json.load(urllib2.urlopen('url'))
Use "content:;" at the hover.This works.
"Although I can't isolate SQL as the source of the problem anymore, I still feel like it is."
Fire up SQL Profiler and take a look. Take the resulting queries and check their execution plans to make sure that index is being used.
Another source of this problem: I found that in Debian 9, the Python httplib2 is hardcoded to insist on TLS v1.0. So any application that uses httplib2 to connect to a server that insists on better security fails with TLSV1_ALERT_PROTOCOL_VERSION.
I fixed it by changing
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
to
context = ssl.SSLContext()
in /usr/lib/python3/dist-packages/httplib2/__init__.py .
Debian 10 doesn't have this problem.
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved.Since the java.sql.Date has a constructor that takes 'long time' and java.util.Date has a method that returns 'long time', I just pass the returned 'long time' to the java.sql.Date to create the date.
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new Date(date.getTime());
You can use:
QString qs;
// do things
std::cout << qs.toStdString() << std::endl;
It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString
.
TF v2.0 supports Eager mode vis-a-vis Graph mode of v1.0. Hence, tf.session() is not supported on v2.0. Hence, would suggest you to rewrite your code to work in Eager mode.
You can use np.concatenate()
specifying which axis
to append, using np.newaxis
:
import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)
If you are reading from many files:
import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)
Always better to install a previous version or in the installation make sure you specify the '/data' in a separate directory folder "C:\data"
Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.
padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)
padded_image = tf.pad(image, paddings, "CONSTANT")
These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.
There are 3 ways to do this:
Right-click on the Chart and click Select Data then edit the series names directly as shown below.
You can either specify the values directly e.g. Series 1
or specify a range e.g. =A2
Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically.
Similarly you can define the series names dynamically using VBA. A simple example below:
ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""
This will redefine the first series name. Just change the index from (1)
to e.g. (2)
and so on to change the following series names. What does the VBA above do? It sets the series name to Hello
as "=""Hello"""
translates to ="Hello"
("
have to be escaped by a preceding "
).
Above answer explains very well ..just to add one thing If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it's present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
You should use the HasValue
property:
SomeProperty.HasValue
For example:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
Another possible cause for this error message is if the HTTP Method is blocked by the server or load balancer.
It seems to be standard security practice to block unused HTTP Methods. We ran into this because HEAD was being blocked by the load balancer (but, oddly, not all of the load balanced servers, which caused it to fail only some of the time). I was able to test that the request itself worked fine by temporarily changing it to use the GET method.
The error code on iOS was: Error requesting App Code: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
I think these could be helpful for you .
Using a SELECT
statement with a simple CASE
expression
Within a SELECT
statement, a simple CASE
expression allows for only an equality check; no other comparisons are made. The following example uses the CASE
expression to change the display of product line categories to make them more understandable.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
Using a SELECT
statement with a searched CASE
expression
Within a SELECT
statement, the searched CASE
expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Using CASE
in an ORDER BY
clause
The following examples uses the CASE
expression in an ORDER BY
clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.
SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
ELSE CountryRegionName END;
Using CASE
in an UPDATE
statement
The following example uses the CASE
expression in an UPDATE
statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT
clause is used to display the before and after vacation values.
USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours =
( CASE
WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
ELSE (VacationHours + 20.00)
END
)
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue,
Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0;
Using CASE
in a HAVING
clause
The following example uses the CASE
expression in a HAVING
clause to restrict the rows returned by the SELECT
statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING
clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.
USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M'
THEN ph1.Rate
ELSE NULL END) > 40.00
OR MAX(CASE WHEN Gender = 'F'
THEN ph1.Rate
ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;
For more details description of these example visit the source.
Also visit here and here for some examples with great details.
You could install nvm and have multiple versions of Node.js installed.
curl https://raw.github.com/creationix/nvm/master/install.sh | sh
source ~/.nvm/nvm.sh
and then run:
nvm install 0.8.22 #(or whatever version of Node.js you want)
you can see what versions you have installed with :
nvm list
and you can change between versions with:
nvm use 0.8.22
The great thing about using NVM is that you can test different versions alongside one another. If different apps require different versions of Node.js, you can run them both.
Run a test.
string coerce: 7.42296099663
string cast: 8.05654597282
string fail coerce: 7.14159703255
string fail cast: 7.87444186211
This was a test that ran each scenario 10,000,000 times. :-)
Co-ercion is 0 + "123"
Casting is (integer)"123"
I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123')
is a fatal error in PHP. You might want your code to check the type of the supplied value.
My test code is below.
function test_string_coerce($s) {
return 0 + $s;
}
function test_string_cast($s) {
return (integer)$s;
}
$iter = 10000000;
print "-- running each text $iter times.\n";
// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();
print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_coerce('123');
}
$string_coerce->Stop();
// string cast
$string_cast = new Timer;
$string_cast->Start();
print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_cast('123');
}
$string_cast->Stop();
// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();
print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_coerce('hello');
}
$string_coerce_fail->Stop();
// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();
print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
test_string_cast('hello');
}
$string_cast_fail->Stop();
// -----------------
print "\n";
print "string coerce: ".$string_coerce->Elapsed()."\n";
print "string cast: ".$string_cast->Elapsed()."\n";
print "string fail coerce: ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast: ".$string_cast_fail->Elapsed()."\n";
class Timer {
var $ticking = null;
var $started_at = false;
var $elapsed = 0;
function Timer() {
$this->ticking = null;
}
function Start() {
$this->ticking = true;
$this->started_at = microtime(TRUE);
}
function Stop() {
if( $this->ticking )
$this->elapsed = microtime(TRUE) - $this->started_at;
$this->ticking = false;
}
function Elapsed() {
switch( $this->ticking ) {
case true: return "Still Running";
case false: return $this->elapsed;
case null: return "Not Started";
}
}
}
Be sure your DOCKERfile
is in the ROOT of the application directory, I had mine in src which resulted in this error because Docker was not finding the path to DOCKERfile
A non-jQuery way to get the available screen dimension. window.screen.width/height
has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth and availHeight - The available width and height on the screen (excluding OS taskbars and such).
Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".
Google indeed ignores most punctuation, with the following exceptions:
As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.
Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.
For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.
If you want to retrieve informations about the environment variable in Java, you can call the method : System.getenv();
. As the properties, this method returns a Map containing the variable names as keys and the variable values as the map values. Here is an example :
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
}
}
The method getEnv()
can also takes an argument. For instance :
String myvalue = System.getEnv("MY_VARIABLE");
For testing, I would do something like this :
public class Environment {
public static String getVariable(String variable) {
return System.getenv(variable);
}
@Test
public class EnvVariableTest {
@Test testVariable1(){
String value = Environment.getVariable("MY_VARIABLE1");
doSometest(value);
}
@Test testVariable2(){
String value2 = Environment.getVariable("MY_VARIABLE2");
doSometest(value);
}
}
What does truncate mean?
You have full control over the formatting by using the strftime() method and using an appropriate format string.
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
it doesn't matter that you declare your minSdk in build.gradle. You have to copy overrideLibrary
in your AndroidManifest.xml
, as documented here.
<manifest
... >
<uses-sdk tools:overrideLibrary="com.example.lib1, com.example.lib2"/>
...
</manifest>
The system automatically ignores the sdkVersion declared in AndroidManifest.xml.
I hope this solve your problem.
You could try using the <col>
tag manage table styling for all rows but you will need to set the table-layout:fixed
style on the <table>
or the tables css class and set the overflow
style for the cells
http://www.w3schools.com/TAGS/tag_col.asp
<table class="fixed">
<col width="20px" />
<col width="30px" />
<col width="40px" />
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</table>
and this be your CSS
table.fixed { table-layout:fixed; }
table.fixed td { overflow: hidden; }
If you use Windows, you will found it follow this: File-->Project Structure-->Facets
chose your Android project and in the "Facet 'Android'" window click TAB "Packaging",you will found what you want
In Rails 2, I would have written:
validates_uniqueness_of :zipcode, :scope => :recorded_at
In Rails 3:
validates :zipcode, :uniqueness => {:scope => :recorded_at}
For multiple attributes:
validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}
Once you are able to parse those strings into a Date object comparing them is easy (Using the <
operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.
You can select the tables from information_schema
SELECT * FROM information_schema.tables
WHERE table_schema = 'public'
Try:
from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;
What's the SQL query you want to translate into a Linq query?
For UTC:
string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
For local system:
string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
If you are using MySQL use a field type of TIME and the associated functionality that comes with TIME.
00:00:00 is standard unix time format.
If you ever have to look back and review the tables by hand, integers can be more confusing than an actual time stamp.
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector
is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
This one solved my issue which is SELinux setting:
chcon -R -t httpd_sys_content_t /home/*
First, checkout to your Branch3:
git checkout Branch3
Then merge the Branch1:
git merge Branch1
And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase
git checkout Branch2
git rebase Branch1
This will update your Branch2 with the latest updates of Branch1.
And what about:
if ($('#dataTable[data-timer]').length > 0) {
// logic here
}
This did the magic for me. chmod -Rf 0777 storage
http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.
But it does not say why exactly 1/1/1970 was chosen in the end.
Notable excerpts from the Wikipedia page:
The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".
Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.
Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.
You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.
If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again
bool check = false;
Console.WriteLine("Please Enter the Name");
name=Console.ReadLine();
for (int i = 0; i < name.Length; i++)
{
if (name[i]>='a' && name[i]<='z' || name[i]==' ')
{
check = true;
}
else
{
check = false;
break;
}
}
if (check==false)
{
Console.WriteLine("Enter Valid Value");
name = Console.ReadLine();
}
According to the Go specification:
For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.
A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.
In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.
If you were unsure if it was a string or not, you could test using the two return syntax.
str, ok := data.(string)
If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:
if str, ok := data.(string); ok {
/* act on str */
} else {
/* not string */
}
Guideline: If you can succinctly provide an exact representation, format it as a Python expression (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an inexact representation, use <...>
format.
There are many possible representations for any value, but the one that's most interesting for Python programmers is an expression that recreates the value. Remember that those who understand Python are the target audience—and that's also why inexact representations should include relevant context. Even the default <XXX object at 0xNNN>
, while almost entirely useless, still provides type, id()
(to distinguish different objects), and indication that no better representation is available.
Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector
's insertion operation on the validity of iterators and references with respect to reserve()
and capacity()
, which the most upvoted answer failed to notice.
C++ 03:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().
C++11:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().
So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)
" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()
". This is one thing that C++03 differs from C++11. In C++03, once an insert()
causes the size of the vector to reach the value specified in the previous reserve()
call (which could well be smaller than the current capacity()
since a reserve()
could result a bigger capacity()
than asked for), any subsequent insert()
could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity()
to know with certainty that the next reallocation won't take place before the size overpasses capacity()
.
In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve()
that you should check the size against, not the return value of a call to capacity()
, otherwise you may get yourself surprised at a "premature" reallocation.
Add the following to the top of your app/build.gradle
file
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.
$http service methods are listed below,
$http.get()
$http.post()
$http.delete()
$http.head()
$http.jsonp()
$http.patch()
$http.put()
One of the Example:
$http.get("sample.php")
.success(function(response) {
$scope.getting = response.data; // response.data is an array
}).error(){
// Error callback will trigger
});
(new Date(ts*1000)+'').slice(16,24)
let ts = 1549312452;
let time = (new Date(ts*1000)+'').slice(16,24);
console.log(time);
_x000D_
Here another method but it is little worse compare to other.
List<int> i=original.Take(original.count).ToList();
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
If you want to have the power of XPATH combined with the ability to also use CSS at any point you can use parsel
:
>>> from parsel import Selector
>>> sel = Selector(text=u"""<html>
<body>
<h1>Hello, Parsel!</h1>
<ul>
<li><a href="http://example.com">Link 1</a></li>
<li><a href="http://scrapy.org">Link 2</a></li>
</ul
</body>
</html>""")
>>>
>>> sel.css('h1::text').extract_first()
'Hello, Parsel!'
>>> sel.xpath('//h1/text()').extract_first()
'Hello, Parsel!'
I use:
border: 0;
From 8.5.4 in CSS 2.1:
'border'
Value: [ <border-width> || <border-style> || <'border-top-color'> ] | inherit
So either of your methods look fine.
As short as @jumbo's answer is :-) you can do it even more tersely.
This just returns the Count
property of the array returned by the antecedent sub-expression:
@(Get-Alias).Count
A couple points to note:
You can put an arbitrarily complex expression in place of Get-Alias
, for example:
@(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count
property to exist by forcing the output to be an array.)
2012.01.30 Update
The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count
property even for singletons, so the at-sign becomes unimportant for this scenario.
for swift 4:
inside the cellForItemAt ,_x000D_
_x000D_
cell.chekbx.addTarget(self, action: #selector(methodname), for: .touchUpInside)_x000D_
_x000D_
then outside of cellForItemAt_x000D_
@objc func methodname()_x000D_
{_x000D_
//your function code_x000D_
}
_x000D_
Simple explanation:
foo = "BEST DAY EVER" #assign a string to variable foo.
=> foo.downcase #call method downcase, this is without any exclamation.
"best day ever" #returns the result in downcase, but no change in value of foo.
=> foo #call the variable foo now.
"BEST DAY EVER" #variable is unchanged.
=> foo.downcase! #call destructive version.
=> foo #call the variable foo now.
"best day ever" #variable has been mutated in place.
But if you ever called a method downcase!
in the explanation above, foo
would change to downcase permanently. downcase!
would not return a new string object but replace the string in place, totally changing the foo
to downcase.
I suggest you don't use downcase!
unless it is totally necessary.
If using TextBox2.Text
as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.
If the text box is blank when Convert.ToInt32
is called, you will receive the System.FormatException
. Suggest trying:
protected void SetImageWidth()
{
try{
Image1.Width = Convert.ToInt32(TextBox1.Text);
}
catch(System.FormatException)
{
Image1.Width = 100; // or other default value as appropriate in context.
}
}
The problem with creating a directory and keeping index.php in it is that
The solutions are 1. MOD REWRITE (as suggested above) 2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/
This is awesome: http://www.ianmccullough.net/5-column-bootstrap-layout/
Just do:
<div class="col-xs-2 col-xs-15">
And CSS:
.col-xs-15{
width:20%;
}
This response header can be used to configure a user-agent's built in reflective XSS protection. Currently, only Microsoft's Internet Explorer, Google Chrome and Safari (WebKit) support this header.
Internet Explorer 8 included a new feature to help prevent reflected cross-site scripting attacks, known as the XSS Filter. This filter runs by default in the Internet, Trusted, and Restricted security zones. Local Intranet zone pages may opt-in to the protection using the same header.
About the header that you posted in your question,
The header X-XSS-Protection: 1; mode=block
enables the XSS Filter. Rather than sanitize the page, when a XSS attack is detected, the browser will prevent rendering of the page.
In March of 2010, we added to IE8 support for a new token in the X-XSS-Protection header, mode=block.
X-XSS-Protection: 1; mode=block
When this token is present, if a potential XSS Reflection attack is detected, Internet Explorer will prevent rendering of the page. Instead of attempting to sanitize the page to surgically remove the XSS attack, IE will render only “#”.
Internet Explorer recognizes a possible cross-site scripting attack. It logs the event and displays an appropriate message to the user. The MSDN article describes how this header works.
How this filter works in IE,
More on this article, https://blogs.msdn.microsoft.com/ie/2008/07/02/ie8-security-part-iv-the-xss-filter/
The XSS Filter operates as an IE8 component with visibility into all requests / responses flowing through the browser. When the filter discovers likely XSS in a cross-site request, it identifies and neuters the attack if it is replayed in the server’s response. Users are not presented with questions they are unable to answer – IE simply blocks the malicious script from executing.
With the new XSS Filter, IE8 Beta 2 users encountering a Type-1 XSS attack will see a notification like the following:
IE8 XSS Attack Notification
The page has been modified and the XSS attack is blocked.
In this case, the XSS Filter has identified a cross-site scripting attack in the URL. It has neutered this attack as the identified script was replayed back into the response page. In this way, the filter is effective without modifying an initial request to the server or blocking an entire response.
The Cross-Site Scripting Filter event is logged when Windows Internet Explorer 8 detects and mitigates a cross-site scripting (XSS) attack. Cross-site scripting attacks occur when one website, generally malicious, injects (adds) JavaScript code into otherwise legitimate requests to another website. The original request is generally innocent, such as a link to another page or a Common Gateway Interface (CGI) script providing a common service (such as a guestbook). The injected script generally attempts to access privileged information or services that the second website does not intend to allow. The response or the request generally reflects results back to the malicious website. The XSS Filter, a feature new to Internet Explorer 8, detects JavaScript in URL and HTTP POST requests. If JavaScript is detected, the XSS Filter searches evidence of reflection, information that would be returned to the attacking website if the attacking request were submitted unchanged. If reflection is detected, the XSS Filter sanitizes the original request so that the additional JavaScript cannot be executed. The XSS Filter then logs that action as a Cross-Site Script Filter event. The following image shows an example of a site that is modified to prevent a cross-site scripting attack.
Source: https://msdn.microsoft.com/en-us/library/dd565647(v=vs.85).aspx
Web developers may wish to disable the filter for their content. They can do so by setting an HTTP header:
X-XSS-Protection: 0
More on security headers in,
try this,
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sample, menu);
super.onCreateOptionsMenu(menu,inflater);
}
Finally, in onCreateView
method, add this line to make the options appear in your Toolbar
setHasOptionsMenu(true);
Ctrl-ww
This will move between open windows (so you could hop between the NERDTree window, the file you are editing and the help window, for example... just hold down Ctrl and press w twice).
I have a solution below and its works for me:
app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
method: 'jsonp',
url: 'http://mywebservice',
params: {
format: 'jsonp',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
}
}]);
in 'http://mywebservice' there must be need a callback parameter which return JSON_CALLBACK with data.
There is a sample example below which works perfect
$scope.url = "https://angularjs.org/greet.php";
$http({
method: 'jsonp',
url: $scope.url,
params: {
format: 'jsonp',
name: 'Super Hero',
callback: 'JSON_CALLBACK'
}
}).then(function (response) {
alert(response.data);
});
example output:
{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}
do it like this
objArrayy.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
});
console.log(objArray)
I made a short answer, that sums up most of the above, to clean the uncertainty that was in my head as a beginner:
Opposed to Objective-C, no variable can contain nil in Swift, so the Optional variable type was added (variables suffixed by "?"):
var aString = nil //error
The big difference is that the Optional variables don't directly store values (as a normal Obj-C variables would) they contain two states: "has a value" or "has nil":
var aString: String? = "Hello, World!"
aString = nil //correct, now it contains the state "has nil"
That being, you can check those variables in different situations:
if let myString = aString? {
println(myString)
}
else {
println("It's nil") // this will print in our case
}
By using the "!" suffix, you can also access the values wrapped in them, only if those exist. (i.e it is not nil):
let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!
println(anotherString) //it will print "Hello, World!"
That's why you need to use "?" and "!" and not use all of them by default. (this was my biggest bewilderment)
I also agree with the answer above: Optional type cannot be used as a boolean.
Both store memory addresses to the first elements of two different arrays. These addresses can't be equal hence the output.
I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in
private void SetFont(Form f, string name, int size, FontStyle style)
{
Font replacementFont = new Font(name, size, style);
f.Font = replacementFont;
}
Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.
/// To call the function do this.
/// e.g in the form load event etc.
public Form1()
{
InitializeComponent();
SetFont(this, "Arial", 8, FontStyle.Bold);
// This sets the whole form and
// everything below it.
// Shaun Cassidy.
}
You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.
/// and then import the namespace
using Droitech.TextFont;
/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);
Simple.
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
KB954606 - Security Update for SQL Server SP2
ReportViewer 2005 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=82833F27-081D-4B72-83EF-2836360A904D
Download and install the following update:
KB954607 - Security Update for SQL Server SP2
append a dot(.) in front of a file name if you want to import this file which is in the same directory where you are running your code.
For example, i'm running a file named a.py and i want to import a method named addFun which is written in b.py, and b.py is there in the same directory
from .b import addFun
You have a couple of options. The easiest involve using the ErrorAction
settings.
-Erroraction
is a universal parameter for all cmdlets. If there are special commands you want to ignore you can use -erroraction 'silentlycontinue'
which will basically ignore all error messages generated by that command. You can also use the Ignore
value (in PowerShell 3+):
Unlike SilentlyContinue, Ignore does not add the error message to the $Error automatic variable.
If you want to ignore all errors in a script, you can use the system variable $ErrorActionPreference
and do the same thing: $ErrorActionPreference= 'silentlycontinue'
See about_CommonParameters for more info about -ErrorAction. See about_preference_variables for more info about $ErrorActionPreference.
Uninstall pg:
gem uninstall pg
Uninstall postgres:
brew uninstall postgres
Nuke the postgres folder which might be lingering with a bunch of stale stuff it in:
rm -rf /usr/local/var/postgres
Reboot (maybe unnecessary)
Reinstall pg:
brew install postgres
My comment in Chris Slade's answer starts pg the hard way, now I use brew services which has simplified my life in so many ways:
brew install services
And start pg with it:
brew services start postgresql
Reinstall the gem:
gem install pg
And bobsyouruncle.
How to install different Python versions is indeed OS dependent.
However, if you're on linux, you can use a tool like pythonbrew or pythonz to help you easily manage and switch between different versions.
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString
method. So here you need to override toString()
in your Person
class and return the desired state.
There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString()
writing shortcut.
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
I'm going to assume that you do not have your secrets.yml
checked into source control (ie. it's in the .gitignore
file). Even if this isn't your situation, it's what many other people viewing this question have done because they have their code exposed on Github and don't want their secret key floating around.
If it's not in source control, Heroku doesn't know about it. So Rails is looking for Rails.application.secrets.secret_key_base
and it hasn't been set because Rails sets it by checking the secrets.yml
file which doesn't exist. The simple workaround is to go into your config/environments/production.rb
file and add the following line:
Rails.application.configure do
...
config.secret_key_base = ENV["SECRET_KEY_BASE"]
...
end
This tells your application to set the secret key using the environment variable instead of looking for it in secrets.yml
. It would have saved me a lot of time to know this up front.
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
There's an easier way than the other answers that doesn't require you to name the resource explicitly or worry about exceptions with package names. It also works if you have used a string directly instead of a resource.
Just do:
public static String getApplicationName(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
int stringId = applicationInfo.labelRes;
return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
}
Hope this helps.
Edit
In light of the comment from Snicolas, I've modified the above so that it doesn't try to resolve the id if it is 0. Instead it uses, nonLocalizedLabel
as a backoff. No need for wrapping in try/catch.
I'm not sure what you're going for here--by the time jQuery(document).ready()
has executed, it has already loaded, and thus document
's load event will already have been called. Attaching the load
event handler at this point will have no effect and it will never be called. If you're attempting to alert
"started" once the document has loaded, just put it right in the (document).ready()
call, like this:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
alert('started');
});?
If, as your code also appears to insinuate, you want to fire the alert when .abc
has loaded, put it in an individual .load
handler:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
$(".abc").on("load", function() {
alert('started');
}
});?
Finally, I see little point in using jQuery
in one place and $
in another. It's generally better to keep your code consistent, and either use jQuery
everywhere or $
everywhere, as the two are generally interchangeable.
I was facing the same problem and I found the solution Android's official Documentation about WebView
Here is my onCreateView()
method and here i used two methods to open the urls
Method 1 is opening url in Browser and
Method 2 is opening url in your desired WebView.
And I am using Method 2 for my Application and this is my code:
public class MainActivity extends Activity {
private WebView myWebView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
// Show the dummy content as text in a TextView.
if (mItem != null) {
/* Method : 1
This following line is working fine BUT when we click the menu item then it opens the URL in BROWSER not in WebView */
//((WebView) rootView.findViewById(R.id.detail_area)).loadUrl(mItem.url);
// Method : 2
myWebView = (WebView) rootView.findViewById(R.id.detail_area); // get your WebView form your xml file
myWebView.setWebViewClient(new WebViewClient()); // set the WebViewClient
myWebView.loadUrl(mItem.url); // Load your desired url
}
return rootView;
} }
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
Read up on RAII and make sure you understand it.
Tuples will be (are) in .Net 4.0 Until then, you can also use a
Dictionary<key1, Dictionary<key2, TypeObject>>
or, creating a custom collection class to represent this...
public class TwoKeyDictionary<K1, K2, T>:
Dictionary<K1, Dictionary<K2, T>> { }
or, with three keys...
public class ThreeKeyDictionary<K1, K2, K3, T> :
Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }
The only time you would NOT throw exceptions from constructors is if your project has a rule against using exceptions (for instance, Google doesn't like exceptions). In that case, you wouldn't want to use exceptions in your constructor any more than anywhere else, and you'd have to have an init method of some sort instead.
If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:
Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";
which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.
I am not quite sure what you need, but I would use something like this:
#!/usr/bin/env ruby
until ARGV.empty? do
puts "From arguments: #{ARGV.shift}"
end
while a = gets
puts "From stdin: #{a}"
end
Note that because ARGV array is empty before first gets
, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).
If stdin is empty or there is no arguments, nothing is printed.
Few test cases:
$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2
$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!
var MyApp = new Class();
MyApp.extend({
utility: {
queryStringHelper: function (url) {
var originalUrl = url;
var newUrl = url;
var finalUrl;
var insertParam = function (key, value) {
key = escape(key);
value = escape(value);
//The previous post had the substr strat from 1 in stead of 0!!!
var kvp = newUrl.substr(0).split('&');
var i = kvp.length;
var x;
while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) {
kvp[kvp.length] = [key, value].join('=');
}
finalUrl = kvp.join('&');
return finalUrl;
};
this.insertParameterToQueryString = insertParam;
this.insertParams = function (keyValues) {
for (var keyValue in keyValues[0]) {
var key = keyValue;
var value = keyValues[0][keyValue];
newUrl = insertParam(key, value);
}
return newUrl;
};
return this;
}
}
});
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
I was having the same problem just delete .m2 folder folder from your local repositry Hope it will work.
os.unlink(path, *, dir_fd=None)
or
os.remove(path, *, dir_fd=None)
Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.
shutil.rmtree(path, ignore_errors=False, onerror=None)
or
os.rmdir(path, *, dir_fd=None)
In order to remove whole directory trees, shutil.rmtree()
can be used. os.rmdir
only works when the directory is empty and exists.
os.removedirs(name)
It remove every empty parent directory with self until parent which has some content
ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are empty.
For more info check official doc: os.unlink
, os.remove
, os.rmdir
, shutil.rmtree
, os.removedirs
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
Hope, this help:
Number.prototype.zeroFill= function (n) {
var isNegative = this < 0;
var number = isNegative ? -1 * this : this;
for (var i = number.toString().length; i < n; i++) {
number = '0' + number;
}
return (isNegative ? '-' : '') + number;
}
<audio id="audio" style="display:none;" src="mp3/Fans-Mi-tooXclusive_com.mp3" controls autoplay loop onloadeddata="setHalfVolume()">
This auto-plays, hides the music and reduces the music even if system volume is high to avoid noise. Place this in script:
<script>
function setHalfVolume() {
var myAudio = document.getElementById("audio");
myAudio.volume = 0.2;
}
</script>
In 2018:
var map = new google.maps.Map(...)
map.addListener('tilesloaded', function () { ... })
https://developers.google.com/maps/documentation/javascript/events
You can use the following wrap to make sync call
this.setState((state =>{_x000D_
return{_x000D_
something_x000D_
}_x000D_
})
_x000D_
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
To stop the service we must use the method stopService()
:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
//startService(myService);
stopService(myService);
then the method onDestroy()
in the service is called:
@Override
public void onDestroy() {
Log.i(TAG, "onCreate() , service stopped...");
}
Here is a complete example including how to stop the service.
I had the same problem to run Windows IIS image using docker for Windows. Reading the Mohammad Trabelsi response above I realised that to solve my problem I needed to switch my containers (on docker) for Windows containers.
To do this:
You can try.
$options['inputs'] = $options['inputs'] + $new_input;
Here's a simple, working example:
package main
import (
"io"
"net/http"
)
func queryParamDisplayHandler(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "name: "+req.FormValue("name"))
io.WriteString(res, "\nphone: "+req.FormValue("phone"))
}
func main() {
http.HandleFunc("/example", func(res http.ResponseWriter, req *http.Request) {
queryParamDisplayHandler(res, req)
})
println("Enter this in your browser: http://localhost:8080/example?name=jenny&phone=867-5309")
http.ListenAndServe(":8080", nil)
}
foreach
supports iteration over three different kinds of values:
Traversable
objectsIn the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable
objects, as for these foreach
is essentially only syntax sugar for code along these lines:
foreach ($it as $k => $v) { /* ... */ }
/* translates to: */
if ($it instanceof IteratorAggregate) {
$it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
$v = $it->current();
$k = $it->key();
/* ... */
}
For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator
interface on the C level.
Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort
). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).
The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).
So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:
foreach ($arr as &$v)
then $arr
is turned into a reference and you can change it during iteration.$ref =& $arr; foreach ($ref as $v)
The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).
There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.
As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.
Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.
While foreach
does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach
loops:
// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
foreach ($arr as &$v) {
// ...
}
}
To support two simultaneous loops with only one internal array pointer, foreach
performs the following shenanigans: Before the loop body is executed, foreach
will back up a pointer to the current element and its hash into a per-foreach HashPointer
. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.
The IAP is a visible feature of an array (exposed through the current
family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach
is in many cases forced to duplicate the array it is iterating over. The precise conditions are:
refcount
is 1, then the array is not shared and we're free to modify it directly.If the array is not duplicated (is_ref=0, refcount=1), then only its refcount
will be incremented (*). Additionally, if foreach
by reference is used, then the (potentially duplicated) array will be turned into a reference.
Consider this code as an example where duplication occurs:
function iterate($arr) {
foreach ($arr as $v) {}
}
$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);
Here, $arr
will be duplicated to prevent IAP changes on $arr
from leaking to $outerArr
. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).
(*) Incrementing the refcount
here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount
and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).
There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:
reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
code();
move_forward(arr);
}
However foreach
, being a rather special snowflake, chooses to do things slightly differently:
reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
move_forward(arr);
code();
}
Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i
, the IAP is already at element $i+1
. This is the reason why code samples showing modification during iteration will always unset
the next element, rather than the current one.
The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach
implementation and we can move on to discuss some examples.
The behavior of your test cases is simple to explain at this point:
In test cases 1 and 2 $array
starts off with refcount=1, so it will not be duplicated by foreach
: Only the refcount
is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array
.
In test case 3, once again the array is not duplicated, thus foreach
will be modifying the IAP of the $array
variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each
indicates by returning false
.
In test cases 4 and 5 both each
and reset
are by-reference functions. The $array
has a refcount=2
when it is passed to them, so it has to be duplicated. As such foreach
will be working on a separate array again.
current
in foreachA good way to show the various duplication behaviors is to observe the behavior of the current()
function inside a foreach
loop. Consider this example:
foreach ($array as $val) {
var_dump(current($array));
}
/* Output: 2 2 2 2 2 */
Here you should know that current()
is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next
which are all by-ref. By-reference passing implies that the array has to be separated and thus $array
and the foreach-array
will be different. The reason you get 2
instead of 1
is also mentioned above: foreach
advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach
already advanced the pointer to the second.
Now lets try a small modification:
$ref = &$array;
foreach ($array as $val) {
var_dump(current($array));
}
/* Output: 2 3 4 5 false */
Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current()
function. Thus current()
and foreach
work on the same array. You still see the off-by-one behavior though, due to the way foreach
advances the pointer.
You get the same behavior when doing by-ref iteration:
foreach ($array as &$val) {
var_dump(current($array));
}
/* Output: 2 3 4 5 false */
Here the important part is that foreach will make $array
an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.
Another small variation, this time we'll assign the array to another variable:
$foo = $array;
foreach ($array as $val) {
var_dump(current($array));
}
/* Output: 1 1 1 1 1 */
Here the refcount of the $array
is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array
and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).
Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.
Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):
foreach ($array as &$v1) {
foreach ($array as &$v2) {
if ($v1 == 1 && $v2 == 1) {
unset($array[1]);
}
echo "($v1, $v2)\n";
}
}
// Output: (1, 1) (1, 3) (1, 4) (1, 5)
The expected part here is that (1, 2)
is missing from the output because element 1
was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?
The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer
. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!
Another consequence of the HashPointer
backup+restore mechanism is that changes to the IAP through reset()
etc. usually do not impact foreach
. For example, the following code executes as if the reset()
were not present at all:
$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
var_dump($value);
reset($array);
}
// output: 1, 2, 3, 4, 5
The reason is that, while reset()
temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset()
to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:
$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
var_dump($value);
unset($array[1]);
reset($array);
}
// output: 1, 1, 3, 4, 5
But, those examples are still sane. The real fun starts if you remember that the HashPointer
restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach
believe that an element that has been removed still exists, so it will jump directly to it. An example:
$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
unset($array['EzFY']);
$array['FYFY'] = 4;
reset($array);
var_dump($value);
}
// output: 1, 4
Here we should normally expect the output 1, 1, 3, 4
according to the previous rules. How what happens is that 'FYFY'
has the same hash as the removed element 'EzFY'
, and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.
One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:
$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];
$ref =& $arr;
foreach ($ref as $val) {
echo "$val\n";
if ($val == 3) {
$ref = $obj;
}
}
/* Output: 1 2 3 6 7 8 9 10 */
As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.
If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset()
etc. on top of that.
PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.
This means that foreach
will no longer use the IAP at all. The foreach
loop will be absolutely no effect on the results of current()
etc. and its own behavior will never be influenced by functions like reset()
etc.
Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount
increment (instead of duplication the array) in all cases. If the array is modified during the foreach
loop, at that point a duplication will occur (according to copy-on-write) and foreach
will keep working on the old array.
In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:
$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
var_dump($val);
$array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */
Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.
This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:
$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
var_dump($val);
$obj->bar = 42;
}
/* Old and new output: 1, 42 */
This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).
Let's consider a few examples, starting with your test cases:
Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting
and duplication behavior is exactly the same between PHP 5 and PHP 7).
Test case 3 changes: Foreach
no longer uses the IAP, so each()
is not affected by the loop. It will have the same output before and after.
Test cases 4 and 5 stay the same: each()
and reset()
will duplicate the array before changing the IAP, while foreach
still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)
The second set of examples was related to the behavior of current()
under different reference/refcounting
configurations. This no longer makes sense, as current()
is completely unaffected by the loop, so its return value always stays the same.
However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:
$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
foreach ($array as &$v2) {
if ($v1 == 1 && $v2 == 1) {
unset($array[1]);
}
echo "($v1, $v2)\n";
}
}
// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
// (3, 1) (3, 3) (3, 4) (3, 5)
// (4, 1) (4, 3) (4, 4) (4, 5)
// (5, 1) (5, 3) (5, 4) (5, 5)
As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.
Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:
$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
unset($array['EzFY']);
$array['FYFY'] = 4;
var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4
Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.
For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:
from scipy.ndimage.filters import gaussian_filter1d
ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()
if you increase sigma you can get a more smoothed function.
Proceed with caution with this one. It modifies the original values and may not be what you want.
If you are targeting SDK > 21 (lollipop or 5.0) use
context.getDrawable(R.drawable.your_drawable_name)
thank you, your first error guides me here and the solution solve mine too!
for permission error, f = open('output', 'w+')
, change it into f = open(output+'output', 'w+')
.
or something else, but the way you are now using is having access to the installation directory of Python which normally in Program Files, and it probably needs administrator permission.
for sure, you could probably running python/your script as administrator to pass permission error though
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
Multiply by 1000, round, and divide back by 1000.
For basic Java: http://download.oracle.com/javase/tutorial/getStarted/index.html and http://download.oracle.com/javase/tutorial/java/index.html
Try this:
git checkout [revision] .
where [revision]
is the commit hash (for example: 12345678901234567890123456789012345678ab
).
Don't forget the .
at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.
You can undo this by
git reset --hard
that will delete all modifications from the working directory and staging area.
If you re in your office ,use your smartphone network. I think It will work.
Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.
You can do this with 1 line of code:
$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);
If you're using jQuery you don't need setTimeout, at least not to autohide an element.
If by chance this error happens when working with SharePoint 2010: Rename your .json file extensions and be sure to update your restService path. No additional "track by $index" was required.
Luckily I was forwarded this link to this rationale:
.json becomes an important file type in SP2010. SP2010 includes certains webservice endpoints. The location of these files is 14hive\isapi folder. The extension of these files are .json. That is the reason it gives such a error.
"cares only that the contents of a json file is json - not its file extension"
Once the file extensions are changed, should be all set.
You need check for image is not nil before assign it to button.
Example:
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
if let image = UIImage(named: "imagename.png") {
button.setImage(image, forState: .Normal)
}
button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)
this turns the recursion in to a loop:
def checkNextID(ID):
global numOfRuns, curRes, lastResult
while ID < lastResult:
try:
numOfRuns += 1
if numOfRuns % 10 == 0:
time.sleep(3) # sleep every 10 iterations
if isValid(ID + 8):
parseHTML(curRes)
ID = ID + 8
elif isValid(ID + 18):
parseHTML(curRes)
ID = ID + 18
elif isValid(ID + 7):
parseHTML(curRes)
ID = ID + 7
elif isValid(ID + 17):
parseHTML(curRes)
ID = ID + 17
elif isValid(ID+6):
parseHTML(curRes)
ID = ID + 6
elif isValid(ID + 16):
parseHTML(curRes)
ID = ID + 16
else:
ID = ID + 1
except Exception, e:
print "somethin went wrong: " + str(e)
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.
But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:
"If this Window is visible, brings this Window to the front and may make it the focused Window."
It seems easy for me that use plt.savefig()
function after plot()
function:
import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')
The answer of Mintir4 is fine, I would also do the following to load the file.
FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";
while ((s = r.readLine()) != null) {
txt += s;
}
r.close();
I have created a demo for you.
Here is how your nested structure should be in Bootstrap 3:
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</div>
</div>
Notice how the whole form-inline
is nested within the col-xs-10
div containing the control of the horizontal form. In other terms, the whole form-inline
is the "control" of the birthday label in the main horizontal form.
Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:
.form-inline .form-group{
margin-left: 0;
margin-right: 0;
}
You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
expression.
(1) If all you need is the difference between two instants in seconds, the very simple time.time()
does the job.
(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:
gmtime()
returns a time tuple in UTC but mktime()
expects a time tuple in local time.
I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31
>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time
You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow()
which won't jump by an hour when DST goes on/off and may give you more precision than time.time()
try
total.Text = DateTime.Now.ToString()
or
Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()
You declare Start
as an Integer
, while you are trying to put a DateTime
in it, which is not possible.
Use PHPMailer,
To send HTML mail you have to set $mail->isHTML() only, and you can set your body with HTML tags
Here is a well written tutorial :
rohitashv.wordpress.com/2013/01/19/how-to-send-mail-using-php/
echo"==================PS COMMAND SNAPSHOT=============================================================="
needs to be
echo "==================PS COMMAND SNAPSHOT=============================================================="
Else, a program or command named echo"===...
is searched.
If you do a grep (-A1: + 1 line context)
grep -A1 "if " cldtest.sh
you find some embedded ifs, and 4 if/then blocks.
grep "fi " cldtest.sh
only reveals 3 matching fi statements. So you forgot one fi too.
I agree with camh, that correct indentation from the beginning helps to avoid such errors. Finding the desired way later means double work in such spaghetti code.
Writing this answer as much for the community as for myself.
If there ever are problems symbolicating a crash report, one can overcome them as follows:
Create a separate folder, copy Foo.app
and Foo.app.dSYM
from the corresponding .xcarchive
into the folder. Also copy the .crash
report into the folder.
Open the crash report in TextEdit or elsewhere, go to the Binary Images:
section, and copy the first address there (e.g. 0xd7000
).
cd
into the folder. Now you can run the following command:
xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 0x0033f9bb
This will symbolicate the symbol at address 0x0033f9bb
. Please make sure to pick the correct value for the -arch
option (can be obtaned from the first line in the Binary Images:
section, or figured out from the Hardware Model:
in the crash report and the app's supported archs).
You can also copy the necessary addresses (e.g. a thread call stack) from the crash report directly into a text file (in TextEdit, hold Option and select the necessary text block, or copy and cut), to get something like this:
0x000f12fb
0x002726b7
0x0026d415
0x001f933b
0x001f86d3
Now you can save this into a text file, e.g. addr.txt
, and run the following command:
xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 -f addr.txt
This will give a nice symbolication for all the addresses at once.
P.S.
Before doing the above, it's worth checking that everything is set up correctly (as atos
will happily report something for basically any supplied address).
To do the checking, open the crash report, and go to the end of the call stack for Thread 0
. The first line from the end to list your app (usually the second one), e.g.:
34 Foo 0x0033f9bb 0xd7000 + 2525627
should be the main()
call. Symbolicating the address (0x0033f9bb
in this case) as described above should confirm that this is indeed main()
and not some random method or function.
If the address is not that of main()
, check your load address (-l
option) and arch (-arch
option).
P.P.S.
If the above doesn't work due to bitcode, download the dSYM for your build from iTunes Connect, extract the executable binary from the dSYM (Finder > Show Package Contents), copy it into the directory, and use it (i.e. Foo
) as the argument to atos
, instead of the Foo.app/Foo
.
var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
$("html, body").animate({
scrollTop: $("#scroll-" + page_id).offset().top
}, 2000)
} else if (page_id == "") {
$("html, body").animate({
scrollTop: $("#scroll-" + page_id).offset().top
}, 2000)
}
});
The errors in ASP.Net are saved on the Server.GetLastError property,
Or i would put a label on the asp.net page for displaying the error.
try
{
do something
}
catch (YourException ex)
{
errorLabel.Text = ex.Message;
errorLabel.Visible = true;
}
There is more than one library for working in C++ in Android programming:
In SQL Plus:
SQL> create procedure myproc (prc out sys_refcursor)
2 is
3 begin
4 open prc for select * from emp;
5 end;
6 /
Procedure created.
SQL> var rc refcursor
SQL> execute myproc(:rc)
PL/SQL procedure successfully completed.
SQL> print rc
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ----------- ---------- ---------- ----------
7839 KING PRESIDENT 17-NOV-1981 4999 10
7698 BLAKE MANAGER 7839 01-MAY-1981 2849 30
7782 CLARKE MANAGER 7839 09-JUN-1981 2449 10
7566 JONES MANAGER 7839 02-APR-1981 2974 20
7788 SCOTT ANALYST 7566 09-DEC-1982 2999 20
7902 FORD ANALYST 7566 03-DEC-1981 2999 20
7369 SMITHY CLERK 7902 17-DEC-1980 9988 11 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1599 3009 30
7521 WARDS SALESMAN 7698 22-FEB-1981 1249 551 30
7654 MARTIN SALESMAN 7698 28-SEP-1981 1249 1400 30
7844 TURNER SALESMAN 7698 08-SEP-1981 1499 0 30
7876 ADAMS CLERK 7788 12-JAN-1983 1099 20
7900 JAMES CLERK 7698 03-DEC-1981 949 30
7934 MILLER CLERK 7782 23-JAN-1982 1299 10
6668 Umberto CLERK 7566 11-JUN-2009 19999 0 10
9567 ALLBRIGHT ANALYST 7788 02-JUN-2009 76999 24 10
In Typescript 3.5+:
interface TypographyProps {
variant: string
fontSize: number
}
type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">
You can add
DBQuery.prototype._prettyShell = true
to your file in $HOME/.mongorc.js
to enable pretty print globally by default.
If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT
(implicitly):
final Instant parsed = Instant.parse(dateTime);
If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
If neither is the case, you can construct a DateTimeFormatter
in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME
is constructed.
Your current pattern has several problems:
ResolverStyle.STRICT
);yyyy
instead of uuuu
(yyyy
will not work in strict mode);hh
instead of 24-hour HH
;S
for fractional seconds, but input has three.Seaching for answer I couldn't find any to be easy and flexible at the same time, then I found the Spring Security Reference and I realized there are near to perfect solutions. AOP solutions often are the greatest ones for testing, and Spring provides it with @WithMockUser
, @WithUserDetails
and @WithSecurityContext
, in this artifact:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
In most cases, @WithUserDetails
gathers the flexibility and power I need.
Basically you just need to create a custom UserDetailsService
with all the possible users profiles you want to test. E.g
@TestConfiguration
public class SpringSecurityWebAuxTestConfig {
@Bean
@Primary
public UserDetailsService userDetailsService() {
User basicUser = new UserImpl("Basic User", "[email protected]", "password");
UserActive basicActiveUser = new UserActive(basicUser, Arrays.asList(
new SimpleGrantedAuthority("ROLE_USER"),
new SimpleGrantedAuthority("PERM_FOO_READ")
));
User managerUser = new UserImpl("Manager User", "[email protected]", "password");
UserActive managerActiveUser = new UserActive(managerUser, Arrays.asList(
new SimpleGrantedAuthority("ROLE_MANAGER"),
new SimpleGrantedAuthority("PERM_FOO_READ"),
new SimpleGrantedAuthority("PERM_FOO_WRITE"),
new SimpleGrantedAuthority("PERM_FOO_MANAGE")
));
return new InMemoryUserDetailsManager(Arrays.asList(
basicActiveUser, managerActiveUser
));
}
}
Now we have our users ready, so imagine we want to test the access control to this controller function:
@RestController
@RequestMapping("/foo")
public class FooController {
@Secured("ROLE_MANAGER")
@GetMapping("/salute")
public String saluteYourManager(@AuthenticationPrincipal User activeUser)
{
return String.format("Hi %s. Foo salutes you!", activeUser.getUsername());
}
}
Here we have a get mapped function to the route /foo/salute and we are testing a role based security with the @Secured
annotation, although you can test @PreAuthorize
and @PostAuthorize
as well.
Let's create two tests, one to check if a valid user can see this salute response and the other to check if it's actually forbidden.
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = SpringSecurityWebAuxTestConfig.class
)
@AutoConfigureMockMvc
public class WebApplicationSecurityTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithUserDetails("[email protected]")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(content().string(containsString("[email protected]")));
}
@Test
@WithUserDetails("[email protected]")
public void givenBasicUser_whenGetFooSalute_thenForbidden() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isForbidden());
}
}
As you see we imported SpringSecurityWebAuxTestConfig
to provide our users for testing. Each one used on its corresponding test case just by using a straightforward annotation, reducing code and complexity.
As you see @WithUserDetails
has all the flexibility you need for most of your applications. It allows you to use custom users with any GrantedAuthority, like roles or permissions. But if you are just working with roles, testing can be even easier and you could avoid constructing a custom UserDetailsService
. In such cases, specify a simple combination of user, password and roles with @WithMockUser.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
factory = WithMockUserSecurityContextFactory.class
)
public @interface WithMockUser {
String value() default "user";
String username() default "";
String[] roles() default {"USER"};
String password() default "password";
}
The annotation defines default values for a very basic user. As in our case the route we are testing just requires that the authenticated user be a manager, we can quit using SpringSecurityWebAuxTestConfig
and do this.
@Test
@WithMockUser(roles = "MANAGER")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(content().string(containsString("user")));
}
Notice that now instead of the user [email protected] we are getting the default provided by @WithMockUser
: user; yet it won't matter because what we really care about is his role: ROLE_MANAGER
.
As you see with annotations like @WithUserDetails
and @WithMockUser
we can switch between different authenticated users scenarios without building classes alienated from our architecture just for making simple tests. Its also recommended you to see how @WithSecurityContext works for even more flexibility.
<table border="1" cellspacing="0" cellpadding= "20">
<tr>
<td id="id1" ></td>
</tr>
</table>
<script>
document.getElementById('id1').style.backgroundColor='#003F87';
</script>
Put id for cell and then change background of the cell.
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
It can be as follows:
UPDATE A
SET A.`id` = (SELECT id from B WHERE A.title = B.title)
The simplest solution is to add a :key attribute to :
<router-view :key="$route.fullPath"></router-view>
This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.
As far as I know nothing like sed is bundled with windows. However, sed is available for Windows in several different forms, including as part of Cygwin, if you want a full POSIX subsystem, or as a Win32 native executable if you want to run just sed on the command line.
Sed for Windows (GnuWin32 Project)
If it needs to be native to Windows then the only other thing I can suggest would be to use a scripting language supported by Windows without add-ons, such as VBScript.
Try this one:
def rm_char(original_str, need2rm):
''' Remove charecters in "need2rm" from "original_str" '''
return original_str.translate(str.maketrans('','',need2rm))
This method works well in python 3.5.2
JOptionPane is your friend : http://www.javalobby.org/java/forums/t19012.html
andorid-support-v4.jar is an external jar file that you have to import into your project.
This is how you do it in Android Studio:
Go to File -> Project Structure
Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"
Select the support library "support-v4 (com.android.support:support-v4:23.0.1)"
Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1'
directly into your dependencies{}
instead of doing it through the GUI.
The POSIX specification for find says:
-mtime
n
The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), isn
.
Interestingly, the description of find
does not further specify 'initialization time'. It is probably, though, the time when find
is initialized (run).
In the descriptions, wherever
n
is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:
+n
More thann
.
n
Exactlyn
.
-n
Less thann
.
At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):
1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00
so:
1409547224 - 1409457540 = 89684
89684 / 86400 = 1
Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).
The n
value calculated for the 2014-08-30 log file therefore is exactly 1
(the calculation is done with integer arithmetic), and the +1
rejects it because it is strictly a > 1
comparison (and not >= 1
).
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
Solved it as follows,
in CSS
#my{
zoom: 100%;
}
Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.
Though this is not the best way to do it, there is another effective solution
Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.
Like @Sunkas wrote, performSelector:withObject:afterDelay:
is the pendant to the dispatch_after
just that it is shorter and you have the normal objective-c
syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject
and you will receive it in the selector
you call:
[self performSelector:@selector(testStringMethod:)
withObject:@"Test Test"
afterDelay:0.5];
- (void)testStringMethod:(NSString *)string{
NSLog(@"string >>> %@", string);
}
If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:
If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,
Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.
This helped me: I created a new maven project which was working fine in my old workspace, but gave above errors in the new workspace. I had to do the following: - Open old workspace on Eclipse - open Preferences tab - Search Maven in filter - Copy the path for settings.xml from User Settings - User Settings - Switch to new workspace - Update the preferences - Maven - User Settings - User Settings path
After the build is completed, all errors are resolved.
Uninstall the Angular CLI and install the latest version of it.
npm uninstall angular-cli
npm install --save-dev @angular/cli@latest
I had to specify individual commands first and then use the *
to bring all in command.
from tkinter import filedialog
from tkinter import *
I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
I have to say I was quite surprised that HttpContext is null inside the constructor. I'm sure it's for performance reasons. Have confirmed that using IPrincipal
as described below does get it injected into the constructor. Its essentially doing the same as the accepted answer, but in a more interfacey-way.
For anyone finding this question looking for an answer to the generic "How to get current user?" you can just access User
directly from Controller.User
. But you can only do this inside action methods (I assume because controllers don't only run with HttpContexts and for performance reasons).
However - if you need it in the constructor (as OP did) or need to create other injectable objects that need the current user then the below is a better approach:
First meet IPrincipal
and IIdentity
public interface IPrincipal
{
IIdentity Identity { get; }
bool IsInRole(string role);
}
public interface IIdentity
{
string AuthenticationType { get; }
bool IsAuthenticated { get; }
string Name { get; }
}
IPrincipal
and IIdentity
represents the user and username. Wikipedia will comfort you if 'Principal' sounds odd.
Important to realize that whether you get it from IHttpContextAccessor.HttpContext.User
, ControllerBase.User
or ControllerBase.HttpContext.User
you're getting an object that is guaranteed to be a ClaimsPrincipal
object which implements IPrincipal
.
There's no other type of User that ASP.NET uses for User
right now, (but that's not to say other something else couldn't implement IPrincipal
).
So if you have something which has a dependency of 'the current user name' that you want injected you should be injecting IPrincipal
and definitely not IHttpContextAccessor
.
Important: Don't waste time injecting IPrincipal
directly to your controller, or action method - it's pointless since User
is available to you there already.
In startup.cs
:
// Inject IPrincipal
services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
Then in your DI object that needs the user you just inject IPrincipal
to get the current user.
The most important thing here is if you're doing unit tests you don't need to send in an HttpContext
, but only need to mock something that represents IPrincipal
which can just be ClaimsPrincipal
.
One extra important thing that I'm not 100% sure about. If you need to access the actual claims from ClaimsPrincipal
you need to cast IPrincipal
to ClaimsPrincipal
. This is fine since we know 100% that at runtime it's of that type (since that's what HttpContext.User
is). I actually like to just do this in the constructor since I already know for sure any IPrincipal
will be a ClaimsPrincipal
.
If you're doing mocking, just create a ClaimsPrincipal
directly and pass it to whatever takes IPrincipal
.
Exactly why there is no interface for IClaimsPrincipal
I'm not sure. I assume MS decided that ClaimsPrincipal
was just a specialized 'collection' that didn't warrant an interface.
Is it possible to select an element if it contains a specific child element?
Unfortunately not yet.
The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.
This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.
An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.
The subject was going to be the element in the selector chain that would have styles applied to it.
Example HTML<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>
This selector would style the span
element
p span {
color: red;
}
This selector would style the p
element
!p span {
color: red;
}
A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()
"
:has()
would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has()
pseudo-selector*.
In any event, continuing the example from above, to select the p
element that contains a span
one could use:
p:has(span) {
color: red;
}
* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
You need to restart the adb server as root. See here.
On Windows use the Xampp shell (there is a 'Shell' button in your XAMPP control panel)
then
cd php\pear
to go to 'C:\xampp\php\pear'
then type
pear
Finally, this is what I did:
private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}
...
File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
You can simple try String(); to remove the quotes.
Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp
Thank me later.
PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
In Windows 7 you could do the following:
Right click on your project and select "Add->Existing Item". In the dialog which appears, browse to the root of the directory you want to add. In the upper right corner you have a search box. Type *.cs
or *.cpp
, whatever the type of files you want to add. After the search finishes, select all files, click Add and wait for a while...
Should be:
SELECT registrationDate,
(SELECT CASE
WHEN COUNT(*)< 2 THEN 'Ama'
WHEN COUNT(*)< 5 THEN 'SemiAma'
WHEN COUNT(*)< 7 THEN 'Good'
WHEN COUNT(*)< 9 THEN 'Better'
WHEN COUNT(*)< 12 THEN 'Best'
ELSE 'Outstanding'
END as a FROM Articles
WHERE Articles.userId = Users.userId) as ranking,
(SELECT COUNT(*)
FROM Articles
WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
Assume you make the access_token
last very long, and don't have refresh_token
, so in one day, hacker get this access_token
and he can access all protected resources!
But if you have refresh_token
, the access_token
's live time is short, so the hacker is hard to hack your access_token
because it will be invalid after short period of time.
Access_token
can only be retrieved back by using not only refresh_token
but also by client_id
and client_secret
, which hacker doesn't have.
It's easy (For Chorme only)
.woff
format) > open link in new tab (this should download the font in .woff
format'simple' code that works and can be read by a ten year old:
function deleteNonEmptyDir($dir)
{
if (is_dir($dir))
{
$objects = scandir($dir);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($dir . "/" . $object) == "dir")
{
deleteNonEmptyDir($dir . "/" . $object);
}
else
{
unlink($dir . "/" . $object);
}
}
}
reset($objects);
rmdir($dir);
}
}
Please note that all I did was expand/simplify and fix (didn't work for non empty dir) the solution here: In PHP how do I recursively remove all folders that aren't empty?
You can use a function like strtol()
which will convert a character array to a long.
It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.
See the following program for an example:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[]) {
int i;
long val;
char *next;
// Process each argument given.
for (i = 1; i < argc; i++) {
// Get value with failure detection.
val = strtol (argv[i], &next, 10);
// Check for empty string and characters left after conversion.
if ((next == argv[i]) || (*next != '\0')) {
printf ("'%s' is not valid\n", argv[i]);
} else {
printf ("'%s' gives %ld\n", argv[i], val);
}
}
return 0;
}
Running this, you can see it in operation:
pax> testprog hello "" 42 12.2 77x
'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid
The main thread is the UI thread, and you cannot do an operation in the main thread which may block the user interaction. You can solve this in two ways:
Force to do the task in the main thread like this
StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);
Or create a simple handler and update the main thread if you want.
Runnable runnable;
Handler newHandler;
newHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
try {
//update UI
} catch (Exception e) {
e.printStackTrace();
}
}
};
newHandler.post(runnable);
And to stop the thread use:
newHandler.removeCallbacks(runnable);
For more information check this out: Painless threading
A full .Net solution is to use the classes from the System.DirectoryServices namespace. They allow to query an AD server directly. Here is a small sample that would do this:
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Username = "here goes the username you want to validate";
entry.Password = "here goes the password";
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(objectclass=user)";
try
{
searcher.FindOne();
}
catch (COMException ex)
{
if (ex.ErrorCode == -2147023570)
{
// Login or password is incorrect
}
}
}
// FindOne() didn't throw, the credentials are correct
This code directly connects to the AD server, using the credentials provided. If the credentials are invalid, searcher.FindOne() will throw an exception. The ErrorCode is the one corresponding to the "invalid username/password" COM error.
You don't need to run the code as an AD user. In fact, I succesfully use it to query informations on an AD server, from a client outside the domain !
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
I also almost exclusively use Vim (almost because I'm trying to learn emacs now) for all my development stuff. I think sheer intuitiveness (from the GUI of course) is the primary reason why people like to use IDEs. By being intuitive, little to no learning overhead of the tool is required. The lesser the learning overhead, the more they can get work done.
Look into composite formatting:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
You could also write (although it's not really recommended):
Console.WriteLine(mon + "." + da + "." + yer);
And, with the release of C# 6.0, you have string interpolation expressions:
Console.WriteLine($"{mon}.{da}.{yer}"); // note the $ prefix.
I faced the same issue but the reason was none of the ones listed above. I created a task, created a scope inside the task and asked the container to obtain a service. That worked fine but then I used a second service inside the task and I forgot to also asked for it to the new scope. Because of that, the 2nd service was using a DbContext that was already disposed.
Task task = Task.Run(() =>
{
using (var scope = serviceScopeFactory.CreateScope())
{
var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
// everything was ok here. then I did:
productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.
...
}
}
I should have done this:
var otherProductService = scope.ServiceProvider.GetService<IProductService>();
otherProductService.DoSomething();
At first I thought the Paste Special was the holy grail! But then I tried it and my hair turned white just like the Indiana Jones movie.
But now I use http://xmltocsharp.azurewebsites.net/ and now I'm as young as ever.
Here's a segment of what it generated:
namespace Xml2CSharp
{
[XmlRoot(ElementName="entry")]
public class Entry {
[XmlElement(ElementName="hybrisEntryID")]
public string HybrisEntryID { get; set; }
[XmlElement(ElementName="mapicsLineSequenceNumber")]
public string MapicsLineSequenceNumber { get; set; }
My scenario:
eg.
a.button { background-image: url(this.png; }
I found that applying the mark-up provided by Dan Tello didn't work.
However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.
eg.
a.button span { background-image: url(this.png; }
There is an alternative approach I used when I couldn't rely on the EXCEPTION
block at the bottom of my procedure. I had variables declared at the beginning:
my_value VARCHAR := 'default';
number_rows NUMBER := 0;
.
.
.
SELECT count(*) FROM TABLE INTO number_rows (etc.)
IF number_rows > 0 -- Then obtain my_value with a query or constant, etc.
END IF;
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
In BOOTSTRAP 4 you can use
<div class="row m-0">
my fullwidth div
</div>
... if you just use a .row without the .m-0 as a top level div, you will have unwanted margin, which makes the page wider than the browser window and cause a horizontal scrollbar.
For quick reference, all the following methods will add a new key 'a' if it does not exist already or it will update the existing key value pair with the new value offered:
data['a']=1
data.update({'a':1})
data.update(dict(a=1))
data.update(a=1)
You can also mixing them up, for example, if key 'c' is in data but 'd' is not, the following method will updates 'c' and adds 'd'
data.update({'c':3,'d':4})
If you need access to the index as you iterate through the string, use enumerate()
:
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t
This code will show an error like
Table[0] can not be found!
because there will not be any table in position 0.
if (ds.Tables[0].Rows.Count == 0)
{
//
}
Nothing.
$('#content').click(function(e) {
alert(1);
});
Will bind to an existing HTML element with the ID set to content
, and will show a message box on click.
#content
exists before using that codeI recently encountered this problem while working on a contract project(deemed classified). The system in which I had to run the code did not have internet access, for security purposes of course, and so installing dependencies, using composer and npm, was becoming huge pain.
After much deliberation with my colleague, we decided to just wing it and copy paste our dependencies rather than doing composer install or npm install.
This led us to NOT add vendors and npm_modules in gitignore. This is when I encountered this problem.
Changed but not updated:
modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content)
I googled this a bit and found this helpful thread on SO. Not being too much of a pro in Git, and being a little intoxicated while working on it, I just searched for all the submodules in the vendors folder
find . -name ".git"
This gave me some 4-5 dependencies that had git on them. I removed all these .git folders and voila, it worked. I knows it's hack, and not a very geeky one anyways. O Gods of SO, please forgive me! Next time I promise to read up on gitlinks and obey O mighty Linus Tovalds.
find triggers on table:
select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%TableName%'
and you can find store procedure which has reference of table:
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%yourtablename%'
Most of the solutions consider that the lists do not have duplicates. In case your lists do have duplicates you can try this:
def isSubList(subList,mlist):
uniqueElements=set(subList)
for e in uniqueElements:
if subList.count(e) > mlist.count(e):
return False
# It is sublist
return True
It ensures the sublist never has different elements than list or a greater amount of a common element.
lst=[1,2,2,3,4]
sl1=[2,2,3]
sl2=[2,2,2]
sl3=[2,5]
print(isSubList(sl1,lst)) # True
print(isSubList(sl2,lst)) # False
print(isSubList(sl3,lst)) # False
Alt+H, then type letters FC, then pick the color.
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
Since the question was labeled with Github
, adding another remote like https_origin
and add the https
connection can force you always to enter the password:
git remote add https_origin https://github.com/.../...
If you've got VS2010
installed, you ought to find a .NET 4.0 gacutil at
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
The 7.0A Windows SDK
should have been installed alongside VS2010 - 6.0A
will have been installed with VS2008
, and hence won't have .NET 4.0 support.
By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as
A div can can hold more than one classes either using bootstrap or not
<div class="active dropdown-toggle my-class">Multiple Classes</div>
For applying multiple classes just separate the classes by space.
Take a look at this links you will find many examples
http://getbootstrap.com/css/
http://css-tricks.com/un-bloat-css-by-using-multiple-classes/
See "The Evils of the For Loop" for a good explanation (there's one small difference considering variable scoping).
Using each
is considered more idiomatic use of Ruby.
Null
refers to an absence of data. Null
is formally defined as a value that is unavailable, unassigned, unknown or inapplicable (OCA Oracle Database 12c, SQL Fundamentals I Exam Guide, p87).
So, you may not see records with columns containing null values when said columns are restricted using an "in" or "not in" clauses.
Workable solution:
downloadCSV(data){
const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const fileData = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = fileData;
link.download = `Usecase-Unprocessed.csv`;
// this is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
setTimeout(function () {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(fileData);
link.remove();
}, 5000);
}
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.