_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d18601 | test | One nuance to be aware of. IsWindowVisible will return the true visibility state of the window, but that includes the visibility of all parent windows as well.
If you need to check the WS_VISIBLE flag for a specific window you can do GetWindowLong(hWnd, GWL_STYLE) and test for WS_VISIBLE.
... It sounds like you don't need to do this for your case, but adding this for future reference in case others run across this question.
A: Do you have an HWND to the window? If not, then you will need to obtain the window handle somehow, for example through FindWindow() (or FindWindowEx()).
Once you have the HWND to the window, call IsWindowVisible(). | unknown | |
d18602 | test | Download and install QuickOPC 5.23(.NET Framework 3.5 or 4.0) or QuickOPC 5.31(.NET Framework 4.5) from http://opclabs.com/products/quickopc/downloads
Create a VB.NET project in VisualStudio.
Add the reference, OpcLabs.EasyOpcClassic.dll to the project.
Use the following code to read data from Kepware server using VB.NET
Imports OpcLabs.EasyOpc
Imports OpcLabs.EasyOpc.DataAccess
Public Class Demand
Private Sub frm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ReadPLCvalue()
End Sub
Private Sub ReadPLCvalue()
Dim objClient As New EasyDAClient
Dim sValue As Object
Try
sValue = objClient.ReadItemValue(KepwareServerMachineName, KepwareServerID, PLCTagName)
Catch ex As OpcException
End Try
StoreToDB(sValue)
End Sub
Private Sub StoreToDB(ByVal source As Object)
'Database operations to store the value.
End Sub
End Class | unknown | |
d18603 | test | Finnally got it working with the below. Took most of the code from https://stackoverflow.com/a/23078185/1814446.
The only difference was for the ng-if to work the directive had to be put on a parent html element.
'use strict';
var app = angular.module('app', []);
app.controller('mainController', ['$window', '$scope', function($window, $scope){
var mainCtrl = this;
mainCtrl.test = 'testing mainController';
}]);
app.directive('windowSize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
scope.style = function () {
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body window-size my-directive ng-app="app" ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<div ng-if="windowWidth > 500">
<h4 style="margin:5px 0">It works!</h4>
<p style="margin:0">window.height: {{windowHeight}}</p> <p style="margin:0">window.width: {{windowWidth}}</p> <p style="margin:0">{{mainCtrl.test}}</p>
</div>
</body>
A: Getting the window width on resize isn't anything specific to Angular JS. in fact Angular doesn't provide any capability to do it. It's native javascript, the native window object fires a resize event that you can access. jQuery provides a handy wrapper for this. By using a simple callback in your controller and then updating your double bound windowWidth property on the $scope object you can get the functionality you need without using a directive.
$(window).resize(function() {
$scope.windowWidth = $( window ).width();
});
A: Just include this code in your controller and you will get the new window width every time.
$scope.windowWidth = $window.innerWidth;
angular.element($window).bind('resize', function(){
$scope.windowWidth = $window.innerWidth;
$scope.$apply();
});
A: The best way is to use a directive and watch for resize event of the window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
angular.element($window).bind('resize', function(){
scope.windowWidth = $window.innerWidth;
});
}
}]);
And use it on your div:
<div my-directive ng-if="windowWidth > 320">
Here is a working plunker. | unknown | |
d18604 | test | Creating/filling a structured array is a little tricky. There are various ways, but I think the simplest to remember is to use a list of tuples:
In [11]: np.array([tuple(row) for row in matrix], dtype=dt)
Out[11]:
array([('name', '23', '45', '1'),
('name2', '223', '43', '5'),
('name3', '12', '33', '2')],
dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])
The result is 1d array, with the dtype fields replacing the columns of the original 2d array. Each element of the new array has the same type - as specified by dt.
Or you can create an empty array of the desired dtype, and fill it, row by row or field by field:
In [14]: arr = np.zeros((3,),dt)
In [16]: arr[0]=tuple(matrix[0,:]) # tuple of row
In [17]: arr['name']=matrix[:,0] # field
In [18]: arr
Out[18]:
array([('name', '23', '45', '1'),
('name2', '', '', ''),
('name3', '', '', '')],
dtype=[('name', 'S10'), ('x', 'S10'), ('y', 'S10'), ('n', 'S10')])
With a compatible dt1, view would also work
dt1 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'S5', 'S5', 'S5']})
matrix.view(dt1)
This doesn't change the data; it just interprets the bytes differently.
converting the strings to numbers is easy with the list of tuples
In [40]: dt2 = numpy.dtype({'names':['name','x','y','n'],'formats': ['S5', 'f', 'f', 'i']})
In [41]: np.array([tuple(row) for row in matrix], dtype=dt2)Out[41]:
array([('name', 23.0, 45.0, 1),
('name2', 223.0, 43.0, 5),
('name3', 12.0, 33.0, 2)],
dtype=[('name', 'S5'), ('x', '<f4'), ('y', '<f4'), ('n', '<i4')]) | unknown | |
d18605 | test | The for ... in loop iterates over the keys (properties) of an object. So
for (var person in people) {
console.log(people[person].name);
}
will get you the desired result.
The variable person will receive the values "frodo", "aragorn" and "legolas" during the execution of the loop which are the keys (properties) of your person object.
A: You take the keys of the object with for ... in statement. Then you need it as property accessor fopr the object.
const people = {
frodo: { name: 'Frodo', age: 33 },
aragorn: { name: 'Aragorn', age: 87 },
legolas: { name: 'Legolas', age: 2931 }
}
for (var person in people) {
console.log(people[person].name);
}
A: You need to look at what person is within your code:
const people = {
frodo: { name: 'Frodo', age: 33 },
aragorn: { name: 'Aragorn', age: 87 },
legolas: { name: 'Legolas', age: 2931 }
}
for(person in people) console.log(person);
It's the name of the object, not the object itself. To access it you need to specify where the object is located:
const people = {
frodo: { name: 'Frodo', age: 33 },
aragorn: { name: 'Aragorn', age: 87 },
legolas: { name: 'Legolas', age: 2931 }
}
for(person in people) {
console.log( people[person].age, people[person].name, people[person] );
}
A: for .. in returns every key in the object. You can get the person by using the key.
const people = {
frodo: { name: 'Frodo', age: 33 },
aragorn: { name: 'Aragorn', age: 87 },
legolas: { name: 'Legolas', age: 2931 }
}
for(var key in people) {
var person = people[key]
console.log(person.name)
} | unknown | |
d18606 | test | I was wrong about EPEL having all the dependencies. It looks like perl-File-Slurp lives in the "AppStream" repository. You can add the the CentOS 8 version of that repository to your ubi8 image:
*
*Install dnf if you haven't already:
microdnf install dnf
*Add the repository configuration (note that I have this disabled by default):
cat > /etc/yum.repos.d/centos-appstream.repo <<'EOF'
[appstream]
name=CentOS Stream $releasever - AppStream
mirrorlist=http://mirrorlist.centos.org/?release=$releasever-stream&arch=$basearch&repo=AppStream&infra=$infra
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
EOF
*Install the CentOS 8 GPG key:
rpm --import https://www.centos.org/keys/RPM-GPG-KEY-CentOS-Official
*Enable the EPEL repository if you haven't already:
dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
*Install rlwrap:
dnf --enablerepo=appstream install rlwrap
Alternately, instead of installing rlwrap and it's myriad dependencies, just install socat:
microdnf install socat
And then use the readline and exec connectors:
socat readline exec:"/path/to/some/program --arg foo",pty | unknown | |
d18607 | test | Here's the solution. You have to iterate through all option elements, grab the value of every element and push inside an array.
function getValues() {
var array = document.getElementsByTagName('option');
var arr = [];
for (var i = 0; i < array.length; i++) {
arr.push(array[i].value)
}
console.log(arr);
};
<select id="options">
<option>Joe</option>
<option>Buckey</option>
<option>Elen</option>
<option>Rimzy</option>
</select>
<button id="submit" onclick="getValues()">Submit</button>
ES6 solution:
function getValues() {
var array = document.getElementsByTagName('option');
var arr = [];
Array.from(array).forEach(v => arr.push(v.value));
console.log(arr);
};
<select id="options">
<option>Joe</option>
<option>Buckey</option>
<option>Elen</option>
<option>Rimzy</option>
</select>
<button id="submit" onclick="getValues()">Submit</button>
A: Assuming that ES6 is an option for you, then the following will do as you wish:
// using a named function:
function grabTextFrom() {
// initialising the local variable using 'let',
// converting the argument supplied to Array.from()
// to convert the Array-like Object (in this case
// a NodeList, or HTMLCollection, from
// document.querySelectorAll()) into an Array:
let texts = Array.from(
document.querySelectorAll(
// 'this' is passed automatically from the
// later use of EventTarget.addEventListener(),
// and the dataset.textFrom property value is
// the value stored in the data-textfrom attribute:
this.dataset.textfrom
)
// iterating over that Array of elements using
// Array.prototype.map() along with an arrow function:
).map(
// 'opt' is a reference to the current Array-element
// from the Array of elements over which we're iterating;
// and here we return the value property-value of that
// current element:
opt => opt.value
);
// logging to the console for demo purposes:
console.log(texts);
// returning to the calling context:
return texts;
}
// finding the first element which matches the
// supplied CSS selector, and adding the
// grabTextFrom() function as the event-handler
// for the 'click' event (note the deliberate
// lack of parentheses in the function-name):
document.querySelector('#submit').addEventListener('click', grabTextFrom);
function grabTextFrom() {
let texts = Array.from(
document.querySelectorAll(this.dataset.textfrom)
).map(
opt => opt.value
);
console.log(texts);
return texts;
}
document.querySelector('#submit').addEventListener('click', grabTextFrom);
<select id="options">
<option>Joe</option>
<option>Buckey</option>
<option>Elen</option>
<option>Rimzy</option>
</select>
<button id="submit" data-textfrom="option">Submit</button>
If, however, you have to provide for ES5 compatibility then the following will work identically:
function grabTextFrom() {
// here we use Array.prototype.slice(), along
// with Function.prototype.call(), to apply
// the slice() method to the supplied NodeList:
var texts = Array.prototype.slice.call(
document.querySelectorAll(this.dataset.textfrom)
// here we use the anonymous function of the
// Array.prototype.map() method to perform the
// same function as above, returning the
// opt.value property-value to the created Array:
).map(function(opt) {
return opt.value;
});
console.log(texts);
return texts;
}
document.querySelector('#submit').addEventListener('click', grabTextFrom);
function grabTextFrom() {
var texts = Array.prototype.slice.call(
document.querySelectorAll(this.dataset.textfrom)
).map(function(opt) {
return opt.value;
});
console.log(texts);
return texts;
}
document.querySelector('#submit').addEventListener('click', grabTextFrom);
<select id="options">
<option>Joe</option>
<option>Buckey</option>
<option>Elen</option>
<option>Rimzy</option>
</select>
<button id="submit" data-textfrom="option">Submit</button>
A: You're close.
document.getElementsByTagName('option') returns an array of <option> elements.
You can't get .value on an array of elements - you can only call it on a single <option> element.
How would you get .value for each element in your array? | unknown | |
d18608 | test | I got it!
What OP did wrong was sending the user_login value in Postman's Params instead of form-data or x-www-form-urlencoded.
Here is the working Postman request
But that's not all.
I am using Flutter for developing my mobile app and http package to send the request and the normal http.post() won't work. It only works with MultipartRequest for some reason.
Here is the full working request for Flutter's http package.
String url = "https://www.yourdomain.com/wp-login.php?action=lostpassword";
Map<String, String> headers = {
'Content-Type': 'multipart/form-data; charset=UTF-8',
'Accept': 'application/json',
};
Map<String, String> body = {
'user_login': userLogin
};
var request = http.MultipartRequest('POST', Uri.parse(url))
..fields.addAll(body)
..headers.addAll(headers);
var response = await request.send();
// forgot password link redirect on success
if ([
200,
302
].contains(response.statusCode)) {
return 'success';
} else {
print(response.statusCode);
throw Exception('Failed to send. Please try again later.');
} | unknown | |
d18609 | test | You could make the check like this
(todayDate - oldDate) / (1000 * 3600 * 24 * 365) > 1
You can see and try it here:
https://jsfiddle.net/rnyxzLc2/
A: This code should handle leap years correctly.
Essentially:
If the difference between the dates' getFullYear() is more than one,
or the difference equals one and todayDate is greater than oldDate after setting their years to be the same,
then there's more than a one-year difference.
var oldDate = new Date("Oct 2, 2014 01:15:23"),
todayDate = new Date(),
y1= oldDate.getFullYear(),
y2= todayDate.getFullYear(),
d1= new Date(oldDate).setFullYear(2000),
d2= new Date(todayDate).setFullYear(2000);
console.log(y2 - y1 > 1 || (y2 - y1 == 1 && d2 > d1));
A: use getFullYear():
fiddle: https://jsfiddle.net/husgce6w/
var oldDate = new Date("July 21, 2001 01:15:23");
var todayDate = new Date();
var thisYear = todayDate.getFullYear();
var thatYear = oldDate.getFullYear();
console.log(todayDate);
console.log(thatYear);
if(thisYear - thatYear > 1) {
console.log("it has been over one year!");
} else {
console.log("it has not gone one year yet!");
} | unknown | |
d18610 | test | Pure python-based monitoring solutions are not really scalable as python at the core is pretty slow compared to something like c and multiprocessing is not native. Your best bet would be to use an opensource solution like Zabbix or cacti and use python API to interact with the data | unknown | |
d18611 | test | One thing to check is that Xcode is searching the library headers properly (especially with LinkingIOS).
"This step is not necessary for libraries that we ship with React Native with the exception of PushNotificationIOS and LinkingIOS."
Linking React Native Libraries in Xcode
A: Is the LinkingIOS.openURL function supposed to run after a response from the server in the fetch block? If so, then you'll want to include it in a another then block.
As it is written now, LinkingIOS.openURL will run right after the fetch line. Then, as they resolve or error out, the then and catch blocks of fetch will run. | unknown | |
d18612 | test | I have solved this problem by simply using the custom forms instead of model forms. While storing the data in the database, I managed myself in the views.py | unknown | |
d18613 | test | NullPointerException: Attempt to invoke virtual method
'java.lang.Integer com.example.databaseHelper.deleteContact
Because you are not initializing dbh object of databaseHelper class before calling deleteContact using dbh object. Initialize it before calling method:
dbh=new databaseHelper(...);
dbh.deleteContact(val); | unknown | |
d18614 | test | Only EJB can working in CMT by default. In Managed beans or CDI beans you have to implement your own mechanism for handling transactions and run your service from within it.
public class ManagedBean {
@Inject
yourEjbService service;
@Resource
UserTransaction utx;
public void save(){
try{
utx.begin();
service.doAction();
utx.commit();
} catch (Exception e) {
try {
utx.rollback();
} catch (Exception ex) {
...
}
}
}
...
}
You also don't have to call EntityManager.flush() neither in your EJB nor in managed bean if you are injecting EntityManager using @PersistenceContext. It will detach entities automatically after each method in your EJB ends.
A: The persistence control mechanisms of Java Enterprise have several options and specific design choices. In almost any Java EE implementation I worked with, comtainer managed transactions (CMT) were used. In an occastional situation, bean managed transactions (BMT) can be the choice.
Bean managed transactions can be preferred when you need to be sure, exactly when the 'commit' (or 'rollback') takes place during program execution. This can be required in a high-performing time-critical application area. For an example of BMT, see e.g. the section 'Bean Managed Transactions' in examples, Bean Managed Transactions
Container managed transactions means that the software in the application server ( 'the container') calls a 'begin' transction before Java code is executed that makes use of a persistence context. When the code execution is finisned (when the call tree has returned, e.g. as a result of a web-request), the application server calls 'commit'. Consequently, the modified entities are actually updated in the application database.
In Java EE, the statements: @TransactionManagement(TransactionManagementType.CONTAINER) and @TransactionManagement(TransactionManagementType.BEAN) indicate container managed transactions, or bean managed transactions, respectively. Java EE
defines several types of beans: session-driven bean, message-driven bean, local bean. These beans are generally @Stateless, and can all work with container managed transactions.
Detailed control of container managed transaction handling can in EE be specified by adding the annotations:
@TransactionAttribute(REQUIRES_NEW)
public void myTopLevelMethodWhichStartsNewInnerTransaction()
....
@TransactionAttribute(REQUIRED)
public void myTopLevelMethodContinueExistingTransactionIfAny()
....
@TransactionAttribute(NEVER)
public void myNoCurrentTransactionAllowedWhenMethodCalled()
....
Flush
The necessarity of calling 'flush' to ensure that the database cache is written on disk, depends on the type of database used. E.g. for Postgress calling flush makes a difference, whereas for the in-memory database 'derby', flush has no effect, and can in that latter situation cause an error similar to the one reported in this question. The effect of flush is thus database dependent. | unknown | |
d18615 | test | Yes, it can be done. There are more possible approaches to this.
The first one, which is the cleanest, is to keep a second buffer, as suggested, of the length of the searched word, where you keep the last chunk of the old buffer. (It needs to be exactly the length of the searched word because you store wordLength - 1 characters + NULL terminator). Then the quickest way is to append to this stored chunk from the old buffer the first wordLen - 1 characters from the new buffer and search your word here. Then continue with your search normally. - Of course you can create a buffer which can hold both chunks (the last bytes from the old buffer and the first bytes from the new one).
Another approach (which I don't recommend, but can turn out to be a bit easier in terms of code) would be to fseek wordLen - 1 bytes backwards in the read file. This will "move" the chunk stored in previous approach to the next buffer. This is a bit dirtier as you will read some of the contents of the file twice. Although that's not something noticeable in terms of performance, I again recommend against it and use something like the first described approach.
A: use the same algorithm as per fgetc only read from the buffers you created. It will be same efficient as strstr iterates thorough the string char by char as well. | unknown | |
d18616 | test | You could reverse the stack order via position = position_fill(reverse = TRUE):
library(ggplot2)
ggplot(newdf) +
aes(x = smoke_status, y = Count, fill = Birth_status) +
xlab("Smoking Activity") +
ylab("Proportion") +
labs(fill = "Birthweight") +
geom_bar(position = position_fill(reverse = TRUE), stat = "identity") +
scale_y_continuous(labels = scales::percent)
DATA
newdf <- structure(list(smoke_status = c("High", "High", "Normal", "Normal"), Birth_status = c("Low", "Normal", "Low", "Normal"), Count = c(
10L,
34L, 4L, 44L
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(smoke_status = c(
"High",
"Normal"
), .rows = structure(list(1:2, 3:4), ptype = integer(0), class = c(
"vctrs_list_of",
"vctrs_vctr", "list"
))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), .drop = TRUE)) | unknown | |
d18617 | test | I suggest you read a little bit more about this topic.
just as a quick answer. TCP makes sure that all the packages are delivered. So if one is dropped for whatever reason. The sender will continue sending it until the receiver gets it. However, UDP sends a packet and just forgets it, so you might loose some of the packets. As a result of this, UDP sends less number of packets over network.
This is why they use UDP for videos because first loosing small amount of data is not a big deal plus even if the sender sends it again it is too late for receiver to use it, so UDP is better. In contrast, you don't want your online banking be over UDP!
Edit: Remember, the speed of sending packets for both UDP and TCP is almost same, and depends on the network! However, after handshake is done in TCP, still receiver needs to send the acks, and sender has to wait for ack before sending new batch of data, so still would be a little slower.
A: In general, TCP is marginally slower, despite less header info, because the packets must arrive in order, and, in fact, must arrive. In a UDP situation, there is no checking of either. | unknown | |
d18618 | test | The code you have included in your question is fine (after adding the getters and setters) and then using:-
public class MainActivity extends AppCompatActivity {
NoteDatabase db;
NoteDAO dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = NoteDatabase.getDatabase(this);
dao = db.noteDAO();
Note note1 = new Note();
note1.setTitle("NOTE001");
note1.setDatetime("2022-01-01 10:30");
note1.setSubtitle("The First Note");
note1.setWebsite("www.mynotes.com");
note1.setNoteText("This is the note");
note1.setColor("Black");
note1.setImagePath("notes/note1.jpg");
dao.insertNote(note1);
for (Note n: dao.getAllNotes()) {
Log.d("NOTEINFO","Title is " + n.getTitle() + " Date is " + n.getDatetime() + " blah blah ToString = " + n);
}
}
}
*
*note the only amendment to the code copied from the question is the use of .allowMainThreadQueries in the databaseBuilder.
The result being:-
D/NOTEINFO: Title is NOTE001 Date is 2022-01-01 10:30 blah blah ToString = NOTE001 : 2022-01-01 10:30
However, adding :-
Note note2 = new Note();
//note1.setTitle("NOTE001"); //<<<<<<<<<<< OOOPS
note2.setDatetime("2022-01-01 10:30");
note2.setSubtitle("The Second Note");
note2.setWebsite("www.mynotes.com");
note2.setNoteText("This is the note");
note2.setColor("Black");
note2.setImagePath("notes/note2.jpg");
Results in what you appear to be describing as per:-
D/NOTEINFO: Title is null Date is 2022-01-01 10:30 blah blah ToString = null : 2022-01-01 10:30
I believe you saying
I also notice that in the Dao interface, it raises 2 errors which are Cannot resolve symbol notes and Cannot resolve symbol id
Is perhaps the clue to the cause, which could be that you have the incorrect dependencies you should have 2 for Room:-
*
*the runtime library e.g. implementation 'androidx.room:room-runtime:2.5.0-alpha02', and
*the compiler library e.g. annotationProcessor 'androidx.room:room-compiler:2.5.0-alpha02'
Another possibility is that in addition to the getters and setters you have a constructor that doesn't set correctly the title so it is left as null. | unknown | |
d18619 | test | See Tom Clarkson answer on
Views in separate assemblies in ASP.NET MVC | unknown | |
d18620 | test | var result gets calculated correct with your SSJS code. The result is 60.
@Sum works for ArrayLists.
Make sure you store result in correct field and save the document. | unknown | |
d18621 | test | No, the bounds of the range both have to be static expressions.
But you can declare a subtype with dynamic bounds:
X: Integer := some_value;
subtype Dynamic_Subtype is Integer range 1 .. X;
A:
Can type Airplane_ID is range 1..x; be written where x is a
variable? I ask this because I want to know if the value of x can be
modified, for example through text input.
I assume that you mean such that altering the value of x alters the range itself in a dynamic-sort of style; if so then strictly speaking, no... but that's not quite the whole answer.
You can do something like this:
Procedure Test( X: In Positive; Sum: Out Natural ) is
subtype Test_type is Natural Range 1..X;
Result : Natural:= Natural'First;
begin
For Index in Test_type'range loop
Result:= Result + Index;
end loop;
Sum:= Result;
end Test;
A: No. An Ada range declaration must be constant.
A: As the other answers have mentioned, you can declare ranges in the way you want, so long as they are declared in some kind of block - a 'declare' block, or a procedure or function; for instance:
with Ada.Text_IO,Ada.Integer_Text_IO;
use Ada.Text_IO,Ada.Integer_Text_IO;
procedure P is
l : Positive;
begin
Put( "l =" );
Get( l );
declare
type R is new Integer range 1 .. l;
i : R;
begin
i := R'First;
-- and so on
end;
end P; | unknown | |
d18622 | test | Use MediaScannerConnection and its static scanFile() method:
MediaScannerConnection.scanFile(this, new String[] { yourPath }, null, null); | unknown | |
d18623 | test | You can use union all. This returns the most recent image from the two tables combined for each id:
with ab as (
select a.* from TableA a union all
select b.* from TableB b
)
SELECT ID, Image
FROM (SELECT ab.*,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY DATE DESC, TIME DESC) as seqnum
FROM ab
) ab
WHERE seqnum = 1;
ORDER BY Date DESC, Time DESC
LIMIT 5;
A: If what you need is the rows with the latest date and time (as your expected results):
with cte as (
select * from Tablea
union all
select * from Tableb
)
select * from cte
where Date || Time = (select max(Date || Time) from cte)
order by id
I assume the dates are always in the format MM/YY and the times hh:mm.
See the demo.
Results:
| ID | Image | Date | Time |
| --- | ----- | ----- | ----- |
| 0 | 5 | 12/03 | 12:35 |
| 1 | 3 | 12/03 | 12:35 |
| 2 | 7 | 12/03 | 12:35 | | unknown | |
d18624 | test | One way to accomplish this would be a computed column in your database.
The main benefit would be that you wouldn't need to change your page(s). Additionally you could reuse the calculated price in other places in your application - I guess you actually calculate the price again on other parts of the site.
A: If this recordset is not huge, one solution is during your loop, store your calculated price into an array. Once you've calculated the pricing, you can sort the array with a sorting function and then print out the results. | unknown | |
d18625 | test | Use the Key event listener.
var key:Object = {
onKeyDown:function() {
switch(Key.getCode()) {
case 49:
trace('key 1 is down');
break;
case 50:
trace('key 2 is down');
break;
}
}
};
Key.addListener(key);
Then you can handle actions in the switch statement. | unknown | |
d18626 | test | That's correct, it does not work to directly use knitr::knit_exit() as an error handler. However, you can override the error output hook with it to achieve your desired outcome:
knitr::knit(
output = stdout(),
text = "
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
# override error output hook here
knitr::knit_hooks$set(error = function(x, options) {
knitr::knit_exit()
})
```
```{r}
1 + 1
```
```{r}
stop('Test')
```
This text should not be in the output.
```{r}
2 + 2
```
")
```
#>
#>
#>
#>
#> ```r
#> 1 + 1
#> #> [1] 2
#> ```
#>
#>
#> ```r
#> stop('Test')
#> ```
Created on 2022-10-24 with reprex v2.0.2
A: In addition to the accepted answer (which helped me a lot and you should upvote ;-) ) one might want the error message to be printed. In that case, the error hook can be used to signal knitr to quit but also save the error message, for example in a global variable. Then, the chunk hook can be used to print the error message in a last output block:
For that, use the following hooks
knitr::knit_hooks$set(error = function(x, options) {
ERROR <<- x
knitr::knit_exit()
})
knitr::knit_hooks$set(chunk = function(x, options){
if(exists('ERROR')) paste0(x,'```\n',ERROR,'```\n\n**Skript stopped with error**')
else x
})
Or, in the complete example:
knitr::knit(
output = stdout(),
text = "
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
# override error output hook here
knitr::knit_hooks$set(error = function(x, options) {
ERROR <<- x
knitr::knit_exit()
})
knitr::knit_hooks$set(chunk = function(x, options){
if(exists('ERROR')) paste0(x,'```\n',ERROR,'```\n\n**Skript stopped with error**')
else x
})
```
```{r}
1 + 1
```
```{r}
stop('Test')
```
This text should not be in the output.
```{r}
2 + 2
```
") | unknown | |
d18627 | test | field("java.net.URL", "authority") will safely retrieve the field named authority from the class java.net.URL
get(field, instance) reflectively obtains the value of the given field in specified instance.
The Javadoc for BTraceUtils is a good starting point. | unknown | |
d18628 | test | The solution is well-documented in jacoco but for Android people, what you need is to add the file in /src/androidTest/resources/jacoco-agent.properties with the contents output=none so jacoco can startup without failing, and coverage will be written as normal and transferred correctly later by the android gradle plugin coverage implementation.
A: I think it's safe to ignore that offline instrumentation warning, because the path should be something alike: executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec") (on the PC - so there is no need to save it on the device and then pull the file).
On Android this will add the JaCoCo agent into the APK:
buildTypes {
debug {
testCoverageEnabled = true
}
} | unknown | |
d18629 | test | Are you trying to simply identify if a certain user is the first to register? If so, you can use the Post Confirmation lambda trigger. Use a DynamoDB table to maintain a flag (this could be a count)and check this flag to identify if that is the first user to successfully confirm. Change the value of the flag to record that the first user has registered. | unknown | |
d18630 | test | You can sort by weight ascending and then create a result using the name as the key so the ones with larger weight will overwrite the smaller weight ones:
array_multisort(array_column($array, 'weight'), SORT_ASC, $array);
foreach($array as $v) { $result[$v['name']] = $v; }
Then if you want to re-index (not required):
$result = array_values($result);
A: Try to use array_unique($array); code | unknown | |
d18631 | test | Use the following code:
include_once('Simple/autoloader.php');
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->enable_cache(false);
$feed->set_output_encoding('utf-8');
$feed->init();
$i=0;
$items = $feed->get_items();
foreach ($items as $item) {
$i++;
/*You are getting title,description,date of your rss by the following code*/
$title = $item->get_title();
$url = $item->get_permalink();
$desc = $item->get_description();
$date = $item->get_date();
}
Download the Simple folder data from : https://github.com/jewelhuq/Online-News-Grabber/tree/master/worldnews/Simple
Hope it will work for you. There $url mean your rss feed url. If you works then response.
A: Turns out, it's simple by using the PHP xml parer function:
$xml = simplexml_load_file ($path . 'RSS.xml');
$channel = $xml->channel;
$channel_title = $channel->title;
$channel_description = $channel->description;
echo "<h1>$channel_title</h1>";
echo "<h2>$channel_description</h2>";
foreach ($channel->item as $item)
{
$title = $item->title;
$link = $item->link;
$descr = $item->description;
echo "<h3><a href='$link'>$title</a></h3>";
echo "<p>$descr</p>";
} | unknown | |
d18632 | test | There's no way to downscale video on YouTube manually. YouTube does this automatically, just upload the highest quality you can, and the appropriate lower qualities will be "created" in the quality settings. | unknown | |
d18633 | test | I just answered this question here, but the general gist is:
I was able to achieve this affect by calling setExpand(true) as the first line of my onCreateView() in my RowsFragment.
If you want to lock this effect forever, you can override setExpand(...) in your RowsFragment and just call super.setExpand(true). I believe you'll still need the initial call in onCreateView() though. | unknown | |
d18634 | test | What is the benefit of using stored procedures instead of SQL queries from an external connection?
*
*Stored Procedures can be complex. Very complex. They can do things
that a single SQL query cannot do. (Execute Block aside.)
*They have their own set of grants so they can do things that current user
cannot do at all.
*Firebird optimizer is not that bad but obviously complex queries require more time for optimization and the result still may be suboptimal. Using imperative language the programmer can split complex query to set of simpler ones making Data Access Paths more predictable.
Is there any execution speed differences between them for small volume
and big volume outputs?
No.
Is there any benefits for the database management as well?
It depends on what you call "database management" and what benefits you have on mind. Most likely - no.
A:
What is the benefit of using stored procedures instead of SQL queries from an external connection?
One benefit, in terms of execution, is stored procedures store their query plan whereas dynamic sql query plans will not be stored and must be calculated each time the query is executed.
Is there any execution speed differences between them for small volume and big volume outputs?
Once the query plan is calculated, no, there is no speed difference.
Is there any benefits for the database management as well?
This is very subjective! In the past I worked at a place where ALL database access went through stored procedures so that they could lock down access to just the SPs. Other places I've worked didn't use stored procs at all because they are generally outside source control and problematic for developers who aren't SQL gurus. Also, business logic spread across multiple systems can become a real problem. | unknown | |
d18635 | test | The AWS Lambda function will need to be configured to connect to a private subnet in the same VPC as the Amazon Redshift cluster.
you would be getting timeout issue. to fix this you need to put your lambda function in VPC
you can do that following the tutorial https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html
Then add inbound rule in security group of Redshift for lambda function security group on port 5439
https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-security-groups.html | unknown | |
d18636 | test | There is no base R equivalent short hand
Generally, if you have a data.frame, you can simply create the appropriate character vector from the names
# if you have a data.frame called df
hands <- grep('^hands', names(df), value = TRUE)
# you can now use this character vector
If you are using dplyr, it comes with a number of special functions for use within select
eg:
library(dplyr)
df <- tbl_df(df)
select(df, starts_with("hands")) | unknown | |
d18637 | test | try using the MigrateDatabaseToLatestVersion initializer, check the section entitled "Automatically Upgrading on Application Startup (MigrateDatabaseToLatestVersion Initializer)" here
it should look something like this
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext , Configuration>());
var appDbContext = new ApplicationDbContext();
appDbContext.Database.Initialize(true); | unknown | |
d18638 | test | The issue is that needle offers shortcuts to create a header for your REST requests. These were overriding my headers and caused a compressed response body to be returned. I simply removed my custom header and used Needle's format instead:
var options = {
compressed: true,
accept: 'application/json',
content_type: 'application/json'
};
I then moved my body to a separate array:
var data = {
"username": "***********", "password":"*********"
}
Finally I created the request:
needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', data, options, function(err, resp, body) {
...
}
this then allowed me to access the response body without issues. | unknown | |
d18639 | test | import os, ssl
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/home/ubuntu/shared/'
certfile = "/home/ubuntu/keys/fullchain.pem"
keyfile = "/home/ubuntu/keys/privkey.pem"
ecdh_curve = "secp384r1"
cipherlist = "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305"
sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslcontext.options |= ssl.OP_NO_TLSv1
sslcontext.options |= ssl.OP_NO_TLSv1_1
sslcontext.protocol = ssl.PROTOCOL_TLSv1_2
sslcontext.set_ciphers(cipherlist)
sslcontext.set_ecdh_curve(ecdh_curve)
sslcontext.load_cert_chain(certfile, keyfile)
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
my_data = request.files.getlist('file')
my_pass = request.form['password']
if my_data and my_pass == 'yakumo':
for file in my_data:
my_handler(file)
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file multiple name=file>
<input type="password" name="password" value="">
<input type=submit value=Upload>
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
def my_handler(f):
filename = secure_filename(f.filename)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, ssl_context=sslcontext, threaded=True, debug=False)
I made a very rookie mistake and didn't for-loop over the multiple files being uploaded. The code here was tested without issues with 4 simultaneous file uploads. I hope it will be useful to someone.
Edit: Code updated with some sweet TLS_1.2 and a password field. Enjoy a reasonably secure upload server. Password is transferred over HTTPS. | unknown | |
d18640 | test | You can override EDITOR environment variable just for one git execution:
EDITOR=nano git commit -a | unknown | |
d18641 | test | You'll want to use the callback method of $.fn.show, read more at http://api.jquery.com/show/
Here's a fiddle showing the proposed change: http://jsfiddle.net/pewt8/ | unknown | |
d18642 | test | Yes you can use MySQL to drive a website using ASP.NET or any other web development technology for that matter. The reason for choosing SQL Server over MySQL would if there were features or performance characteristics you wanted in SQL Server that did not exist in MySQL. For example, common-table expressions do not exist in MySQL. If there are no features in either that are driving your decision, then it comes down to personal preference and cost.
A: If you're more comfortable with Sql Server then clearly it'd be worth going down that route, for a small scale site it really does come down to personal preference. That said there are things such as the asp.net membership providers that come, by default, with support for Sql Server as opposed to MySql so that could be a deciding factor for you.
Ultimately, it comes down to personal choice. Which do you prefer and are you willing to pay if Sql Server is your preference? | unknown | |
d18643 | test | As Marcelo said, you can't do this using the property itself.
You would either have to:
*
*Add a method to tempTask that returns a pointer to the estimatedTime iVar (NSInteger *pointer = sharedManager.tempTask.estimatedTimePointer)
*Use a temporary NSInteger, taking its address for whatever calls you need, then copy the result into estimatedTime
Option 1 is probably a really bad idea, because it breaks object encapsulation.
A: Properties aren't variables; they are just syntactic sugar for get/set-style methods. Consequently, you can't take the address of a property.
A: For using numbers in pointers I would suggest using a NSNumber* rather than a NSInteger* (an NSInteger is really an int). For example, if sharedManager.tempTask.estimatedTime is an NSInteger, you could do:
NSNumber *pointer = [NSNumber numberWithInt:sharedManager.tempTask.estimatedTime];
Now, when you want to use the int value for the number do:
NSInteger i = [n intValue];
The NSNumber * is a obj-c object so the usual retain/release/autorelease mechanisms apply.
A: Actually when you say Object1.Propertyxy.Property1
It is actually called as a FUNCTION rather than a VARIABLE/VALUE at some memory.
In your case "tempTask" will act as a
function and "estimatedTime" as a
argument and the result would be the
RETURN of the function.
I know and completely agree that pointers are very favorable for increasing speed but in this case it is just useless as it would require storing that PROPERTY somewhere and thereafter referring to i, just a waste of time and memory, go for it only if you have to use that very specefic property a 100 times per run :D
Hope this helped, if it didn't just let me know, I'll be glad to help. | unknown | |
d18644 | test | This is the closure concept. It is worded differently here than normal. Basically there are two things going on -- first you have the closure, that is the variables that are declared locally to the context of the function definition are made available to the function. This is the "scope chain" he refers to. In addition, locally defined variables (var statements within the function) don't exist until the function starts at "execution context". (Typically these are stored on the stack or a heap). | unknown | |
d18645 | test | First of all, the public methods of UIManager are static. It is incorrect, misleading, and pointless to create an instance of UIManager. The correct way to invoke those methods is:
UIManager.put("OptionPane.background", Color.BLUE);
UIManager.put("OptionPane.messagebackground", Color.BLUE);
UIManager.put("Panel.background", Color.BLUE);
This is the whole sample.
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame
{
public static void main(String []args) {
UIManager.put("OptionPane.background", Color.blue);
UIManager.put("Panel.background", Color.blue);
UIManager.put("Button.background", Color.white);
String value = JOptionPane.showInputDialog("Enter your name");
System.out.println("Hello " + value);
// exit awt thread
System.exit(1);
}
}
A: In nimbus look and feel these all codes are not usable.
So solution is,
UIManager.put("control", new Color(0, 0, 0));
This is also call "Dark Nimbus" add this top of your main frame's main method.
So it will automatically change All JOptionPane's background.
And also you can't change button background with
UIManager.put("OptionPane.buttonBackground", BLACK);
So you should use,
UIManager.put("nimbusBase", new Color(0, 0, 0));
Remember - but unfortunately, this code will change all your buttons etcs' background. So you have to add *.setBackground(...); to all other objects.
If you want to change foreground of JOptionPane you should use
UIManager.put("text", new Color(255, 255, 255));
Again unfortunately this will change your all of text's foreground.
These all codes are called Dark Nimbus.
If you're using nimbus you can try these UIManager codes to customize nimbus look and feel.
UIManager.put("control", new Color(0, 0, 0));
UIManager.put("info", new Color(0, 0, 0));
UIManager.put("nimbusBase", new Color(0, 0, 0));
UIManager.put("nimbusAlertYellow", new Color(248, 187, 0));
UIManager.put("nimbusDisabledText", new Color(255, 255, 255));
UIManager.put("nimbusFocus", new Color(115, 164, 209));
UIManager.put("nimbusGreen", new Color(176, 179, 50));
UIManager.put("nimbusInfoBlue", new Color(66, 139, 221));
UIManager.put("nimbusLightBackground", new Color(0, 0, 0));
UIManager.put("nimbusOrange", new Color(191, 98, 4));
UIManager.put("nimbusRed", new Color(169, 46, 34));
UIManager.put("nimbusSelectedText", new Color(255, 255, 255));
UIManager.put("nimbusSelectionBackground", new Color(18, 134, 175));
UIManager.put("text", new Color(255, 255, 255));
You can try these codes. In my project the nimbus seem as
But I always recommend using "Flatleaf" (Search google "FlatLafLookAndFeel" or go to jar.download.com"). It is a professional and you can change all to your own. | unknown | |
d18646 | test | There are ultimately a number of difficulties you may well run into as you attempt this. The bottom line is that to get at dynamically-generated content, you have to render the page, which is a lot different operation from simply downloading what the HTTP server gives you for a given URL.
In addition, it's not clear what you're using to render the web page. You are using a class named HtmlDocument and a method named LoadHtml(). This suggests that you are using Html Agility Pack, but your question is silent on that point. To my recollection, that library doesn't render HTML; but I could be wrong or have out of date information.
All that said, there is a very clear bug in your code. You create an event handle, which is apparently used to signal the completion of the asynchronous operation, but you never wait on it. This means that the thread that started the I/O will just keep going and attempt to retrieve the result before it is actually available.
One way to address that would be to wait on the event handle:
protected void retrieveDataSource(int matchId_val)
{
ManualResetEvent completionEvent = new ManualResetEvent(false);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
{
source = e.Result;
completionEvent.Set();
};
wc.DownloadStringAsync(new Uri("http://na.lolesports.com/tourney/match/" + matchId_val));
completionEvent.WaitOne();
}
Of course, if you're just going to make the thread block while you wait for the operation to complete, that raises the question of why are you using asynchronous I/O at all? Why not just call DownloadString() instead, which will automatically block until the operation is done.
I also advise against the use of a class field for the purpose of passing data from a called method to the caller. It would make more sense here for retrieveDataSource() to return the result to the caller directly. Were the code written in that way, the issue with the thread synchronization would have been more readily apparent, as you likely would have noticed the method returning before that value was actually available.
But if you insist on using the asynchronous method, the above change should at least resolve your thread synchronization issue. | unknown | |
d18647 | test | The latter doesn't work because the decimal value is boxed into an object. That means to get the value back you have to unbox first using the same syntax of casting, so you have to do it in 2 steps like this:
double dd = (double) (decimal) o;
Note that the first (decimal) is unboxing, the (double) is casting.
A: This can be done with Convert.ChangeType:
class Program
{
static void Main(string[] args)
{
decimal dec = new Decimal(33);
object o = (object)dec;
double dd = GetValue<double>(o);
Console.WriteLine(dd);
}
static T GetValue<T>(object val)
{
return (T)Convert.ChangeType(val, typeof(T));
}
}
The reason your code doesn't work has been well explained by others on this post.
A: You can only cast boxed value types back to the exact type that was boxed in. It doesn't matter if there is an implicit or explicit conversion from the boxed type to the one you are casting to -- you still have to cast to the boxed type (in order to unbox) and then take it from there.
In the example, this means two consecutive casts:
double dd = (double) (decimal) o;
Or, using the Convert methods:
double dd = Convert.ToDouble(o);
Of course this won't do for your real use case because you cannot immediately go from a generic type parameter to ToDouble. But as long as the target type is IConvertible, you can do this:
double dd = (double)Convert.ChangeType(o, typeof(double));
where the generic type parameter T can be substituted for double. | unknown | |
d18648 | test | I think you could use this
You probably are after something like this:
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break(); Of course that will still get
compiled in a Release build. If you want it to behave more like the
Debug object where the code simply doesn't exist in a Release build,
then you could do something like this:
[Conditional("DEBUG")] void DebugBreak() {
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break(); } Then add a call to it in your code. | unknown | |
d18649 | test | There is a extension for that.
Simply search for "highlight-matching-tag" in the extension tab
or download it here: https://marketplace.visualstudio.com/items?itemName=vincaslt.highlight-matching-tag
I recommend to set a custom setting like this:
"highlight-matching-tag.style": {
"borderWidth": "1px",
"borderColor": "orange",
"borderStyle": "solid"
} | unknown | |
d18650 | test | Move all the code in viewDidLoad that depends on the long running operation to another method and then call that method in the completion handler of the long-running process.
A: You could put all of this code into your viewdidload so that the app won't open until that code is finished running.
Are you trying to make it so the app stays on the launch screen until the the data has been fetched.
If I am correct you should just put the code in the viewdidload function it should say.
View did appear and then in the put the code correct me if I am wrong I am new to this.
Can you share the top of your code. | unknown | |
d18651 | test | Yes, you should download the images in the timeline provider and send the timeline when they are all done. Refer to the following recommendation by an Apple frameworks engineer.
I use a dispatch group to achieve this.
Something like:
let imageRequestGroup = DispatchGroup()
var images: [UIImage] = []
for imageUrl in imageUrls {
imageRequestGroup.enter()
yourAsyncUIImageProvider.getImage(fromUrl: imageUrl) { image in
images.append(image)
imageRequestGroup.leave()
}
}
imageRequestGroup.notify(queue: .main) {
completion(images)
}
I then use SwiftUI's Image(uiImage:) initializer to display the images
A: I dont have a good solution, but I try to use WidgetCenter.shared.reloadAllTimelines(), and it make sence.
In the following code.
var downloadImage: UIImage?
func downloadImage(url: URL) -> UIImage {
var picImage: UIImage!
if self.downloadImage == nil {
picImage = UIImage(named: "Default Image")
DispatchQueue.global(qos: .background).async {
do {
let data = try Data(contentsOf: url)
DispatchQueue.main.async {
self.downloadImage = UIImage.init(data: data)
if self.downloadImage != nil {
DispatchQueue.main.async {
WidgetCenter.shared.reloadAllTimelines()
}
}
}
} catch { }
}
} else {
picImage = self.downloadImage
}
return picImage
}
Also you have to consider when to delete this picture.
This like tableView.reloadData(). | unknown | |
d18652 | test | Since you have
CTransaction tran;
outside the first while loop, items keep getting added to it. Move it inside the while loop.
CTransactionSet transSet;
string txtLine;
// read every line from the stream
while (getline(inFile, txtLine))
{
CTransaction tran;
A: I solve the problem by doing what you said R Sahu but the most important solution is by using .ignore so we don't read the part before the ' '
CTransactionSet transSet;
string txtLine;
// read every line from the stream
while (getline(inFile, txtLine))
{
istringstream txtStream(txtLine);
txtStream.ignore(txtLine.length(), ' ');
// read every element from the line that is seperated by commas
// and put it into the vector or strings
string txtElement;
CTransaction tran;
while (getline(txtStream, txtElement, ','))
{
tran.insert(txtElement);
}
transSet.push_back(tran);
} | unknown | |
d18653 | test | x will receive the null value when the user cancels the prompt, so:
var x=prompt("Please enter your name","");
if (x === null) {
// User canceled
}
Live example
A: It returns as if you had clicked cancel.
It is null not as a string ..
alert( prompt('') === null );
will alert true if you press Esc or cancel button | unknown | |
d18654 | test | Check if you have JavaScript disabled in your browser, running this example on jsFiddle does output the alert messages:
To enable JavaScript in Chrome
*
*Click the Chrome menu in the top right hand corner of your browser.
*Select Settings
*Click Show advanced settings
*Under the "Privacy" section, click the Content settings button.
*In the "Javascript" section, select "Allow all sites to run JavaScript (recommended)"
To enable JavaScript in Firefox
Click the Tools drop-down menu and select Options. Check the boxes next to Block pop-up windows, Load images automatically, and Enable JavaScript. Refresh your browser by right-clicking anywhere on the page and selecting Reload, or by using the Reload button in the toolbar.
As the poster mentioned above, if you have any other scripts running somewhere they might be throwing up errors and has nothing to do with JavaScript being disabled. | unknown | |
d18655 | test | I don't see any reason why you couldn't use SSMS in tandom with VS 2010 - actually, for some operations like CREATE DATABASE, you'll have to - you cannot do that from VS.
VS is probably a pretty good database dev environment for 60-80% of your cases - but I doubt you'll be able to completely forget about SSMS. But again: the Visual Studio database projects are really nothing other than collections of SQL scripts - so I don't see why anyone would say you have to "go all the way" with VS if you start using it that way..... it just executes SQL scripts against a SQL database - you can and might need to still use SQL Server Management Studio for some more advanced tasks..... | unknown | |
d18656 | test | I also have the same question,
and here's how I solve it.
You need to .slick("unslick") it first
$('.portfolio-thumb-slider').slick("unslick");
$('.portfolio-item-slider').slick({
slidesToShow: 1,
adaptiveHeight: false,
// put whatever you need
});
Hope that help.
A: There is a method for these kind of things. As documentation states:
slickAdd
html or DOM object, index, addBefore
Add a slide. If an index is provided, will add at that index, or before if addBefore is set. If no index is provided, add to the end or to the beginning if addBefore is set. Accepts HTML String || Object
I would do it like this:
$('#id1').slick();
$.ajax({
url: someurl,
data: somedata,
success: function(content){
var cont=$.parseHTML(content); //depending on your server result
$(cont).find('.dynamically.created.div').each(function(){
$('#id1').slick('slickAdd', $(this));
})
}
})
A: You need the initialise the function again while adding the dynamic element
Suggest you to do this
function sliderInit(){
$('.scroll-footer').slick({
slidesToShow: 2,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000,
arrows: true
});
};
sliderInit();
Call the function here for default load of function and call the same function sliderInit() where you are adding dynamic element.
NOTE : Remember to write this function after adding the element. | unknown | |
d18657 | test | No it is not, If you don't provide then a default name will be given but you can use that name to get that connection some where else.
QSqlDatabase db = QSqlDatabase::database("connectionName");
Here's what documentation says.
If connectionName is not specified, the new connection becomes the
default connection for the application, and subsequent calls to
database() without the connection name argument will return the
default connection. If a connectionName is provided here, use
database(connectionName) to retrieve the connection.
So if you don't provide any name, then whenever the below will return you that connection.
QSqlDatabase db = QSqlDatabase::database(); | unknown | |
d18658 | test | There is a online tool from which you can generate css gradient -
http://www.colorzilla.com/gradient-editor/
On left side of screen you have options to choose colors and on right you have code which you need to copy in your css.
A: Try www.css3generator.com and then select gradient and select color and equivalent code will be generated ..copy the code and use in your CSS.
This site is very helpful.
A: Use CSS3:
body {
background-image: -webkit-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: -moz-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: -o-linear-gradient(top left, white 0%, #9FBFD2 100%);
background-image: linear-gradient(top left, white 0%, #9FBFD2 100%);
} | unknown | |
d18659 | test | I was with you till you said you needed it to run in the main thread. I don't think it's possible the way you describe.
The problem is that you're going to need at least two threads to perform the timing and the actual work, and neither of those can be the main thread because a timer won't use the main thread, and because you'll want the operation to terminate, which if it were the main thread would shut down the whole app. The way you would do this normally is to set up a wrapper class that is run from the main thread and sets up the background thread for the operation as well as the timer.
Why, exactly, does the 3rd party library have to be invoked from the main thread?
A: I knocked together a solution similar to the one linked to, except that I used Thread.Interrupt() instead of Thread.Abort(), thinking that would be a little kinder to the main thread. The problem is that Thread.Interrupt() won't interrupt a call that is blocked, so it is unsatisfactory under many cases. Thread.Abort() is a dangerous call and should be avoided where possible. Pick your poison.
For what it's worth, this is my implementation:
public static class AbortableProc
{
public static void Execute(Action action, Action timeoutAction, int milli)
{
Thread currThread = Thread.CurrentThread;
object stoppedLock = new object();
bool stopped = false;
bool interrupted = false;
Thread timer = new Thread(() =>
{
Thread.Sleep(milli);
lock (stoppedLock)
{
if (!stopped)
{
currThread.Interrupt();
stopped = true;
interrupted = true;
}
}
});
timer.Start();
try
{
action();
lock (stoppedLock)
{
stopped = true;
}
}
catch (ThreadInterruptedException)
{
}
if (interrupted)
{
timeoutAction();
}
}
}
For grins, I put in a timeoutAction so that you could use it in this mode:
AbortableProc.Execute(
() => { Process(kStarting); Process(kWorking); Process(kCleaningUp); },
() => { if (IsWorking()) CleanUp(); }
}; | unknown | |
d18660 | test | Found an answer - Element class doesn't have this functionality anymore, it's been moved to global XmlService, like this:
XmlService.getCompactFormat().format(items[0])
produces what I need - one text line containing xml-formatted items[0] element | unknown | |
d18661 | test | You can use display: inline; inside of display: inline-block;.
.header_class_name {
display: inline;
}
.para_class_name {
display: inline;
word-break: break-word;
}
<h4 class="header_class_name">my title here</h4>
<p class="para_class_name">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
A: edit - adding a solution based on your comment
try using white-space: nowrap;, if that doesn't work, you can try setting the containing div size to a higher width.
you can try doing several things:
*
*wrap both divs with <nobr>
*make the parent div a flexbox with
flex-direction: row; flex-wrap: nowrap;
the problem with this solution is that they would 'leak' outside your viewport width, so I would consider allowing line break/making the font smaller/using elipsis
A: You can use min-width property, so when window shrinks, layout should stay firm. | unknown | |
d18662 | test | Works fine here with
ng build --base-href /ngx/ --output-path dist/ngx,
running http-server from the dist directory, and going to http://localhost:8080/ngx/index.html | unknown | |
d18663 | test | I find my self the solution.
Problem was that I used org.jongo.Jongo instead of JHipster default com.mongodb.Db in @ChangeSet.
For some reasons Jongo doesn't work well with Embedded Mongo.
When I switched to Db, all problems has gone.
NOT WORKING:
@ChangeSet(...)
public void someChange(Jongo jongo) throws IOException {
org.jongo.MongoCollection collection = jongo.getCollection("collection");
DBObject basicDBObject = new BasicDBObject();
collection.insert(basicDBObject);
...
}
WORKING:
@ChangeSet(...)
public void someChange(Db db) throws IOException {
com.mongodb.MongoCollection collection = db.getCollection("collection");
DBObject basicDBObject = new BasicDBObject();
collection.insert(basicDBObject);
...
} | unknown | |
d18664 | test | First, get three last products and get their IDs using wp_get_recent_posts function and map IDs, then add post__not_in argument to WP_query with these three post IDs
$recent_posts = wp_get_recent_posts([
'post_type' => 'product',
'numberposts' => 3
]);
$last_three_posts = array_map(function($a) { return $a['ID']; }, $recent_posts);
$args = array(
'post_type' => 'product',
'orderby' => 'rand',
'posts_per_page' => 3,
'post__not_in' => $last_three_posts,
);
$loop = new WP_Query( $args ); | unknown | |
d18665 | test | There is a design backward compatibility library that bring important material design components to Android 2.1 and above.
See :
http://android-developers.blogspot.fr/2015/05/android-design-support-library.html
Generally speaking, Android always provides some support libraries to provide backward compatibility to previous version on Android.
You will find all you need here :
https://developer.android.com/topic/libraries/support-library/features.html
A: First I should remember Material Design isn't only some code or component else ,It's totally a concept about how design your app to get best UI/UX.
And yes ,android 5 and above ,have some pretty and new features and components ,that you can use some of them in android <5 by some support library that Google or someone else provide them ,
for example look at these two lib:
com.android.support:appcompat-v7
com.android.support:design
these are most useful libs by Google to have material components in android <5 development. | unknown | |
d18666 | test | Xcode 7.1 - Swift 2.0
//Adding Title Label
var navigationTitlelabel = UILabel(frame: CGRectMake(0, 0, 200, 21))
navigationTitlelabel.center = CGPointMake(160, 284)
navigationTitlelabel.textAlignment = NSTextAlignment.Center
navigationTitlelabel.textColor = UIColor.whiteColor()
navigationTitlelabel.text = "WORK ORDER"
self.navigationController!.navigationBar.topItem!.titleView = navigationTitlelabel
A: You can create your own title view to make it.
Something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
//Do any additional setup after loading the view, typically from a nib.
UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; //<<---- Actually will be auto-resized according to frame of navigation bar;
[titleLabelView setBackgroundColor:[UIColor clearColor]];
[titleLabelView setTextAlignment: NSTextAlignmentCenter];
[titleLabelView setTextColor:[UIColor whiteColor]];
[titleLabelView setFont:[UIFont systemFontOfSize: 27]]; //<<--- Greatest font size
[titleLabelView setAdjustsFontSizeToFitWidth:YES]; //<<---- Allow shrink
// [titleLabelView setAdjustsLetterSpacingToFitWidth:YES]; //<<-- Another option for iOS 6+
titleLabelView.text = @"This is a Title";
navigationBar.topItem.titleView = titleLabelView;
//....
}
Hope this helps.
A: I used this code for swift 4 (note label rect is NOT important..)
func navBar()->UINavigationBar?{
let navBar = self.navigationController?.navigationBar
return navBar
}
override func viewDidLoad() {
super.viewDidLoad()
setTNavBarTitleAsLabel(title: "VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY LONGGGGGG")
}
// will shrink label...
func setTNavBarTitleAsLabel(title: String, color: UIColor ){
// removed some code..
let navigationTitlelabel = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
navigationTitlelabel.numberOfLines = 1
navigationTitlelabel.lineBreakMode = .byTruncatingTail
navigationTitlelabel.adjustsFontSizeToFitWidth = true
navigationTitlelabel.minimumScaleFactor = 0.1
navigationTitlelabel.textAlignment = .center
navigationTitlelabel.textColor = color
navigationTitlelabel.text = title
if let navBar = navBar(){
//was navBar.topItem?.title = title
self.navBar()?.topItem?.titleView = navigationTitlelabel
//navBar.titleTextAttributes = [.foregroundColor : color ?? .black]
}
} | unknown | |
d18667 | test | If you are allowed to modify your HTTP request, one way would be to add a ad-hoc HTTP header for the method name :
public String getStuffFromUrl() {
HttpHeaders headers = new HttpHeaders();
headers.add("JavaMethod", "getStuffFromUrl");
entity = new Entity(headers)
...
return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody();
}
You could then get back the method name and remove the header from within the ClientHttpRequestInterceptor prior the HTTP request is actualy sent out.
ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution)
throws IOException {
String javaMethodName="Unknown";
List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod");
if(javaMethodHeader!=null && javaMethodHeader.size()>0) {
javaMethodName = javaMethodHeader.get(0);
}
log.info("Calling method = "+ javaMethodName);
execution.execute(request, body);
}
(provided code not tested) | unknown | |
d18668 | test | Sometimes your workspace could get corrupted.
In my case, I tried to Reload the project and it worked
A: in my case changed JDK version in Maven importer from JDK 11 to my local JDK version 1.8
A: Try this and then build: mvn -U idea:idea
A: Had the same problem. I have tried everything: invalidating cache, deleting the whole .m2 folder, changing settings, reloding the project, nothing helped.
The solution for me was to delete the .iml files which are IntelliJ module files used for keeping module configuration. After reopening the project it worked.
The idea was not mine, I found the hint here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/203365204--package-does-not-exist-error-despite-autocomplete-being-aware-of-them
A: Here is how my IntelliJ settings for spring boot application looks like
Click open -> browse your workspace -> and select POM.xml file
Check this in your intelliJ settings
Do this too [Settings --> Maven --> Importing]
A: I just had the same issue. My solution was to remove all dependencies from the pom, reload via maven -> Reload All Maven Projects. Run mvn compile. Add dependencies back to the pom, maven -> Reload All Maven Projects. Run mvn compile.
Now the Intellij build works.
A: You need to change Maven's JDK for importing option from Project JDK to the Path variable for Java on your machine.
You can get to this by going to Settings -> Build, Execution, Deployment -> Build Tools -> Maven -> Importing. Scroll down to the bottom and look for JDK for importing:. Select from the list the path variable for JAVA.
For Windows users, JAVA_HOME should be an option in the drop-down list.
A: Follow these steps, your problem should be solved. You just need to add Spring-framework-starter-web and Spring-framework-starter-tester from your pom.xml file.
*
*Got to generate(ALT+Insert)
*Add dependencies
*Search "springframwork"
*Add...
Here is the link
A: In my case, adding the project as maven project helped . | unknown | |
d18669 | test | Presumably Content needs a Master ? Actually, constructors are a fairly good way of managing this, but if that is a problem, you could also do something like:
internal class Content {
internal void SetMaster(Master master) {this.master = master; }
//...
}
internal class Master {
internal void SetContent(Content content) {
if(content == null) throw new ArgumentNullException("content");
// maybe handle double-calls...
this.content = content;
content.SetMaster(this);
}
}
...
Master M = new Master();
M.SetContent(new Content());
or have Master create the Content by default. Frankly, though, I'd leave it "as is" until there is an actual "this is a problem".
A: Why not use lazy initialisation idom?
public class Master
{
private Content _content;
internal Content content
{
get
{
if (_content == null)
{
_content = new Content(this);
}
return _content;
}
}
}
If Master always has to have content property set then create Content member during construction:
public class Master
{
internal Content content
{
get; private set;
}
internal Master()
{
content = new Content(this);
}
}
You may also use mixed approach:
public class Master
{
internal Content content
{
get; private set;
}
internal Content GetOrCreateContent()
{
if (content == null)
{
content = new Content(this);
}
return content;
}
internal Master()
{
}
}
A: Since the the code inside the classes is not shown, I have to make some assumptions what you intended to do. As I could see from your code, the Content needs a Master and the Master can't live without a Content.
With the solution I have made for you, you can do the following:
void Main()
{
Master M1 = new Master(); // content instantiated implicitly
Master M2 = new Content().master; // master instantiated implicitly
}
So you can either instantiate the Master and Content within is instantiated, or vice versa: Instantiate a Content and the Master is implicitly instantiated.
No matter which alternative you've chosen: The corresponding other object is always instantiated and available via the property variable.
The classes in this example are defined as follows:
internal class Content {
internal Master master { get; set; }
internal Content(Master pmaster) {
master=pmaster;
}
internal Content() {
master = new Master() { content = this };
}
}
public class Master {
internal Content content { get; set; }
internal Master() {
content = new Content(this);
}
// this is optional and can be omitted, if not needed:
internal Master(Content pcontent) {
content = pcontent;
}
}
Note that I kept the structure you gave in you question as closely as possible, while you have now extra flexibility. | unknown | |
d18670 | test | It essentially provides you the plumbing of wrapping what you put on the command line inside:
while (<>) { ... What you have on cmd line here ... }
So:
perl -e 'while (<>) { if (/^(\w+):/) { print "$1\n"; } }'
and this:
perl -n -e 'if (/^(\w+):/) { print "$1\n" }'
are equivalent.
A: with the -n option, the code in the script will be interpreted as if you writed this :
while (<>) {
<code>
}
for example, the following script, called with a file as an argument will replace all the end of line of the file and send the result on the standard output:
#!usr/bin/perl -n
~s/\n//;
print ;
it must be called like this:
perl script.pl <file> | unknown | |
d18671 | test | str_replace("width:90%", "width:65%", $string)
A: $string = preg_replace("/width:90%/", "width:65%", $string);
if you want to make sure only elements with the class="textbox" are affected:
$string = preg_replace("/(style=\".+)(width:90%)(.+class=\"textbox\")/", "$1width:65%$3", $string);
having it work with any value and unit:
$string = preg_replace("/width:(\d+)(%|px)/", "width:65($2)", $string);
A: Thanks a lot jairajs
this worked for me
preg_replace("/width:\d+(%|px)/", "width:65%", $string)
and thanks to Gerald Schneider for helping me out | unknown | |
d18672 | test | That top space comes from grouped style tableView header. You can add your own table header view at top of the table, set its color to "Group Table View Background Color", and set its height to what you want (16).
A: iOS11 Pure code Solution
Anyone looking to do this in pure code and remove the 35px empty space needs to add a tableHeaderView to their tableView - it appears having it as nil just sets it as default sizing of 35px
i.e.
tableView.tableHeaderView = tableHeaderView
var tableHeaderView:UIView = {
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: CGFloat.leastNormalMagnitude)
return view
}()
Note device width would be your bounds/view width and height is NOT 0 - but CGFloat.leastNormalMagnitude | unknown | |
d18673 | test | Found a different solution, as I cound not find any way forward. Its a simple direct hot encoding. For this I enter for every word I need a new column into the dataframe and create the encoding directly.
vocabulary = ["achtung", "suchen"]
for word in vocabulary:
df2[word] = 0
for index, row in df2.iterrows():
if word in row["title"].lower():
df2.set_value(index, word, 1) | unknown | |
d18674 | test | Replacing elements in mootools is easy, as long as the markup is not invalid as above.
http://jsfiddle.net/dimitar/4WatG/1/
document.getElements("#mydiv span").each(function(el) {
new Element("div", {
html: el.get("html")
}).replaces(el);
});
this will replace all spans for divs in the above markup (use spans instead of trs).
as stated up, http://jsfiddle.net/dimitar/4WatG/ -> firefox strips invalid markup of TR not being a child of a table which makes it hard to target.
A: I'm just going to leave this floating here.
Element.implement({'swapTagName': function(newTagName) {
return new Element(newTagName, {html: this.get('html')}).replaces(this);
}});
Usage:
//cleaning HTML3.2 like it's 2012
target.getElements('font[size=5pt],b').swapTagName('h2').addClass('header_paragraphs');
target.getElements('font').swapTagName('p'); | unknown | |
d18675 | test | Since you're using debian as base OS image, then you cannot add ubuntu's repository as mentioned by Tarun Lalwani in comments. | unknown | |
d18676 | test | To get correct response from the Google server, set User-Agent HTTP header. For example:
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
}
url = "https://google.com/search"
terms = ["thanks", "for", "the help"]
for t in terms:
params = {"q": t, "hl": "en"}
print(f"Getting {t}")
soup = BeautifulSoup(
requests.get(url, params=params, headers=headers).content, "html.parser"
)
divs = soup.findAll("div", attrs={"class": "yuRUbf"})
for div in divs:
print(div.a["href"], div.a.text)
print()
Prints:
Getting thanks
https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks Preklad slova „ thanks ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad
https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks%21 Preklad slova „ thanks! ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad
https://www.merriam-webster.com/dictionary/thanks Thanks | Definition of Thanks by Merriam-Websterhttps://www.merriam-webster.com › dictionary › thanks
https://dictionary.cambridge.org/dictionary/english/thanks THANKS | meaning in the Cambridge English Dictionaryhttps://dictionary.cambridge.org › dictionary › thanks
https://www.thanks.com/ Thanks: Thank Homehttps://www.thanks.com
https://www.dictionary.com/browse/thanks Thanks Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › thanks
https://www.collinsdictionary.com/dictionary/english/thank Thank definition and meaning | Collins English Dictionaryhttps://www.collinsdictionary.com › dictionary › thank
https://www.youtube.com/watch?v=FnpZQoAOUFw THANK YOU and THANKS - How to thank someone in Englishhttps://www.youtube.com › watch
Getting for
https://www.merriam-webster.com/dictionary/for For | Definition of For by Merriam-Websterhttps://www.merriam-webster.com › dictionary › for
https://www.dictionary.com/browse/for For Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › for
https://dictionary.cambridge.org/dictionary/english/for Meaning of for in English - Cambridge Dictionaryhttps://dictionary.cambridge.org › dictionary › for
https://www.macmillandictionary.com/dictionary/british/for FOR (preposition, conjunction) definition and synonymshttps://www.macmillandictionary.com › british › for
https://www.collinsdictionary.com/dictionary/english/for For definition and meaning - English - Collins Dictionaryhttps://www.collinsdictionary.com › dictionary › for
https://www.thefreedictionary.com/for For - definition of for by The Free Dictionaryhttps://www.thefreedictionary.com › for
https://www.learnersdictionary.com/definition/for 1 for - Merriam-Webster's Learner's Dictionaryhttps://www.learnersdictionary.com › definition › for
Getting the help
https://www.imdb.com/title/tt1454029/ The Help (2011) - IMDbhttps://www.imdb.com › title
https://en.wikipedia.org/wiki/The_Help_(film) The Help (film) - Wikipediahttps://en.wikipedia.org › wiki › The_Help_(film)
https://www.vanityfair.com/hollywood/2018/09/viola-davis-the-help-regret Viola Davis Regrets Making The Help: “It Wasn't the Voiceshttps://www.vanityfair.com › Hollywood › viola davis
https://www.csfd.cz/film/277770-cernobily-svet/prehled/ Černobílý svět (2011) | ČSFD.czhttps://www.csfd.cz › film › prehled
https://www.rottentomatoes.com/m/the_help The Help - Rotten Tomatoeshttps://www.rottentomatoes.com › the_help
https://www.usatoday.com/story/entertainment/movies/2020/06/08/the-help-isnt-helpful-resource-racism-heres-why/5322569002/ 'The Help' isn't a helpful resource on racism. Here's why - USA ...https://www.usatoday.com › story › movies › 2020/06/08
https://www.amazon.com/Help-Emma-Stone/dp/B004A8ZWVK The Help : Emma Stone, Octavia Spencer, Jessica - Amazon ...https://www.amazon.com › Help-Emma-Stone
https://www.amazon.com/Help-Kathryn-Stockett/dp/0399155341 The Help: Stockett, Kathryn: 9780399155345 - Amazon.comhttps://www.amazon.com › Help-Kathryn-Stockett
https://www.martinus.sk/?uItem=258803 Kniha: The Help (Kathryn Stockett) - Anglický jazyk - Martinushttps://www.martinus.sk › ... | unknown | |
d18677 | test | Lalit explained the difference between picture size and preview size on camera. You can try this method to get the most optimal size related to the screen size of the device.
private Camera.Size getOptimalSize(Camera.Parameters params, int w, int h) {
final double ASPECT_TH = .2; // Threshold between camera supported ratio and screen ratio.
double minDiff = Double.MAX_VALUE; // Threshold of difference between screen height and camera supported height.
double targetRatio = 0;
int targetHeight = h;
double ratio;
Camera.Size optimalSize = null;
// check if the orientation is portrait or landscape to change aspect ratio.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
targetRatio = (double) h / (double) w;
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
targetRatio = (double) w / (double) h;
}
// loop through all supported preview sizes to set best display ratio.
for (Camera.Size s : params.getSupportedPreviewSizes()) {
ratio = (double) s.width / (double) s.height;
if (Math.abs(ratio - targetRatio) <= ASPECT_TH) {
if (Math.abs(targetHeight - s.height) < minDiff) {
optimalSize = s;
minDiff = Math.abs(targetHeight - s.height);
}
}
}
return optimalSize;
}
A: Picture size This is the size of the image produced when you tell the camera to take a photo. If it is the same aspect ratio as the native resolution then it will be directly scaled from that. If the aspect ratio is different then it will be cropped from the native size. In my experience, the largest size returned by getSupportedPictureSizes is the native resolution of the camera.
Preview size This is the size of the image preview that is shown on-screen. It may be a different aspect ratio than either the native size or the picture size, causing further cropping
To get the closest match between what you see on screen and the image that is produced when you take a photo try to select a preview size with an aspect ratio as close as possible to the aspect ratio of the picture size that you've selected. I generally try to get both as close as possible to the native size.
please also check this link | unknown | |
d18678 | test | It is possible to move label depending on it's rows count
Add render function to the chart object
{
"chart": {
...
events: {
render() {
for (let i = 0; i < this.xAxis[0].names.length; i++) {
const label = this.xAxis[0].ticks[i].label;
const rows = (label.element.innerHTML.match(/<\/tspan>/g) || []).length;
label.translate(-8 * rows, 0);
}
}
}
where 8 is half of row size in px
https://jsfiddle.net/kLz1uoga/5/ | unknown | |
d18679 | test | All problem were in wrong path to /tmp directory.
Docs. Final code for Firebase functions:
const fs = require('fs');
const s3 = require('../../services/storage');
const download = require('download');
const saveMediaItemToStorage = async (sourceId, item) => {
// * creating file name
const fileName = `${item.id}.${item.extension}`;
// * saving file to /tmp folder
await download(item.originalMediaUrl, '/tmp', { filename: fileName });
const blob = fs.readFileSync(`/tmp/${fileName}`);
// * saving file to s3
await s3
.upload({
Bucket: 'name',
Key: `content/${sourceId}/${fileName}`,
Body: blob,
ACL: 'public-read'
})
.promise();
// * remove file from temp folder
fs.unlink(`/tmp/${fileName}`, function (err) {
if (err) return console.log(err);
console.log('file deleted successfully');
});
};
module.exports = saveMediaItemToStorage; | unknown | |
d18680 | test | There is no best way to achieve what you are looking for, considering it goes against the Android Design Guidelines. Although not explicitly stated, the navigation drawer icon and the back button icon are never displayed together.
The theory behind this design is that navigation should be intuitive and predictable, displaying two navigational icons next to each other detracts from an intuitive user interface. The back button should be displayed if there is something to go back to. Though, the need for persistent navigation can be addressed in two different ways. Take Google's Gmail app for example.
By default the NavigationView supports using a swipe from the left edge of the screen as a gesture to open the navigation drawer. In the Gmail app, the navigation drawer icon is show while you are in any one of your inboxes. As soon as a message is selected, the navigation drawer icon is replaced with the back button. Though, you will notice that you can still access the drawer using the gesture stated previously.
On larger screens, the Gmail app supports a miniature navigation drawer. This drawer can remain in view without the need to display to navigational icons. Though this is a little more difficult to implement with the current support library, if you are looking to, this answer may help.
Finally, to answer your question, there is no built-in way to display a back button and a navigation drawer icon together. If you need to do so, the only way would be to use a "work-around", as you currently are.
Though, the only change I would probably make is to use an ImageButton rather than an ImageView. Then you can set the style of the button using style="?android:attr/actionButtonStyle" to mimic the look of an ActionBar button.
A: Just to update, for the time being, to achieve the above what I have done is.
I added a layout to my fragment file where I draw a custom back button like this:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark20"
android:orientation="horizontal"
android:padding="15dp"
android:weightSum="3">
<ImageView
android:id="@+id/backButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:layout_weight="0.2"
android:src="@drawable/delete_icon" />
</LinearLayout>
When a person clicks on backImage, I call popBackStack.
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
The above code gives me the desired functionality.
Note, for the above to work you need to make sure you are adding your fragmentTransaction to backstack as below
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_content_layout,NAME_OFYOUR_FRAGMENT,"nameOfYourFragment");
transaction.addToBackStack(null);
transaction.commit(); | unknown | |
d18681 | test | Maybe because there is no param id.
If you want to set venue location, use location_id.
A: Try doing the same thing with the same parameters here: https://developers.facebook.com/tools/explorer and see what the error message is. | unknown | |
d18682 | test | Put all the power values in a Map so you only need to iterate through cards once instead of running a filter() many times
const cards = [{id: "29210z-192011-222", power: 0.9}, {id: "39222x-232189-12a", power: 0.2}];
const powerMap = new Map(cards.map(({id, power}) => [id, power]));
const wantedId = "39222x-232189-12a"
console.log('Power for id:', wantedId , 'is:', powerMap.get(wantedId)) | unknown | |
d18683 | test | like this:
Objective-C:
UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(80.5, 33)];
[polygonPath addLineToPoint: CGPointMake(119.9, 101.25)];
[polygonPath addLineToPoint: CGPointMake(41.1, 101.25)];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(58, 56, 45, 45)];
[UIColor.redColor setFill];
[ovalPath fill];
Swift:
var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(80.5, 33))
polygonPath.addLineToPoint(CGPointMake(119.9, 101.25))
polygonPath.addLineToPoint(CGPointMake(41.1, 101.25))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(58, 56, 45, 45))
UIColor.redColor().setFill()
ovalPath.fill()
Both produce this:
or this:
Objective-C:
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(40, 18, 91, 91)];
[UIColor.redColor setFill];
[ovalPath fill];
UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(85.5, 18)];
[polygonPath addLineToPoint: CGPointMake(124.9, 86.25)];
[polygonPath addLineToPoint: CGPointMake(46.1, 86.25)];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];
Swift:
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(40, 18, 91, 91))
UIColor.redColor().setFill()
ovalPath.fill()
var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(85.5, 18))
polygonPath.addLineToPoint(CGPointMake(124.9, 86.25))
polygonPath.addLineToPoint(CGPointMake(46.1, 86.25))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()
For this:
And with a frame:
Objective-C:
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect frame = CGRectMake(75, 28, 76, 66);
CGContextSaveGState(context);
CGContextBeginTransparencyLayer(context, NULL);
CGContextClipToRect(context, frame);
UIBezierPath* polygonPath = UIBezierPath.bezierPath;
[polygonPath moveToPoint: CGPointMake(CGRectGetMinX(frame) + 1.48684 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.42424 * CGRectGetHeight(frame))];
[polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.98823 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))];
[polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 0.98546 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))];
[polygonPath closePath];
[UIColor.grayColor setFill];
[polygonPath fill];
UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + floor((CGRectGetWidth(frame) - 44) * 0.50000 + 0.5), CGRectGetMinY(frame) + floor((CGRectGetHeight(frame) - 44) * 1.00000 + 0.5), 44, 44)];
[UIColor.redColor setFill];
[ovalPath fill];
CGContextEndTransparencyLayer(context);
CGContextRestoreGState(context);
Swift:
let context = UIGraphicsGetCurrentContext()
let frame = CGRectMake(75, 28, 76, 66)
CGContextSaveGState(context)
CGContextBeginTransparencyLayer(context, nil)
CGContextClipToRect(context, frame)
var polygonPath = UIBezierPath()
polygonPath.moveToPoint(CGPointMake(frame.minX + 1.48684 * frame.width, frame.minY + 0.42424 * frame.height))
polygonPath.addLineToPoint(CGPointMake(frame.minX + 1.98823 * frame.width, frame.minY + 1.42424 * frame.height))
polygonPath.addLineToPoint(CGPointMake(frame.minX + 0.98546 * frame.width, frame.minY + 1.42424 * frame.height))
polygonPath.closePath()
UIColor.grayColor().setFill()
polygonPath.fill()
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX + floor((frame.width - 44) * 0.50000 + 0.5), frame.minY + floor((frame.height - 44) * 1.00000 + 0.5), 44, 44))
UIColor.redColor().setFill()
ovalPath.fill()
CGContextEndTransparencyLayer(context)
CGContextRestoreGState(context)
This obviously isn't going to draw a bunch of small circles in the triangle, but you've not specified how many circles need to be drawn and so it's impossible to help you further without this very important information, but this will give you a start.
And for reference, here's where you'll need to visit, the following information is dealing with packing problems and math, specifically packing problems with fitting circls inside of triangles:
https://en.wikipedia.org/wiki/Malfatti_circles
http://hydra.nat.uni-magdeburg.de/packing/crt/crt.html#Download
https://en.wikipedia.org/wiki/Circle_packing_in_an_equilateral_triangle
and then this:
Dense Packings of Equal Disks in an Equilateral Triangle R. L. Graham,
B. D. Lubachevsky
Previously published packings of equal disks in an equilateral
triangle have dealt with up to 21 disks. We use a new discrete-event
simulation algorithm to produce packings for up to 34 disks. For each
n in the range 22≤n≤34 we present what we believe to be the densest
possible packing of n equal disks in an equilateral triangle. For
these n we also list the second, often the third and sometimes the
fourth best packings among those that we found. In each case, the
structure of the packing implies that the minimum distance d(n)
between disk centers is the root of polynomial Pn with integer
coefficients. In most cases we do not explicitly compute Pn but in all
cases we do compute and report d(n) to 15 significant decimal digits.
Disk packings in equilateral triangles differ from those in squares or
circles in that for triangles there are an infinite number of values
of n for which the exact value of d(n) is known, namely, when n is of
the form Δ(k):=k(k+1)2. It has also been conjectured that d(n−1)=d(n)
in this case. Based on our computations, we present conjectured
optimal packings for seven other infinite classes of n, namely
n=Δ(2k)+1,Δ(2k+1)+1,Δ(k+2)−2,Δ(2k+3)−3,Δ(3k+1)+2,4Δ(k), and 2Δ(k+1)+2Δ(k)−1.
We also report the best packings we found for other values of n in
these forms which are larger than 34, namely, n=37, 40, 42, 43, 46,
49, 56, 57, 60, 63, 67, 71, 79, 84, 92, 93, 106, 112, 121, and 254,
and also for n=58, 95, 108, 175, 255, 256, 258, and 260. We say that
an infinite class of packings of n disks, n=n(1),n(2),...n(k),..., is
tight , if [1/d(n(k)+1)−1/d(n(k))] is bounded away from zero as k goes
to infinity. We conjecture that some of our infinite classes are
tight, others are not tight, and that there are infinitely many tight
classes.
http://www.combinatorics.org/ojs/index.php/eljc/article/view/v2i1a1
and this as well:
Abstract
This paper presents a computational method to find good, conjecturally
optimal coverings of an equilateral triangle with up to 36 equal
circles. The algorithm consists of two nested levels: on the inner
level the uncovered area of the triangle is minimized by a local
optimization routine while the radius of the circles is kept constant.
The radius is adapted on the outer level to find a locally optimal
covering. Good coverings are obtained by applying the algorithm
repeatedly to random initial configurations.
The structures of the coverings are determined and the coordinates of
each circle are calculated with high precision using a mathematical
model for an idealized physical structure consisting of tensioned bars
and frictionless pin joints. Best found coverings of an equilateral
triangle with up to 36 circles are displayed, 19 of which are either
new or improve on earlier published coverings.
http://projecteuclid.org/euclid.em/1045952348
and then finally, this:
https://en.wikipedia.org/wiki/Malfatti_circles
A: Thanks Larcerax.
I need to draw 53 circles on the boundary of Triangle Like a Rosary. Each circle will be drawn at specific distance.
Out of 53 circles , 5 would be bigger than others(3 on corners(vertices) and other 2 on middle of 2 sides).
Triangle would stand like Cone. | unknown | |
d18684 | test | First of all, your third function is not identical to your second function.
First function
Fixed code:
function addy(c) {
c = parseInt(c);
var sum = 0; // <------- THIS LINE
var nas = c.toString().split('');
for (var i = 0; i < nas.length; i++) {
sum = sum + parseInt(nas[i]);
}
if(sum < 9) {
return sum;
}
addy(sum);
}
console.log(addy(123));
Your original code has a line:
var sum; // sum is undefined
Therefore, when the execution reaches this line:
sum = sum + parseInt(nas[i]);
sum will become NaN because that translate to:
undefined = undefined + parseInt(nas[i]);
To make it work, you simply need to initialise the value of sum:
var sum = 0; // Give sum a default value;
Second function
Fixed code:
function addy(c){
var s=0;
while(c!==0)
{
s = s + parseInt(c%10);
c = parseInt(c/10);
}
if(s>9)
{
s = addy(s);
return s; // <----- THIS LINE
}
else
{
return s;
}
}
console.log(addy(1234));
In original code:
if(s>9)
{
s = addy(s);
}
else
{
return s;
}
Nothing is being returned if s > 9. Therefore you get undefined.
To make it work, you simply need to add a return line:
if (s > 9){
s = addy(s);
return s; // <--- THIS LINE
} else {
return s;
} | unknown | |
d18685 | test | As far as i could see, all classes that are used to establish a PieChart, like PieChart.Data and of course the ObservableList are already designed so that they will update the PieChart the moment something changes, be it the list itself or values inside the Data Objects. See the binding chapters how this is done. But you don't need to write your own bindings for the PieChart.
The code below should do what you want. Use addData(String name, double value) to create a new Data object for your pie chart, or update an existing one which has the same name like the first parameter of the method. The PieChart will automatically play a animation when changes are made to the list (new Data object added) or a Data object got changed.
//adds new Data to the list
public void naiveAddData(String name, double value)
{
pieChartData.add(new Data(name, value));
}
//updates existing Data-Object if name matches
public void addData(String name, double value)
{
for(Data d : pieChartData)
{
if(d.getName().equals(name))
{
d.setPieValue(value);
return;
}
}
naiveAddData(name, value);
}
A: Just in case someone feels extremely lost and isn't sure how to implement denhackl's answer, here is a working version of what he tried to explain.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class LivePie extends Application {
ObservableList<PieChart.Data> pieChartData;
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Imported Fruits");
stage.setWidth(500);
stage.setHeight(500);
this.pieChartData =
FXCollections.observableArrayList();
addData("Test", 5.1);
addData("Test2", 15.1);
addData("Test3", 3.1);
addData("Test1", 4.9);
addData("Test2", 15.1);
addData("Test3", 2.1);
addData("Test5", 20.1);
final PieChart chart = new PieChart(pieChartData);
chart.setTitle("Imported Fruits");
final Label caption = new Label("");
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");
((Group) scene.getRoot()).getChildren().addAll(chart, caption);
stage.setScene(scene);
stage.show();
}
public void naiveAddData(String name, double value)
{
pieChartData.add(new javafx.scene.chart.PieChart.Data(name, value));
}
//updates existing Data-Object if name matches
public void addData(String name, double value)
{
for(javafx.scene.chart.PieChart.Data d : pieChartData)
{
if(d.getName().equals(name))
{
d.setPieValue(value);
return;
}
}
naiveAddData(name, value);
}
public static void main(String[] args) {
launch(args);
}
}
Many thanks to the creator of the topic and the answers provided!
A: Here's a good introductory article on using properties and binding.
http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm | unknown | |
d18686 | test | I think the problem is with your file mask. You are including Tests.class, but your class is called StartTest (notice the missing s) so it won't be included. | unknown | |
d18687 | test | After seeing the link you provided, you simply need to pass and store the section name in SectionListAdapter as below:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
private String mSectionName;
public SectionListDataAdapter(Context context, String sectionName, ArrayList<SingleItemModel> itemsList) {
mSectionName = sectionName;
this.itemsList = itemsList;
this.mContext = context;
}
@Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
@Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
@Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), mSectionName +" : "+ tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Now in your RecyclerViewDataAdapter simply change the one line of initializing SectionListDataAdapter inside your onBindViewHolder as below:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<SectionDataModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<SectionDataModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
@Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
@Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = dataList.get(i).getHeaderTitle();
ArrayList singleSectionItems = dataList.get(i).getAllItemsInSection();
itemRowHolder.itemTitle.setText(sectionName);
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, sectionName, singleSectionItems);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "click event on more, "+sectionName , Toast.LENGTH_SHORT).show();
}
});
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
@Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle;
protected RecyclerView recycler_view_list;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
this.recycler_view_list = (RecyclerView) view.findViewById(R.id.recycler_view_list);
this.btnMore= (Button) view.findViewById(R.id.btnMore);
}
}
} | unknown | |
d18688 | test | The problem here, I believe, is that Haskell defines access functions for all the fields in a record, so you get one function
name :: Person -> String
and then one
name :: PetAnimal -> String
which is what the compiler does not like.
You could change one or both of the names, or put them in different modules.
A: Type Classes are another way to achieve a common interface that you may consider.
data Person = Person { personname :: String -- and some other details
}
data PetAnimal = PetAnimal { petanimalname :: String
}
class HasName a where
name :: a -> String
instance HasName PetAnimal where
name = petanimalname
instance HasName Person where
name = personname | unknown | |
d18689 | test | You can use unicode() to convert a byte string from some encoding to Unicode, but unless you specifiy the encoding, Python assumes it's ASCII.
SQLite does not use ASCII but UTF-8, so you have to tell Python about it:
...join(unicode(y, 'UTF-8') for y in ...) | unknown | |
d18690 | test | The solution is to do all the tasks in one job. Variables are not shared between different job instances.
This works:
jobs:
- job: jobName
steps:
- task: AzureKeyVault@1
inputs:
azureSubscription: '***'
KeyVaultName: '***'
displayName: "Read Secrets from KeyVault"
- task: InstallSSHKey@0
inputs:
knownHostsEntry: $(known_host)
sshPublicKey: $(public_key)
sshKeySecureFile: 'private_key_file'
displayName: "Create SSH files"
- script: |
git clone --recurse-submodules [email protected]:v3/****
git submodule update --init --recursive
docker login -u $(userName) -p $(password) ***
docker build ****
docker push ****
displayName: "Build and Push Docker Container"
A: An alternative is to edit the .gitmodules path to be a relative url, eg url = ../subModuleName:
[submodule "app/subModuleName"]
path = app/subModuleName
url = ../subModuleName
branch = master
The url is now relative to the parent repo's url. So when the ado pipeline clones it via https, it uses the same for the submodule. Developers can clone the repo using either https or ssh, and the submodule will use the same - no need to enter passwords. | unknown | |
d18691 | test | I will have to initialize a new instance of the Financial Report Controller with Print Presenter as one of the instance variable?
No. But you will have to pass the appropriate Print Presenter to the Financial Report Controller somehow.
When you decide which one is appropriate doesn’t have to be on initialization. You could pass it later with a setter. Or you could pass a collection of them to choose from.
Or, like you said, create a new instance of the controller. They all work. Use what makes sense for your situation. | unknown | |
d18692 | test | You ran into issues because the you were using the Date() constructor incorrectly. According to http://www.w3schools.com/js/js_dates.asp, the Date constructor accepts the following inputs:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
In your original code, you were passing a Date object into the "year" argument. I changed:
new Date(lastyear, 0, 1)
to
new Date(lastyear.getFullYear(), 0, 1)
which fixed the problem.
var lastyear = new Date(new Date().getFullYear() - 1, 0, 1);
var start = (new Date(lastyear.getFullYear(), 0, 1)).getTime(),
end = (new Date(lastyear.getFullYear(), 11, 31)).getTime();
Is this the solution you are looking for? | unknown | |
d18693 | test | The query doesn't exclude duplicates, there just isn't any duplicates to exclude. There is only one record with id 3 in the table, and that is included because there is a 3 in the in () set, but it's not included twice because the 3 exists twice in the set.
To get duplicates you would have to create a table result that has duplicates, and join the table against that. For example:
select t.Name
from someTable t
inner join (
select id = 3 union all
select 4 union all
select 5 union all
select 3 union all
select 7 union all
select 8 union all
select 9
) x on x.id = t.id
A: Try this:
SELECT Name FROM Tbl
JOIN
(
SELECT 3 Id UNION ALL
SELECT 4 Id UNION ALL
SELECT 5 Id UNION ALL
SELECT 3 Id UNION ALL
SELECT 7 Id UNION ALL
SELECT 8 Id UNION ALL
SELECT 9 Id
) Tmp
ON tbl.Id = Tmp.Id | unknown | |
d18694 | test | Try using this kind of sintax "? :" for the conditional instead of if/else | unknown | |
d18695 | test | It's easier to write parallel programs for 1000s of threads than it is for 10s of threads. GPUs have 1000s of threads, with hardware thread scheduling and load balancing. Although current GPUs are suited mainly for data parallel small kernels, they have tools that make doing such programming trivial. Cell has only a few, order of 10s, of processors in consumer configurations. (The Cell derivatives used in supercomputers cross the line, and have 100s of processors.)
IMHO one of the biggest problems with Cell was lack of an instruction cache. (I argued this vociferously with the Cell architects on a plane back from the MICRO conference Barcelona in 2005. Although they disagreed with me, I have heard the same from bigsuper computer users of cell.) People can cope with fitting into fixed size data memories - GPUs have the same problem, although they complain. But fitting code into fixed size instruction memory is a pain. Add an IF statement, and performance may fall off a cliff because you have to start using overlays. It's a lot easier to control your data structures than it is to avoid having to add code to fix bugs late in the development cycle.
GPUs originally had the same problems as cell - no caches, neither I nor D.
But GPUs did more threads, data parallelism so much better than Cell, that they ate up that market. Leaving Cell only its locked in console customers, and codes that were more complicated than GPUs, but less complicated than CPU code. Squeezed in the middle.
And, in the meantime, GPUs are adding I$ and D$. So they are becoming easier to program.
A: Why did Cell die?
1) The SDK was horrid. I saw some very bright developers about scratch their eyes out pouring through IBM mailing lists trying to figure out this problem or that with the Cell SDK.
2) The bus between compute units was starting to show scaling problems and never would have made it to 32 cores.
3) OpenCl was about 3-4 years too late to be of any use.
A: I'd say the reasons for the lack of popularity for cell development are closer to:
*
*The lack of success in the PS3 (due to many mistakes on Sony's part and strong competition from the XBOX 360)
*Low manufacturing yield, high cost (partly due to low yield), and lack of affordable hardware systems other than the PS3
*Development difficulty (the cell is an unusual processor to design for and the tooling is lacking)
*Failure to achieve significant performance differences compared to existing x86 based commodity hardware. Even the XBOX 360's several year old triple core Power architecture processor has proven competitive, compared to a modern Core2 Quad processor the cell's advantages just aren't evident.
*Increasing competition from GPU general purpose computing platforms such as CUDA
A:
If you started two or three years ago
to program the cell, will you continue
on this or are you considering
switching to GPU's?
I would have thought that 90% of the people who program for the Cell processor are not in a position where they can arbitrarily decide to stop programming for it. Are you aiming this question at a very specific development community? | unknown | |
d18696 | test | One algorithm comes to mind immediately, though optimizations can be made, if time-complexity is a concern.
At each element in the 2x2 array (or we can call it a matrix if you like), there are 8 directions that we can travel (North, NE, East, SE, South, SW, West, NW).
The pseudo code for the meat of the algorithm goes a bit like this (I assume pass by value, so that "current_string" is a new string at each function call):
find(position, direction, current_string){
new_letter = m[0, position + direction];
if(!current_string.Contains(new_letter)){
// We have not yet encountered this letter during the search.
// If letters occur more than once in the array, then you must
// assign an index to each position in the array instead and
// store which positions have been encountered along each
// search path instead.
current_string += new_letter;
find(position, (0, 1), current_string);
find(position, (1, 1), current_string);
find(position, (1, 0), current_string);
find(position, (1, -1), current_string);
find(position, (0, -1), current_string);
find(position, (-1, -1), current_string);
find(position, (-1, 0), current_string);
find(position, (-1, 1), current_string);
} else {
// This letter has been encountered during this path search,
// terminate this path search. See comment above if letters
// occur more than once in the matrix.
print current_string; // Print one of the found strings!
}
}
Now you need to add some checks for things like "is position + direction outside the bounds of the array, if so, print current_string and terminate".
The high level idea of the algorithm above is to search along all possible paths recursively, terminating paths when they run into themselves (in the same way that snakes die in the game Snake).
If you use hashing to test containment of a new letter against the current string (as per the line if(!current_string.Contains(new_letter)){), which is amortized O(1) searching, then the worst case runtime complexity of this algorithm is linear in the number of possible strings there are in the matrix. I.e. if there are n possible string combonations in the matrix, then this algorithm takes about cn steps to complete for large n, where c is some constant. | unknown | |
d18697 | test | Or another fix is to disconnect from your company intranet, connect to the internet via wifi or using your mobile phone usb tethering. Then try to install the plugin, it will work. It's because np++ domain is blocked by your network administrator
A: Finally! I figured out why thanks to this post here:
https://notepad-plus-plus.org/community/topic/17276/cannot-install-plugins-at-all/11
because my machine is company machine, it appears the proxy must be set
Do this in elevated mode (i.e. open notepad++ as administrator)
after that, from pluginAdmin,
install compare plugin, restarted notepad++, and wala! the plugin is showing up finally!! | unknown | |
d18698 | test | I's use the double-click event here: otherwise it's a bit awkward needing to click out of the cell and back again to reverse the hide/unhide.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim rng As Range
'exit if not in monitored column
If Intersect(Target, Me.Range("O:O")) Is Nothing Then Exit Sub
'check for +/-
If Target.Value = "+" Or Target.Value = "-" Then
Set rng = Target.Offset(1, 0).Resize(8).EntireRow
rng.Hidden = Not rng.Hidden
Target.Value = IIf(rng.Hidden, "+", "-") 'reset cell text
Cancel = True 'don't enter edit mode in the clicked cell
End If
End Sub | unknown | |
d18699 | test | This is just a guess on my part, but I found the exec() to run a command, and you might look that up. You could probably build a string with "global {}" or set it to a throw away value and fill in your built name, and then run the string with exec([stringname]).
Here's just a test I ran from the command prompt in python.
myval = "test1"
mystr = "global " + myval
exec(mystr)
print(mystr)
global test1
print(type("test1"))
<class 'str'>
Hope this helps you. Good luck with your program!
Did you try something like this after your first setting lines?
temp_str = "global " + oddsvar
exec(temp_str)
Again, I'm just guessing. I hope you can get this to work like you need. For the other set of values, you might try building a string, and then using the exec on that. Something like this
temp_str = oddsvar + "mba263.odds_ratios(result)['Odds ratios']"
exec(temp_str) | unknown | |
d18700 | test | If you're running Windows or any case-insensitive filesystem, then there's nothing to do but check one casing. If "Hello.txt" exists, then "hEllo.txt" exists (and is the same file) (the difficult problem here is when you want to make sure that the file is spelled with a given casing in the filesystem)
If you're running a case-sensitive filesystem, just take directory name of the current file, list file contents, and compare entries against the current filename, ignoring case.
A: Take a look at fcaseopen, which demonstrates how to handle case insensitive file operations.
Essentially, the C headers/functions to use are:
*
*From dirent.h, use opendir/readdir/closedir to go thru the files in a directory
*From string.h, use strcasecmp to compare two filesnames, ignoring the case of the characters | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.