I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
If you are in a linux environment all you have to do is to create a symlink to your .jar file from inside /etc/init.d/
sudo ln -s /path/to/your/myboot-app.jar /etc/init.d/myboot-app
Then you can start the application like any other service
sudo /etc/init.d/myboot-app start
To close the application
sudo /etc/init.d/myboot-app stop
This way, application will not terminate when you exit the terminal. And application will shutdown gracefully with stop command.
jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
link Couting characters, words, lenght of the words and total lenght in a sentence
I just wanted to contribute this should someone be looking for help with adding separators between the strings, depending on whether a field is NULL or not.
So in the example of creating a one line address from separate fields
Address1, Address2, Address3, City, PostCode
in my case, I have the following Calculated Column which seems to be working as I want it:
case
when [Address1] IS NOT NULL
then ((( [Address1] +
isnull(', '+[Address2],'')) +
isnull(', '+[Address3],'')) +
isnull(', '+[City] ,'')) +
isnull(', '+[PostCode],'')
end
Hope that helps someone!
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
Some awk
version.
awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'
When pattern found, set c=5
If c
is true, print and decrease number of c
Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".
I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.
There is a step by step explanation (with pictures) available @ Restore DataBase
Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
This will bring up the Connect to Server dialog box.
Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
Click Connect.
On the right, right-click Databases and select Restore Database.
This will bring up the Restore Database window.
On the Restore Database screen, select the From Device radio button and click the "..." box.
This will bring up the Specify Backup screen.
On the Specify Backup screen, click Add.
This will bring up the Locate Backup File.
Select the DBBackup folder and chose your BackUp File(s).
On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.
You're done.
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
The profiler trace puts it into perspective.
Query B is using parallelism: CPU > duration eg the query uses 2 CPUs, average 1.15 secs each
Query A is probably not: CPU < duration
This explains cost relative to batch: 17% of the for the simpler, non-parallel query plan.
The optimiser works out that query B is more expensive and will benefit from parallelism, even though it takes extra effort to do so.
Remember though, that query B uses 100% of 2 CPUS (so 50% for 4 CPUs) for one second or so. Query A uses 100% of a single CPU for 1.5 seconds.
The peak for query A is lower, at the expense of increased duration. With one user, who cares? With 100, perhaps it makes a difference...
These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
Though insertBefore()
(see MDN) is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:
insertAdjacentElement()
(see MDN) This lets you reference any element, and insert the to-be moved element exactly where you want:
<!-- refElem.insertAdjacentElement('beforebegin', moveMeElem); -->
<p id="refElem">
<!-- refElem.insertAdjacentElement('afterbegin', moveMeElem); -->
... content ...
<!-- refElem.insertAdjacentElement('beforeend', moveMeElem); -->
</p>
<!-- refElem.insertAdjacentElement('afterend', moveMeElem); -->
Others to consider for similar use cases: insertAdjacentHTML()
and insertAdjacentText()
References:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText
Multi-line buttons like that are not really trivial to implement. This page has an interesting (though somewhat dated) discussion on the subject. Your best bet would probably be to either drop the multi-line requirement or to create a custom button using e.g. div
s and CSS, and adding some JavaScript to make it work as a button.
Solution with method String::repeat (Java 11)
String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;
If needed change 8 to another number or parameterize it
I have always had to write some PL/SQL for this or I just concatenate a ',' to the field and copy into an editor and remove the CR from the list giving me the single line.
That is,
select country_name||', ' country from countries
A little bit long winded both ways.
If you look at Ask Tom you will see loads of possible solutions but they all revert to type declarations and/or PL/SQL
I use a CSS fix rather than JS to workaround my round cornered layer with transparent PNG inside
Try
.ie .whateverDivWrappingTheImage img { background: #ffaabb; /* this should be the background color matching your design actually */ filter: chroma(#ffaabb); /* and this should match whatever value you put in background-color */ }
This may require more work on ie9 or later.
Note: MDN gives a method using a while loop:
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
I wouldn't say it's any better than other answers. Just interesting.
127 means command not found
In your case, curl command was not found. Therefore it means, curl was not found.
You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html
Close RStudio before installation.
Another simple solution with +=
:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
Trying with a different version of gcc worked for me - gcc 4.9 in my case.
You can use the following function to select content of any element:
jQuery.fn.selectText = function(){
this.find('input').each(function() {
if($(this).prev().length == 0 || !$(this).prev().hasClass('p_copy')) {
$('<p class="p_copy" style="position: absolute; z-index: -1;"></p>').insertBefore($(this));
}
$(this).prev().html($(this).val());
});
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
This function can be called as follows:
$('#selectme').selectText();
after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.
We are now in 2018 and hoola, there is a way to implement WS and WAMPServer on php. It 's Called Ratchet.
Based on Ivan Laharnar with less code and simplier:
declare
lastSeq number;
begin
SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
if lastSeq IS NULL then lastSeq := 1; end if;
execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;
I have combine two different answers:
Complete HTML missing tags
$string = strip_tags($strHTML);
$yourText = $strHTML;
if (strlen($string) > 350) {
$stringCut = substr($post->body, 0, 350);
$doc = new DOMDocument();
$doc->loadHTML($stringCut);
$yourText = $doc->saveHTML();
}
$yourText."...<a href=''>View More</a>"
Take a closer look at the ?axis
documentation. If you look at the description of the labels
argument, you'll see that it is:
"a logical value specifying whether (numerical) annotations are
to be made at the tickmarks,"
So, just change it to true, and you'll get your tick labels.
x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)
Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.
It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis
into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.
Just run into this one of longest thread, below is my solution:
parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)
Let me know if anyone can poke a hole
For my project, I am set up to use https
. I just got a new computer and cloned the project in git. The protocol and port number for the project are not saved in the solution file, so you have to make sure to set it again.
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.
Specify /D
to change the drive also.
CD /D %root%
Following the accepted answer by ChrLipp using Android Studio 1.2.2 in Ubuntu 14.04:
This worked for me. Try rebooting your system if it is not working for you.
In Alamofire 4 it is important to add the body data before you add the file data!
let parameters = [String: String]()
[...]
self.manager.upload(
multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")
},
to: path,
[...]
)
I'd probably use a LEFT JOIN
, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULL
s.
So, something like:
SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL
Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.
To answer the first:
UPDATE Orders SET Quantity = Quantity + 1 WHERE ...
To answer the second:
There are several ways to do this. Since you did not specify a database, I will assume MySQL.
INSERT INTO table SET x=1, y=2 ON DUPLICATE KEY UPDATE x=x+1, y=y+2
REPLACE INTO table SET x=1, y=2
They both can handle your question. However, the first syntax allows for more flexibility to update the record rather than just replace it (as the second one does).
Keep in mind that for both to exist, there has to be a UNIQUE key defined...
UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.
While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]Math.random
)Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.
Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:
function simulatedClick(target, options) {
var event = target.ownerDocument.createEvent('MouseEvents'),
options = options || {},
opts = { // These are the default values, set up for un-modified left clicks
type: 'click',
canBubble: true,
cancelable: true,
view: target.ownerDocument.defaultView,
detail: 1,
screenX: 0, //The coordinates within the entire page
screenY: 0,
clientX: 0, //The coordinates within the viewport
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
button: 0, //0 = left, 1 = middle, 2 = right
relatedTarget: null,
};
//Merge the options with the defaults
for (var key in options) {
if (options.hasOwnProperty(key)) {
opts[key] = options[key];
}
}
//Pass in the options
event.initMouseEvent(
opts.type,
opts.canBubble,
opts.cancelable,
opts.view,
opts.detail,
opts.screenX,
opts.screenY,
opts.clientX,
opts.clientY,
opts.ctrlKey,
opts.altKey,
opts.shiftKey,
opts.metaKey,
opts.button,
opts.relatedTarget
);
//Fire the event
target.dispatchEvent(event);
}
Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html
You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId'))
would work.
You can pass in an object into options
to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.
I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.
To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:
C#: ///
VB: '''
See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
In Wordpress jQuery.noConflict()
is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $
doesn't work, but jQuery
does, so your code should look like this:
<script type="text/javascript">
jQuery(function($) {
for(var i=0; i <= 20; i++)
$("ol li:nth-child(" + i + ")").addClass('olli' + i);
});
</script>
True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.
Try comparing the value of the column to the DBNull.Value
value to filter and manage null values in whatever way you see fit.
foreach(DataRow row in table.Rows)
{
object value = row["ColumnName"];
if (value == DBNull.Value)
// do something
else
// do something else
}
More information about the DBNull class
If you want to check if a null value exists in the table you can use this method:
public static bool HasNull(this DataTable table)
{
foreach (DataColumn column in table.Columns)
{
if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
return true;
}
return false;
}
which will let you write this:
table.HasNull();
If you're using a relatively new version of Python, you can also use a context manager, such as this one:
from __future__ import with_statement
from grizzled.os import working_directory
with working_directory(path_to_directory):
# code in here occurs within the directory
# code here is in the original directory
UPDATE
If you prefer to roll your own:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
You can try this:
import os
current_dir = os.path.dirname(os.path.abspath(__file__)) # Can also use os.getcwd()
print(current_dir) # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')
print(new_dir) # prints "D:\abc\def\ghi"
update(
{_id: 1, 'items.id': 2},
{'$set': {'items.$[]': update}},
{new: true})
Here is the doc about $[]
: https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[]
Use x.fullNameMethod()
to call the method.
To get your radio button to list horizontally , just add
RepeatDirection="Horizontal"
to your .aspx file where the asp:radiobuttonlist is being declared.
It seems that <TouchableHighlight>
must have exactly one child. The docs say that it supports only one child and more than one must be wrapped in a <View>
, but not that it must have at least (and most) one child. I just wanted to have a plain coloured button with no text/image, so I didn't deem it necessary to add a child.
I'll try to update the docs to indicate this.
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "="
in the scope. Here's three solutions depending on your situation.
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use $observe
or $watch
:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// observe changes in attribute - could also be scope.$watch
attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
scope.variable = value;
}
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// observe changes in attribute - could also be scope.$watch
$attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
$scope.variable = value;
}
});
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Note that you should not set the variable to "="
in the scope, if you are using the $observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout
to wait until the $apply
has run. Also we need to use $emit
to send it to the parent scope app controller (due to the isolated scope in the directive):
app.directive('yourDirective', ['$timeout', function ($timeout) {
return {
restrict: 'A',
// NB: isolated scope!!
scope: {
yourDirective: '='
},
link: function (scope, element, attrs) {
// wait until after $apply
$timeout(function(){
console.log(scope.yourDirective);
// use scope.$emit to pass it to controller
scope.$emit('notification', scope.yourDirective);
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: [ '$scope', function ($scope) {
// wait until after $apply
$timeout(function(){
console.log($scope.yourDirective);
// use $scope.$emit to pass it to controller
$scope.$emit('notification', scope.yourDirective);
});
}]
};
}])
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$on('notification', function (evt, value) {
console.log(value);
$scope.variable = value;
});
}]);
And here's the html (no brackets!):
<div ng-controller="MyCtrl">
<div your-directive="someObject.someVariable"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
If your variable is not changing and you need to evaluate it in your directive, you can use the $eval
function:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval(attrs.yourDirective);
console.log(scope.variable);
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval($attrs.yourDirective);
console.log($scope.variable);
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
There is another way to add google repository
Add gradle-4.1-rc-1-all
in gradle-wrapper.properties.
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-rc-1-all.zip
Then add google()
in the top-level build.gradle
allprojects {
repositories {
google()
jcenter()
}
}
This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row
<div class="row" >
<div class="span9">
<%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>
</div>
</div>
It could be something like that:
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
_x000D_
See splice Array's method.
You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
span {
font-size:12px;
}
a {
color:green;
}
.test1>a:hover span {
display:none;
}
.test1>a:hover:before {
color:red;
content:"Apple";
}
</style>
</head>
<body>
<div class="test1">
<a href="#"><span>Google</span></a>
</div>
<div class="test2">
<a href="#"><span>Apple</span></a>
</div>
</body>
</html>
Note: The hover:before switch works only on the .test1 class
As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)
However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).
The script below relies on JQuery
/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;
/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
$.get("<whatever url will end your session>");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
This script may be included in all pages
<script type="text/javascript" src="js/autoLogoff.js"></script>
Let's go through this code:
var validNavigation = false;
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.
An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.
function endSession() {
$.get("<whatever url will end your session>");
}
The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session
This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function showButtons () { $('#b1, #b2, #b3').show(); }
</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}
</style>
</head>
<body>
<a href="#" onclick="showButtons();">Show me the money!</a>
<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />
</body>
</html>
svn revert filename
this should revert a single file.
What about the official JDBC 4.0 compatible JDBC driver from Microsoft?
$(function(){
var search = 'foo';
$("table tr td").filter(function() {
return $(this).text() == search;
}).parent('tr').css('color','red');
});
Will turn the text red for rows which have a cell whose text is 'foo'.
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
I also faced this issue and failed to figure out the reason for the same for sometimes. Later i found that auto import issue using IDE. That is imports of the program.
Basically i was using eclipse IDE. And I was importing a wrong class "org.junit.jupiter.api.Test"
into the program instead of required class "org.junit.Test".
Hence check your imports before running any programs.
Here's a solution if you just want to update certain components on a page:
In template
<Component1 :key="forceReload" />
<Component2 :key="forceReload" />
In data
data() {
return {
forceReload: 0
{
}
In methods:
Methods: {
reload() {
this.forceReload += 1
}
}
Use a unique key and bind it to a data property for each one you want to update (I typically only need this for a single component, two at the most. If you need more, I suggest just refreshing the full page using the other answers.
I learned this from Michael Thiessen's post: https://medium.com/hackernoon/the-correct-way-to-force-vue-to-re-render-a-component-bde2caae34ad
<button onclick=location=URL>Refresh</button>
This might look funny but it really does the trick.
Below code for disabled links:
<a href="javascript: void(0)">test disabled link</a>
another very simple solution is:
<a href="#">test disabled link</a>
First solution is efficient.
For the simple case of just copying the last commit from branch wss to v2.1, you can simply grab the commit id (git log --oneline | head -n 1
) and do:
git checkout v2.1
git merge <commit>
if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:
rm /tmp/wsdl-*
Another option is to use Apple Keynote on a Mac (Libre Office couldn't event open a pptx I had) to save the presentation to HTML5. It does a pretty good job to produce exactly what it displays in keynote, e.g. it includes animations and video. Compatibility of keynote to powerpoint has it's limits though (independent of the export).
Some file no load before you call.
For example: Your code:
<%= javascript_include_tag "distpicker.min" %>
<%= javascript_include_tag "distpicker.data.min" %>
Change to this:
<%= javascript_include_tag "distpicker.data.min" %>
<%= javascript_include_tag "distpicker.min" %>
Your server is imposing some resource limit that your site is hitting. This is usually RAM, CPU, or INODES.
Ask your server administrator what the limits are and what it is you are hitting to solve.
The SQL Server login required is DOMAIN\machinename$
. This is the how the calling NT AUTHORITY\NETWORK SERVICE
appears to SQL Server (and file servers etc)
In SQL,
CREATE LOGIN [XYZ\Gandalf$] FROM WINDOWS
You can do something like this:
int days[] = { /*length:*/5, /*values:*/ 1,2,3,4,5 };
int *ptr = days + 1;
printf("array length: %u\n", ptr[-1]);
return 0;
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
If you want to use names, try a namedtuple:
from collections import namedtuple
Pair = namedtuple("Pair", ["first", "second"])
pairs = [Pair("a", 1), Pair("b", 2), Pair("c", 3)]
for pair in pairs:
print("First = {}, second = {}".format(pair.first, pair.second))
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
When you use docker run
to start a container, it actually creates a new container based on the image you have specified.
Besides the other useful answers here, note that you can restart an existing container after it exited and your changes are still there.
docker start f357e2faab77 # restart it in the background
docker attach f357e2faab77 # reattach the terminal & stdin
To connect from Terminal to AWS AMI:
chmod 400 mykey.pem
ssh -i mykey.pem [email protected]
It would seem that the attr functionality is getting further deprecated
$(this).attr('TYPE')
undefined
$(this).prop('type')
"text"
Try installing the xorg-x11-xauth package.
One of my friends is writing a graphics app using NVIDIA CUDA. Application fits in very nicely with OOP paradigm and the problem can be decomposed into modules neatly. However, to use CUDA you need to use C, which doesn't support inheritance. Therefore, you need to be clever.
a) You devise a clever system which will emulate inheritance to a certain extent. It can be done!
i) You can use a hook system, which expects every child C of parent P to have a certain override for function F. You can make children register their overrides, which will be stored and called when required.
ii) You can use struct memory alignment feature to cast children into parents.
This can be neat but it's not easy to come up with future-proof, reliable solution. You will spend lots of time designing the system and there is no guarantee that you won't run into problems half-way through the project. Implementing multiple inheritance is even harder, if not almost impossible.
b) You can use consistent naming policy and use divide and conquer approach to create a program. It won't have any inheritance but because your functions are small, easy-to-understand and consistently formatted you don't need it. The amount of code you need to write goes up, it's very hard to stay focused and not succumb to easy solutions (hacks). However, this ninja way of coding is the C way of coding. Staying in balance between low-level freedom and writing good code. Good way to achieve this is to write prototypes using a functional language. For example, Haskell is extremely good for prototyping algorithms.
I tend towards approach b. I wrote a possible solution using approach a, and I will be honest, it felt very unnatural using that code.
If you want to validate your date(YYYY-MM-DD)
along with the comparison it will be use full for you...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}
SELECT
MyParts.*,MyPriceDate.Price,MyPriceDate.PriceDate
FROM MyParts
INNER JOIN (SELECT Partid, MAX(PriceDate) AS MaxPriceDate FROM MyPrice GROUP BY Partid) dt ON MyParts.Partid = dt.Partid
INNER JOIN MyPrice ON dt.Partid = MyPrice.Partid AND MyPrice.PriceDate=dt.MaxPriceDate
You can use row_number()
to get the row number of the row. It uses the over
command - the partition by
clause specifies when to restart the numbering and the order by
selects what to order the row number on. Even if you added an order by
to the end of your query, it would preserve the ordering in the over
command when numbering.
select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1
Here is my attempt, using Node's assert module + npm package object-hash.
I suppose that you would like to check if two arrays contain the same objects, even if those objects are ordered differently between the two arrays.
var assert = require('assert');
var hash = require('object-hash');
var obj1 = {a: 1, b: 2, c: 333},
obj2 = {b: 2, a: 1, c: 444},
obj3 = {b: "AAA", c: 555},
obj4 = {c: 555, b: "AAA"};
var array1 = [obj1, obj2, obj3, obj4];
var array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well
// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)
// even if array1 and array2 contain the same objects in different order,
// because array1[0].c !== array2[0].c
// sort objects in arrays by their hashes, so that if the arrays are identical,
// their objects can be compared in the same order, one by one
var array1 = sortArrayOnHash(array1);
var array2 = sortArrayOnHash(array2);
// then, this should output "PASS"
try {
assert.deepEqual(array1, array2);
console.log("PASS");
} catch (e) {
console.log("FAIL");
console.log(e);
}
// You could define as well something like Array.prototype.sortOnHash()...
function sortArrayOnHash(array) {
return array.sort(function(a, b) {
return hash(a) > hash(b);
});
}
Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine. The only solution is to fetch the page from the server side code and change the needed CSS.
In Postgres 9.4 or later, this is simplest and fastest:
SELECT c.*
FROM comments c
JOIN unnest('{1,3,2,4}'::int[]) WITH ORDINALITY t(id, ord) USING (id)
ORDER BY t.ord;
WITH ORDINALITY
was introduced with in Postgres 9.4.
No need for a subquery, we can use the set-returning function like a table directly. (A.k.a. "table-function".)
A string literal to hand in the array instead of an ARRAY constructor may be easier to implement with some clients.
For convenience (optionally), copy the column name we are joining to (id
in the example), so we can join with a short USING
clause to only get a single instance of the join column in the result.
Detailed explanation:
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...)
function. For instance, I wanted 3 decimal places:
double value = 34.0495834;
QString strValue = QString::number(value, 'f', 3);
// strValue == "34.050"
The 'f'
specifies decimal format notation (more info here, you can also specify scientific notation) and the 3
specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number
function can be found here in the QString
documentation
This function, with a given parent directory
iterates over all its directories
recursively and prints
all the filenames
which it founds inside. Too useful.
import os
def printDirectoryFiles(directory):
for filename in os.listdir(directory):
full_path=os.path.join(directory, filename)
if not os.path.isdir(full_path):
print( full_path + "\n")
def checkFolders(directory):
dir_list = next(os.walk(directory))[1]
#print(dir_list)
for dir in dir_list:
print(dir)
checkFolders(directory +"/"+ dir)
printDirectoryFiles(directory)
main_dir="C:/Users/S0082448/Desktop/carpeta1"
checkFolders(main_dir)
input("Press enter to exit ;")
I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.
*Answering your question, system variable has higher priority *
@Component
@Profile("dev")
public class DatasourceConfigForDev
Now, the profile is dev
Note : if the Profile is given as
@Profile("!dev")
then the profile will exclude dev and be for all others.
<beans profile="dev">
<bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("spring.profiles.active", "dev");
}
}
@Autowired
private ConfigurableEnvironment env;
// ...
env.setActiveProfiles("dev");
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
The profile names passed as the parameter will be activated during application start-up:
-Dspring.profiles.active=dev
In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:
to set via command line : export spring_profiles_active=dev
Any bean that does not specify a profile belongs to “default” profile.
CSS:
selector{
padding:0 0 10px 0; // Top left bottom right
}
Another answer relies on the third-to-last character being a space. This will work with (almost) any character in that position and does it "WITHOUT using sed, or perl, etc.":
while read -r line
do
echo ${line:0:${#line}-3}
done
If your lines are fixed length change the echo
to:
echo ${line:0:9}
or
printf "%.10s\n" "$line"
but each of these is definitely much slower than sed
.
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
A reference to a pointer is possible in C++, but the reverse is not possible means a pointer to a reference isn't possible. A reference to a pointer provides a cleaner syntax to modify the pointer. Look at this example:
#include<iostream>
using namespace std;
void swap(char * &str1, char * &str2)
{
char *temp = str1;
str1 = str2;
str2 = temp;
}
int main()
{
char *str1 = "Hi";
char *str2 = "Hello";
swap(str1, str2);
cout<<"str1 is "<<str1<<endl;
cout<<"str2 is "<<str2<<endl;
return 0;
}
And consider the C version of the above program. In C you have to use pointer to pointer (multiple indirection), and it leads to confusion and the program may look complicated.
#include<stdio.h>
/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
int main()
{
char *str1 = "Hi";
char *str2 = "Hello";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
return 0;
}
Visit the following for more information about reference to pointer:
As I said, a pointer to a reference isn't possible. Try the following program:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int *ptr = &x;
int &*ptr1 = ptr;
}
It's basically a shorthand. So instead of having to write:
this.props.dispatch(toggleTodo(id));
You would use mapDispatchToProps as shown in your example code, and then elsewhere write:
this.props.onTodoClick(id);
or more likely in this case, you'd have that as the event handler:
<MyComponent onClick={this.props.onTodoClick} />
There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist
Thanks for the ideas! I used the above ideas to make a macro to do a bulk file conversion--convert every file of one format in a folder to another format.
This code requires a sheet with cells named "FilePath" (which must end in a "\"), "StartExt" (original file extension), and "EndExt" (desired file extension). Warning: it doesn't ask for confirmation before replacing existing files with the same name and extension.
Private Sub CommandButton1_Click()
Dim path As String
Dim pathExt As String
Dim file As String
Dim oldExt As String
Dim newExt As String
Dim newFile As String
Dim shp As Picture
Dim chrt As ChartObject
Dim chrtArea As Chart
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Get settings entered by user
path = Range("FilePath")
oldExt = Range("StartExt")
pathExt = path & "*." & oldExt
newExt = Range("EndExt")
file = Dir(pathExt)
Do While Not file = "" 'cycle through all images in folder of selected format
Set shp = ActiveSheet.Pictures.Insert(path & file) 'Import image
newFile = Replace(file, "." & oldExt, "." & newExt) 'Determine new file name
Set chrt = ActiveSheet.ChartObjects.Add(0, 0, shp.Width, shp.Height) 'Create blank chart for embedding image
Set chrtArea = chrt.Chart
shp.CopyPicture 'Copy image to clipboard
With chrtArea 'Paste image to chart, then export
.ChartArea.Select
.Paste
.Export (path & newFile)
End With
chrt.Delete 'Delete chart
shp.Delete 'Delete imported image
file = Dir 'Advance to next file
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
When i had the issue i saved the value into a hidden input:
in html body:
<body>
<?php
if (isset($_POST['Id'])){
$fid= $_POST['Id'];
}
?>
... then put the hidden input on the page and write the value $fid with php echo
<input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">
then in $(document).ready( function () {
var postId=document.getElementById("fid").value;
so i got my hidden url parameter in php an js.
It is actually possible.
See: CSS Tip: How to Make Circles Without Images. See demo.
But be warned, It has serious disadvantages in terms of compatibility basically, you are making a cat bark.
See it working here
As you will see you just have to set up the height
and width
to half the border-radius
Good luck!
Short of granting access to DBMS_LOCK.sleep
, this will work but it's a horrible hack:
IN_TIME INT; --num seconds
v_now DATE;
-- 1) Get the date & time
SELECT SYSDATE
INTO v_now
FROM DUAL;
-- 2) Loop until the original timestamp plus the amount of seconds <= current date
LOOP
EXIT WHEN v_now + (IN_TIME * (1/86400)) <= SYSDATE;
END LOOP;
You have 9 fields listed, but only 8 values. Try adding the method.
The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.
So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.
One way to convert a string to an integer is to use the int function. For example:
percent = (int(pyc) / int(tpy)) * 100
The direct replacement is if
/elif
/else
.
However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".
Popen expect a list of strings for non-shell calls and a string for shell calls.
Call subprocess.Popen with shell=True:
process = subprocess.Popen(command, stdout=tempFile, shell=True)
Hopefully this solves your issue.
This issue is listed here: https://bugs.python.org/issue17023
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the
USER32
box.B) In the All Event IDs field, type
1074
, then click/tap on OK.C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type
6008
, then click/tap on OK.B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....
I have found that %CD%
gives the path the script was called from and not the path of the script, however, %~dp0
will give the path of the script itself.
TempData
is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.
To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.
Hope this helps.
This answer doesn't necessarily scale but only requires minor adjustments as the list grows. Semantically it might seem a little counter-intuitive since it is two lists, but aside from that it'll look the way you want in any browser ever made.
ul {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
ul > li {_x000D_
width: 6em;_x000D_
}
_x000D_
<!-- Column 1 -->_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 2</li>_x000D_
<li>Item 3</li>_x000D_
</ul>_x000D_
<!-- Column 2 -->_x000D_
<ul>_x000D_
<li>Item 4</li>_x000D_
<li>Item 5</li>_x000D_
<li>Item 6</li>_x000D_
</ul>
_x000D_
Update for CXF 3.1.7
In my case I put the WSDL files in src/main/resources
and added this path to my Srouces in Eclipse (Right Click on Project-> Build Path -> Configure Build Path...-> Source[Tab] -> Add Folder).
Here is how my pom
file looks like and as can be seen there is NO wsdlLocation
option needed:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>classpath:wsdl/FOO_SERVICE.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
And here is the generated Service. As can be seen the URL is get from ClassLoader and not from the Absolute File-Path
@WebServiceClient(name = "EventService",
wsdlLocation = "classpath:wsdl/FOO_SERVICE.wsdl",
targetNamespace = "http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/")
public class EventService extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventService");
public final static QName EventPort = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventPort");
static {
URL url = EventService.class.getClassLoader().getResource("wsdl/FOO_SERVICE.wsdl");
if (url == null) {
java.util.logging.Logger.getLogger(EventService.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "classpath:wsdl/FOO_SERVICE.wsdl");
}
WSDL_LOCATION = url;
}
The answer for git branch -r --contains <commit>
works well for normal remote branches, but if the commit is only in the hidden head
namespace that GitHub creates for PRs, you'll need a few more steps.
Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r
doesn't know about PR #42 because refs like refs/pull/42/head
aren't listed as a remote branch by default.
In .git/config
for the [remote "origin"]
section add a new line:
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
(This gist has more context.)
Then when you git fetch
you'll get all the PR branches, and when you run git branch -r --contains <commit>
you'll see origin/pr/42
contains the commit.
use js to prevent add data:
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
It is very simple to update using Inner join query in SQL .You can do it without using FROM
clause. Here is an example :
UPDATE customer_table c
INNER JOIN
employee_table e
ON (c.city_id = e.city_id)
SET c.active = "Yes"
WHERE c.city = "New york";
Interestingly, base R aggregate
's data.frame
method is not showcased here, above the formula interface is used, so for completeness:
aggregate(
x = df1[c("x1", "x2")],
by = df1[c("year", "month")],
FUN = sum, na.rm = TRUE
)
More generic use of aggregate's data.frame method:
Since we are providing a
data.frame
as x
and list
(data.frame
is also a list
) as by
, this is very useful if we need to use it in a dynamic manner, e.g. using other columns to be aggregated and to aggregate by is very simpleFor example like so:
colsToAggregate <- c("x1")
aggregateBy <- c("year", "month")
dummyaggfun <- function(v, na.rm = TRUE) {
c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
}
aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)
You can register a route change listener on your main component and scroll to top on route changes.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
}
For "polling" transport.
Apache side:
<VirtualHost *:80>
ServerName mysite.com
DocumentRoot /my/path
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /my-connect-3001 http://127.0.0.1:3001/socket.io
ProxyPassReverse /my-connect-3001 http://127.0.0.1:3001/socket.io
</VirtualHost>
Client side:
var my_socket = new io.Manager(null, {
host: 'mysite.com',
path: '/my-connect-3001'
transports: ['polling'],
}).socket('/');
As of API 21, you could also use:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Late simple example:
from os import path, getcwd, chdir
def print_my_path():
print('cwd: {}'.format(getcwd()))
print('__file__:{}'.format(__file__))
print('abspath: {}'.format(path.abspath(__file__)))
print_my_path()
chdir('..')
print_my_path()
Under Python-2.*, the second call incorrectly determines the path.abspath(__file__)
based on the current directory:
cwd: C:\codes\py
__file__:cwd_mayhem.py
abspath: C:\codes\py\cwd_mayhem.py
cwd: C:\codes
__file__:cwd_mayhem.py
abspath: C:\codes\cwd_mayhem.py
As noted by @techtonik, in Python 3.4+, this will work fine since __file__
returns an absolute path.
... you can use it on any granularity type i.e.:
DATEPART(YEAR, [date])
DATEPART(MONTH, [date])
DATEPART(DAY, [date])
DATEPART(HOUR, [date])
DATEPART(MINUTE, [date])
(note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date")
So, you need to remove the @CascadeType.ALL
from the @ManyToOne
association. Child entities should not cascade to parent associations. Only parent entities should cascade to child entities.
@ManyToOne(fetch= FetchType.LAZY)
Notice that I set the fetch
attribute to FetchType.LAZY
because eager fetching is very bad for performance.
Whenever you have a bidirectional association, you need to synchronize both sides using addChild
and removeChild
methods in the parent entity:
public void addTransaction(Transaction transaction) {
transcations.add(transaction);
transaction.setAccount(this);
}
public void removeTransaction(Transaction transaction) {
transcations.remove(transaction);
transaction.setAccount(null);
}
I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:
Dim db As New ContractDataContext()
Dim query = From o In db.Orders _
Group Join v In db.Vendors _
On v.VendorNumber Equals o.VendorNumber _
Into ov = Group _
From x In ov.DefaultIfEmpty() _
Group Join s In db.Status _
On s.Id Equals o.StatusId Into os = Group _
From y In os.DefaultIfEmpty() _
Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _
Select Vendor_Name = x.Name, _
Order_Number = o.OrderNumber, _
Status_Name = y.StatusName
unset
code if not freeing immediate memory is still very helpful and would be a good practice to do this each time we pass on code steps before we exit a method. take note its not about freeing immediate memory.
immediate memory is for CPU, what about secondary memory which is RAM.
and this also tackles about preventing memory leaks.
please see this link http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2
i have been using unset for a long time now.
better practice like this in code to instanly unset all variable that have been used already as array.
$data['tesst']='';
$data['test2']='asdadsa';
....
nth.
and just unset($data);
to free all variable usage.
please see related topic to unset
How important is it to unset variables in PHP?
[bug]
Testing ErrorLevel
works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel
of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.
Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT
command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel
.
start /wait something.exe
echo %errorlevel%
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
Another portable solution:
POSH: The Portable Open Source Harness
"POSH is a simple, portable, easy-to-use, easy-to-integrate, flexible, open source "harness" designed to make writing cross-platform libraries and applications significantly less tedious to create and port."
http://poshlib.hookatooka.com/poshlib/trac.cgi
as described and used in the book: Write portable code: an introduction to developing software for multiple platforms By Brian Hook http://books.google.ca/books?id=4VOKcEAPPO0C
-Jason
-- I like this as the data type and the format remains consistent with a date time data type
;with cte as(
select
cast(utcdate as date) UtcDay, DATEPART(hour, utcdate) UtcHour, count(*) as Counts
from dbo.mytable cd
where utcdate between '2014-01-14' and '2014-01-15'
group by
cast(utcdate as date), DATEPART(hour, utcdate)
)
select dateadd(hour, utchour, cast(utcday as datetime)) as UTCDateHour, Counts
from cte
RegEx is the way to go in most cases.
In some cases, it may be faster to specify more elements or the specific element to perform the replace on:
$(document).ready(function () {
$('.myclass').each(function () {
$('img').each(function () {
$(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
})
})
});
This does the replace once on each string, but it does it using a more specific selector.
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
Use a makefile
. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.
Read the make
manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.
The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.
The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:
SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...
It looks like SyndFeed
is not using generics.
You could either have an unsafe cast and a warning suppression:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();
or call Collections.checkedList - although you'll still need to suppress the warning:
@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);
I usually use some #define and constants to make the calculation easy:
#define NANO_SECOND_MULTIPLIER 1000000 // 1 millisecond = 1,000,000 Nanoseconds
const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;
Hence my code would look like this:
timespec sleepValue = {0};
sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);
xcode-select --install
worked for me
I had the "same" problem because I was writting
@GeneratedValue(strategy = GenerationType.IDENTITY)
I deleted that line due that I do not need it at the moment, I was testing with objects and so. I think it is <generator class="native" />
in your case
I do not have any controller and my API is not being accessed, it is only for testing (at the moment).
You need to have a SQLite JDBC driver in your classpath.
Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name sqlite-jdbc. It bundles the native drivers for major platforms so you don't need to configure them separately.
class Program
{
static void Main(string[] args)
{
char[] originalString = "This string contains the unicode character Pi(p)".ToCharArray();
StringBuilder asAscii = new StringBuilder(); // store final ascii string and Unicode points
foreach (char c in originalString)
{
// test if char is ascii, otherwise convert to Unicode Code Point
int cint = Convert.ToInt32(c);
if (cint <= 127 && cint >= 0)
asAscii.Append(c);
else
asAscii.Append(String.Format("\\u{0:x4} ", cint).Trim());
}
Console.WriteLine("Final string: {0}", asAscii);
Console.ReadKey();
}
}
All non-ASCII chars are converted to their Unicode Code Point representation and appended to the final string.
See Working Demo on jsFiddle: http://jsfiddle.net/qHL8Z/3/
$(function() {_x000D_
var timer = null,_x000D_
interval = 1000,_x000D_
value = 0;_x000D_
_x000D_
$("#start").click(function() {_x000D_
if (timer !== null) return;_x000D_
timer = setInterval(function() {_x000D_
$("#input").val(++value);_x000D_
}, interval);_x000D_
});_x000D_
_x000D_
$("#stop").click(function() {_x000D_
clearInterval(timer);_x000D_
timer = null_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="number" id="input" />_x000D_
<input id="stop" type="button" value="stop" />_x000D_
<input id="start" type="button" value="start" />
_x000D_
If you want to use the variable as enum, just add the function:
Enum EVehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
const getVehicleAsEnum = (vehicleStr:string) => vehicleStr === 'car' ? EVehicle.Car : vehicleStr === 'bike' ? EVehicle.Bike : vehicleStr === 'truck' ? EVehicle.Truck : undefined
And then test:
const vehicleEnum = getVecicleAsEnum(str)
if(vehicleEnum) {
// do something
}
I know this is an older post but one thing to watch out for when you cannot change the security is to make sure that your username and password are set.
I had a service with authenticationMode as UserNameOverTransport, when the username and password were not set for the service client I would get this error.
Make an /login url, than accept "user" and "password" parameters via GET and don't require basic auth. Here, use php, node, java, whatever and parse your passwd file and match parameters (user/pass) against it. If there is a match then redirect to http://user:[email protected]/ (this will set credential on your browser) if not, send 401 response (without WWW-Authenticate header).
upstream
defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.
After encountering the same issue in a Web API 2 project (and being unable to use the standard CORS packages for reasons not worth going into here), I was able to resolve this by implementing a custom DelagatingHandler:
public class AllowOptionsHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (request.Method == HttpMethod.Options &&
response.StatusCode == HttpStatusCode.MethodNotAllowed)
{
response = new HttpResponseMessage(HttpStatusCode.OK);
}
return response;
}
}
For the Web API configuration:
config.MessageHandlers.Add(new AllowOptionsHandler());
Note that I also have the CORS headers enabled in Web.config, similar to some of the other answers posted here:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Note that my project does not include MVC, only Web API 2.
Unless somefunction
is a very bad coded legacy function, you shouldn't need what you're asking.
Use multiple except
clause to handle in different ways different exceptions:
try:
someFunction()
except ValueError:
# do something
except ZeroDivision:
# do something else
The main point is that you shouldn't catch generic exception, but only the ones that you need to. I'm sure that you don't want to shadow unexpected errors or bugs.
Another option is to use Qt Jambi. It has nearly all the greatness of Qt (many components, good documentation, easy to use), without the hassle of C++. I used it 3-4 years ago for a small project, even then it was almost mature.
You might want to see the discussion about Swing vs. Qt here.
You can fix this problem without disturbing the bootstrap css and wait for a fix in the next version, so you can simply wrap your row by defining you own class .container-fluid with padding.
//Add this class to your global css file
<style>
.container-fluid {
padding: 0 15px;
}
</style>
//Wrap your rows in within this .container-fluid
<div class="container-fluid">
<div class="row">
<div class="col-md-3">content</div>
<div class="col-md-9">content</div>
<div class="col-md-3">content</div>
</div>
</div>
Say you have a download function to download a file from network, and want to be notified when download task has finished.
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
// How to use it.
downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
})
Hope it helps.
this solution it gonna be ok on Redhat 8.0
sudo yum install libxml2-devel
The webpack2 documentation explains this in a much cleaner way: https://webpack.js.org/guides/public-path/#use-cases
webpack has a highly useful configuration that let you specify the base path for all the assets on your application. It's called publicPath.
In my case, I kept ignoring the instructions that very explicitly tell you to use a terminal on Mac OS, because it looked like it was unzipping correctly:
On Linux or Mac OS X you can unzip ngrok from a terminal with the following command. On Windows, just double click ngrok.zip to extract it.
unzip /path/to/ngrok.zip
However, as soon as I tried running the above command in my terminal, it worked perfectly fine!
Deleting all the caches makes download all the dependacies again. so it take so long time and it is boring thing wait again again to re download all the dependancies.
How ever i could be able to resolve this below way.
Just delete groups which need to be refreshed.
Ex : if we want to refresh com.user.test group
rm -fr ~/.gradle/caches/modules-2/files-2.1/com.user.test/
then remove dependency from build.gradle and re add it. then it will refresh dependencies what we want.
=UNIQUE({filter(Core!L8:L27,isblank(Core!L8:L27)=false),query(ArrayFormula(countif(Core!L8:L27,Core!L8:L27)),"select Col1 where Col1 <> 0")})
Core!L8:L27 = list
According to Md. Sajedul Karim answer I wrote a similar one.
webView = (WebView) view.findViewById(R.id.web);
progressBar = (ProgressBar) view.findViewById(R.id.progress);
webView.setWebChromeClient(new WebChromeClient());
setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarVisibility(View.GONE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(getActivity(), "Cannot load page", Toast.LENGTH_SHORT).show();
setProgressBarVisibility(View.GONE);
}
});
webView.loadUrl(url);
private void setProgressBarVisibility(int visibility) {
// If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
if (progressBar != null) {
progressBar.setVisibility(visibility);
}
}
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
Would BTrees help? They're part of the Zope Object Database code. Downloading the whole ZODB package is a bit of overkill, but I hope the BTrees module would be at least somewhat separable.
If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:
@Import(Application.class) //or the specific configurations you want
//(Optional) Other Annotations that will not trigger an autowire
public class TestConfiguration {
//your custom test configuration
}
And then you can configure your tests in one of two ways:
With the regular configuration:
@SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
//Other annotations here
public class TestThatUsesNormalApplication {
//my test code
}
With the test custom test configuration:
@SpringBootTest(classes = {TestConfiguration.class}) //this still works!
//Other annotations here
public class TestThatUsesCustomTestConfiguration {
//my test code
}
I needed to use element.attr('form')
instead of element.form
.
I use Firefox on Fedora 12.
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel
and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
This is a hard question to answer definitively because the terms and often misused or confused.
Often, an emulator is a complete re-implementation of a particular device or platform. The emulator acts exactly like the real device would. For example, a NES emulator implements the CPU, the sound chip, the video output, the controller signals, etc. The unmodified code from a NES castridge can be dumped and then the resulting image can be loaded into our emulator and played.
A simulator is a partial implementation of a device/platform, it does just enough for its own purposes. For example, the iPhone Simulator runs an "iPhone app" that has been specifically compiled to target x86 and the Cocoa API rather than the real device's ARM CPU and Cocoa Touch API. However, the binary that we run in the simulator would not work on the real device.
You will need a reference to the specific frame you want to close but assuming you have the reference dispose()
should close the frame.
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frameToClose.dispose();
}
});
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia
(WebRTC). You can find it on GitHub.
I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.
The best way is to:
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
yum localinstall php-mcrypt-5.3.3-3.el6.x86_64.rpm
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/libmcrypt-2.5.8-9.el6.x86_64.rpm
yum localinstall libmcrypt-2.5.8-9.el6.x86_64.rpm
or go to: http://dl.fedoraproject.org/pub/epel/6/x86_64/ to match your version check from your info.php that is ok -- done!
When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.
The right way is putting it in an header file, and include this header file whenever needed.
This is the solution I like more, because it makes the code highly modular. I would code your struct as:
#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
struct a
{
int i;
struct b
{
int j;
}
};
#endif
I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").
And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.
If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:
struct a ;
Will be enough, and it decreases coupling.
This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.
In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.
I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.
The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:
struct MyStruct ; /* Forward declaration */
struct MyStruct
{
/* etc. */
} ;
void doSomething(struct MyStruct * p) /* parameter */
{
struct MyStruct a ; /* variable */
/* etc */
}
While a typedef will enable you to write it without the struct keyword.
struct MyStructTag ; /* Forward declaration */
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
void doSomething(MyStruct * p) /* parameter */
{
MyStruct a ; /* variable */
/* etc */
}
It is important you still keep a name for the struct. Writing:
typedef struct
{
/* etc. */
} MyStruct ;
will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)
Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.
Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.
Indeed, the code above could well be written as:
typedef struct MyStruct
{
/* etc. */
} MyStruct ;
IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:
// C++ explicit declaration by the user
struct MyStruct
{
/* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;
Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs
statement to state that the StringBuffer is equivalent to LPSTR.
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function
Swift 3 solution.
All these did NOT work.
Module
on right pane did NOT work.This worked finally.
Just create new directory and create a new project inside that. Add the files except Main.sotryboard.
Now copy the view controllers from previous project and paste it into new Main.storyboard.
Voila ! This works.
You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.
E.g. you have the users set things up so that some-app://
links start "SomeApp", and then in my-awesome-extension
you open a tab pointing to some-app://some-data-the-app-wants
, and you're good to go!
The only time you should worry your users about something that happened in the code is if there is something they can or need to do to avoid the issue. If they can change data on a form, push a button or change a application setting in order to avoid the issue then let them know. But warnings or errors that the user has no ability to avoid just makes them lose confidence in your product.
Exceptions and Logs are for you, the developer, not your end user. Understanding the right thing to do when you catch each exception is far better than just applying some golden rule or rely on an application-wide safety net.
Mindless coding is the ONLY kind of wrong coding. The fact that you feel there is something better that can be done in those situations shows that you are invested in good coding, but avoid trying to stamp some generic rule in these situations and understand the reason for something to throw in the first place and what you can do to recover from it.
Or you can skip rake and use the 'rspec' command:
rspec path/to/spec/file.rb
In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine.
If you're using an older version of rspec it is:
spec path/to/spec/file.rb
Try nslookup google.com to determine if there's a DNS issue. 192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well? What happens when you try ping google.com. Can you browse to it on a Internet web browser?
Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything
Create Parameter (if not automaticly created)
Define values - wrong way example
Define values - correct way example
Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.
The Result
One picture for Data type: Int
When in a window, go to GO ---> ENTER LOCATION... And then copy paste this: /opt/lampp/htdocs
Now you are at the htdocs folder. Then you can add your files there, or in a new folder inside this one (for example "myproyects" folder and inside it your files... and then from a navigator you access it by writting: localhost/myproyects/nameofthefile.php
What I did to find it easily everytime, was right click on "myproyects" folder and "Make link..."... then I moved this link I created to the Desktop and then I didn't have to go anymore to the htdocs, but just enter the folder I created in my Desktop.
Hope it helps!!
When you give up the inline blocks
.post-container {
border: 5px solid #333;
overflow:auto;
}
.post-thumb {
float: left;
display:block;
background:#ccc;
width:200px;
height:200px;
}
.post-content{
display:block;
overflow:hidden;
}
The methods are identical when an object or array is passed, but res.json()
will also convert non-objects, such as null
and undefined
, which are not valid JSON.
The method also uses the json replacer
and json spaces
application settings, so you can format JSON with more options. Those options are set like so:
app.set('json spaces', 2);
app.set('json replacer', replacer);
And passed to a JSON.stringify()
like so:
JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation
This is the code in the res.json()
method that the send method doesn't have:
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
The method ends up as a res.send()
in the end:
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click
wb_apple.Document.GetElementById("phoneNumber").Focus()
wb_apple.Document.GetElementById("phoneNumber").InnerText = tb_phonenumber.Text
wb_apple.Document.GetElementById("reservationCode").Focus()
wb_apple.Document.GetElementById("reservationCode").InnerText = tb_regcode.Text
'SendKeys.Send("{Tab}{Tab}{Tab}")
'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName("a")
'If Element.OuterHtml.Contains("iReserve.sms.submitButtonLabel") Then
'Element.InvokeMember("click")
'Exit For
' End If
'Next Element
wb_apple.Document.GetElementById("smsPageForm").Focus()
wb_apple.Document.GetElementById("smsPageForm").InvokeMember("submit")
End Sub
git format-patch
also has the -B
flag.
The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).
This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.
An example:
git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch
I use this to load ko knockout object in console
document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");
or host locally
document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
In my case I got this message while debugging:
"Error while calling service <ServiceName> Could not load file or assembly 'RestSharp,
Version=105.2.3.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference.
(Exception from HRESULT: 0x80131040)"
Cause
In my project I have had 2 internal components using the RestSharp but both component have different version of RestSharp (one with version 105.2.3.0
and the other with version 106.2.1.0
).
Solution
Either upgrade one of the components to newer or downgrade the other. In my case it was safer for me to downgrade from 106.2.1.0
to 105.2.3.0
and than update the component in NuGet package manager. So both components has the same version.
Rebuild and it worked with out problems.
There is no reliable way to do this in pure Java. Setting the user.dir
property via System.setProperty()
or java -Duser.dir=...
does seem to affect subsequent creations of Files
, but not e.g. FileOutputStreams
.
The File(String parent, String child)
constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant Sun bug was closed in 2008 as "will not fix".
After trying with every single option describe in this posts and others, I came to the conclusion that the the fix is a follows.
In every XToMany place @XXXToMany(mappedBy="parent", fetch=FetchType.EAGER)
and intermediately after
@Fetch(value = FetchMode.SUBSELECT)
This worked for me
This line:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
$scope.myForm.file.$setValidity("size", false);
I faced the Invalid parameter: redirect_uri problem problem while following spring boot and keycloak example available at http://www.baeldung.com/spring-boot-keycloak. when adding the client from the keycloak server we have to provide the redirect URI for that client so that keycloak server can perform the redirection. When I faced the same error multiple times, I followed copying correct URL from keycloak server console and provided in the valid Redirect URIs space and it worked fine!
I have had the same problem with not getting an accurate size using these techniques and I've changed my approach to make it work.
I have a long attributed string which I've been trying to fit into a scroll view so that it shows properly without being truncated. What I did to make the text work reliably was to not set the height at all as a constraint and instead allowed the intrinsic size to take over. Now the text is displayed correctly without being truncated and I do not have to calculate the height.
I suppose if I did need to get the height reliably I would create a view which is hidden and these constraints and get the height of the frame once the constraints are applied.
I would pick the if statement for the sake of clarity and convention, although I'm sure that some would disagree. After all, you are wanting to do something if
some condition is true! Having a switch with one action seems a little... unneccesary.
In the latest version of Bootstrap, I found removing outline itself doesn't work. And I have to add this because there is also a box-shadow:
.btn:focus, .btn:active {
outline: none !important;
box-shadow: none !important;
}
ok, after 5 years have passed....
if discount.try :nonzero?
...
end
It's important to note that try
is defined in the ActiveSupport gem, so it is not available in plain ruby.
I experienced the same problem, but for different reasons.
After Will Madden's solution didn't help, I tried every alternative fix I could find via the Intertubes - also to no avail. Exploring further, I just happened to open up one of the font files at issue. The original content of the file had somehow been overwritten by Webpack to include some kind of configuration info, likely from previous tinkering with the file-loader. I replaced the corrupted files with the originals, and voilà, the errors disappeared (for both Chrome and Firefox).
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
d4 = dict(d1.items() + d2.items() + d3.items())
alternatively (and supposedly faster):
d4 = dict(d1)
d4.update(d2)
d4.update(d3)
Previous SO question that both of these answers came from is here.
Just use the below code to resolve this:
JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
replace('-', '+').replace('_', '/')))).readObject();
In the above code replace('-', '+').replace('_', '/')
did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:
function url_base64_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
}
var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
try{
return decodeURIComponent(escape(result));
} catch (err) {
return result;
}
}
A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.
For example (to select a layer named 'Note' and add line feeds after all periods):
var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");