_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d17901 | val | One solution could be to remove the cascade "cascade={CascadeType.ALL}"
More on this subject here | unknown | |
d17902 | val | How about just use arrange() on the integer part of variable?
descriptive %>% arrange(as.integer(gsub("Q","",variable)))
Output:
# A tibble: 15 Γ 8
variable n mean sd median iqr min max
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Q1 63 3.94 1.03 4 2 2 5
2 Q2 63 2.86 1.58 3 3 1 5
3 Q3 63 1.97 1.06 2 2 1 4
4 Q4 63 3.98 1.04 4 2 2 5
5 Q5 63 4.21 0.94 4 1 2 5
6 Q6 63 4.05 1.04 4 2 1 5
7 Q7 63 2.38 1.36 2 2.5 1 5
8 Q8 63 4.03 1.05 4 2 2 5
9 Q9 63 2.25 1.12 2 2 1 5
10 Q10 63 1.84 0.88 2 2 1 3
11 Q11 63 2.62 1.31 3 3 1 5
12 Q12 63 3.98 1.01 4 2 2 5
13 Q13 63 4.33 0.8 5 1 2 5
14 Q14 63 1.91 0.88 2 2 1 4
15 Q15 63 4.25 0.95 5 1 2 5
A: We could use mixedorder which would work even if the values have different prefix
library(dplyr)
descriptive %>%
arrange(order(gtools::mixedorder(variable)))
-output
# A tibble: 15 Γ 8
variable n mean sd median iqr min max
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Q1 63 3.94 1.03 4 2 2 5
2 Q2 63 2.86 1.58 3 3 1 5
3 Q3 63 1.97 1.06 2 2 1 4
4 Q4 63 3.98 1.04 4 2 2 5
5 Q5 63 4.21 0.94 4 1 2 5
6 Q6 63 4.05 1.04 4 2 1 5
7 Q7 63 2.38 1.36 2 2.5 1 5
8 Q8 63 4.03 1.05 4 2 2 5
9 Q9 63 2.25 1.12 2 2 1 5
10 Q10 63 1.84 0.88 2 2 1 3
11 Q11 63 2.62 1.31 3 3 1 5
12 Q12 63 3.98 1.01 4 2 2 5
13 Q13 63 4.33 0.8 5 1 2 5
14 Q14 63 1.91 0.88 2 2 1 4
15 Q15 63 4.25 0.95 5 1 2 5
Or with parse_number
descriptive %>%
arrange(readr::parse_number(variable))
A: There are already better soultions. Just for fun:
We could split variable column with regex (?<=[A-Za-z])(?=[0-9]) and then arrange:
library(tidyr)
library(dplyr)
df %>%
separate(variable, c("quarter", "number"), sep = "(?<=[A-Za-z])(?=[0-9])", remove = FALSE) %>%
arrange(quarter, as.numeric(number)) %>%
select(-c(quarter, number))
variable n mean sd median iqr min max
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Q1 63 3.94 1.03 4 2 2 5
2 Q2 63 2.86 1.58 3 3 1 5
3 Q3 63 1.97 1.06 2 2 1 4
4 Q4 63 3.98 1.04 4 2 2 5
5 Q5 63 4.21 0.94 4 1 2 5
6 Q6 63 4.05 1.04 4 2 1 5
7 Q7 63 2.38 1.36 2 2.5 1 5
8 Q8 63 4.03 1.05 4 2 2 5
9 Q9 63 2.25 1.12 2 2 1 5
10 Q10 63 1.84 0.88 2 2 1 3
11 Q11 63 2.62 1.31 3 3 1 5
12 Q12 63 3.98 1.01 4 2 2 5
13 Q13 63 4.33 0.8 5 1 2 5
14 Q14 63 1.91 0.88 2 2 1 4
15 Q15 63 4.25 0.95 5 1 2 5 | unknown | |
d17903 | val | Let's just see what happens when we simplify everything a little bit:
$firstBox = reset($parsed_wiki_syntax['infoboxes']);
if($firstBox) {
foreach($firstBox['contents'] as $content) {
$key = $content['key'];
$value = $content['value'];
echo "<b>" . $key . "</b>: " . $value . "<br><br>";
}
}
The use of array_keys() and the for/foreach loops get a little confusing quickly, so I'm not sure exactly what your error is without looking more. The big trick with my code above is the use of reset() which resets an array and returns (the first element). This lets us grab the first infobox and check if it exists in the next line (before attempting to get the contents of a non-existent key). Next, we just loop through all contents of this first infobox and access the key and value keys directly.
A: You if want to access both keys and values, a simple good ol' foreach will do. Consider this example:
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$contents = $values['infoboxes'][0]['contents'];
foreach($contents as $key => $value) {
echo "[key => " . $value['key'] . "][value = " . htmlentities($value['value']) . "]<br/>";
// just used htmlentities just as to not mess up the echo since there are html tags inside the value
}
Sample Output:
[key => name][value = George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>]
[key => image][value = George Harrison 1974 edited.jpg]
[key => alt][value = Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.]
[key => caption][value = George Harrison at the White House in 1974.]
Sample Fiddle
A: As an exercise in scanning the given array without hardcoding anything.
It doesn't simplify anything, it is not as clear as some of the other answers, however, it would process any structure like this whatever the keys were.
It uses the 'inherited' iterator, that all arrays have, for the 'types' and foreach for the contents.
<?php
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$typeList = current(current($values));
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), '...', '<br />';
foreach(current($typeList) as $content) {
$key = current($content);
next($content);
echo 'content: ', $key, ' => ', current($content), '<br />' ;
} | unknown | |
d17904 | val | Thats because the instances of classes from the new HttpClient module are immutable. So you need to reassign all the properties that you mutate. This translates into the following in your case:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const headers = req.headers.set("ModuleId", this.dnnContext.moduleId).set("TabId", this.dnnContext.tabId);
const clonedRequest= red.clone({
headers: headers
});
// Pass on the cloned request instead of the original request.
return next.handle(clonedRequest);
}
A: I have faced similar issue & figured out your 2nd(TypeError: CreateListFromArrayLike called on non-object) issue, for some
reason if you pass number type(it has type check but if var type is any it allows & it was the case for me) value in header(ModuleId or TabId in your case) it throws this error so you can convert it
to string while passing like:
const authReq = req.clone({
headers: req.headers.set('ModuleId', this.dnnContext.moduleId.toString()).set('TabId', this.dnnContext.tabId.toString())
});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
Also replied on your github issue. | unknown | |
d17905 | val | Take a look at the Java Application Launcher man page.
java -cp aurora.jar; ojdbc6.jar
oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user sched/sched@teach:prod
%BOS_SRC%/credit/card/api/ScheduleCardApi
You have a space between your classpath entries aurora.jar; ojdbc6.jar. The launcher thinks the first jar is the only classpath entry and the ojdbc6.jar is your class containing the main(String[] args) method. It also considers everything after that as arguments to pass to the main(String[] args) method. Remove that space.
A: Remove the space between the aurora.jar; and the ojdbc6.jar
A: Spaces delimit the parameters each other. The JVM interprets the command as if you run "ojdbc6.jar" class: "jar" as a classname and "ojdbc6" as a package.
To concat the names of libraries you want to place into classpath for a specific class run please use semicolon with no spaces as "lib1;lib2"
P.S.: Could you please ask your colleagues if you may paste some of our credentials to the SO? :) | unknown | |
d17906 | val | Normally just clearing Drupal's cache would fix this but if not go into the 'Manage Fields' screen for the content type to which node_data_field_guru_photo, node_data_field_guru_link etc. are attached, make a temporary change (e.g. to the order of the fields) and save. That should force a refresh of the field cache and you should be on your way.
A: Just rearrange the order of you content type fields and then save it. In my case broken or missing handler was showing for Class content type. rearranging the content type fields solved my problem. | unknown | |
d17907 | val | Here you go
select visitors, date(datetime)
from corrected_scanners_per_half_hour
where date_format(datetime, '%H:%i') between '08:30' and '17:30' | unknown | |
d17908 | val | The docs for replace say:
"Updates the value of the component's state to the new value if and only if the value currently is the same as the given oldValue."
https://github.com/apache/nifi/blob/master/nifi-api/src/main/java/org/apache/nifi/components/state/StateManager.java#L79-L92
I would suggest something like this:
if (stateMap.getVersion() == -1) {
stateManager.setState(stateMapProperties, Scope.CLUSTER);
} else {
stateManager.replace(stateMap, stateMapProperties, Scope.CLUSTER);
}
The first time through when you retrieve the state, the version should be -1 since nothing was ever stored before, and in that case you use setState, but then all the times after that you can use replace.
A: The idea behind replace() and the return value is, to be able to react on conflicts. Another task on the same or on another node (in a cluster) might have changed the state in the meantime. When replace() returns false, you can react to the conflict, sort out, what can be sorted out automatically and inform the user when it can not be sorted out.
This is the code I use:
/**
* Set or replace key-value pair in status cluster wide. In case of a conflict, it will retry to set the state, when the given
* key does not yet exist in the map. If the key exists and the value is equal to the given value, it does nothing. Otherwise
* it fails and returns false.
*
* @param stateManager that controls state cluster wide.
* @param key of key-value pair to be put in state map.
* @param value of key-value pair to be put in state map.
* @return true, if state map contains the key with a value equal to the given value, probably set by this function.
* False, if a conflict occurred and key-value pair is different.
* @throws IOException if the underlying state mechanism throws exception.
*/
private boolean setState(StateManager stateManager, String key, String value) throws IOException {
boolean somebodyElseUpdatedWithoutConflict = false;
do {
StateMap stateMap = stateManager.getState(Scope.CLUSTER);
// While the next two lines run, another thread might change the state.
Map<String,String> map = new HashMap<String, String>(stateMap.toMap()); // Make mutable
String oldValue = map.put(key, value);
if(!stateManager.replace(stateMap, map, Scope.CLUSTER)) {
// Conflict happened. Sort out action to take
if(oldValue == null)
somebodyElseUpdatedWithoutConflict = true; // Different key was changed. Retry
else if(oldValue.equals(value))
break; // Lazy case. Value already set
else
return false; // Unsolvable conflict
}
} while(somebodyElseUpdatedWithoutConflict);
return true;
}
You can replace the part after // Conflict happened... with whatever conflict resolution you need. | unknown | |
d17909 | val | You forgot to include jQuery on your JS Fiddle. Add it and it works.
A: I guess thereΒ΄s just an order problem...just a guess
*
*Include jquery
*Include your script at the bottom of your page in $(document).ready(function(){})
*Should work as expected. | unknown | |
d17910 | val | You can replace your second ArrayList by a HashMap and check if it is already there.
movies_info.add(new HashMap<String,String>());
if (!movies_info.get(i).containsKey(title)){
movies_info.get(i).put(title,title);
}
Both the search for a key in the HashMap and also adding a new element have constant time complexity O(1)
To get the values afterwards you can use this code
for (String title : movie_info.get(i).keySet()){
// Use title
}
A: I would suggest a different approach. Instead of creating a list of lists of String-s, you can have a class called Movie and create a list of Movie objects. Then you can directly query the list by calling the contains method.
Note: you need to override two methods in the Movie class, hashCode and equals, for the contains method to work. By overriding these two methods, you will tell the list object how to compare two Movie objects.
UPDATE: you don't have to manually write the equals and hashCode methods (at least not if you are using the Eclipse IDE). You can just right-click anywhere inside the class's body and choose Source -> Generate hashCode and equals ..., it will prompt you on which fields of the class you want to compare two objects, select the fields, hit OK and off you go, these two methods will be automatically generated for you.
Here's a simple example:
public class Movie
{
String title;
public Movie(String t)
{
this.title = t;
}
public String getTitle()
{
return title;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (title == null)
{
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
You can test it like this:
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("Movie 1"));
movies.add(new Movie("Movie 2"));
System.out.println(movies.contains(new Movie("Movie 1")));
}
}
A: Something like this? it simplifies a bit..
for(List<String> mInfo : movies_info) {
if(!mInfo.contains(title)) {
//do stuff
}
} | unknown | |
d17911 | val | TLDR: This is a known bug of long standing. I first wrote about it in 2010:
https://blogs.msdn.microsoft.com/ericlippert/2010/01/18/a-definite-assignment-anomaly/
It is harmless and you can safely ignore it, and congratulate yourself on finding a somewhat obscure bug.
Why doesn't the compiler enforce that Email must be definitely assigned?
Oh, it does, in a fashion. It just has a wrong idea of what condition implies that the variable is definitely assigned, as we shall see.
Why does this code compile if the struct is created in a separate assembly, but it doesn't compile if the struct is defined in the existing assembly?
That's the crux of the bug. The bug is a consequence of the intersection of how the C# compiler does definite assignment checking on structs and how the compiler loads metadata from libraries.
Consider this:
struct Foo
{
public int x;
public int y;
}
// Yes, public fields are bad, but this is just
// to illustrate the situation.
void M(out Foo f)
{
OK, at this point what do we know? f is an alias for a variable of type Foo, so the storage has already been allocated and is definitely at least in the state that it came out of the storage allocator. If there was a value placed in the variable by the caller, that value is there.
What do we require? We require that f be definitely assigned at any point where control leaves M normally. So you would expect something like:
void M(out Foo f)
{
f = new Foo();
}
which sets f.x and f.y to their default values. But what about this?
void M(out Foo f)
{
f = new Foo();
f.x = 123;
f.y = 456;
}
That should also be fine. But, and here is the kicker, why do we need to assign the default values only to blow them away a moment later? C#'s definite assignment checker checks to see if every field is assigned! This is legal:
void M(out Foo f)
{
f.x = 123;
f.y = 456;
}
And why should that not be legal? It's a value type. f is a variable, and it already contains a valid value of type Foo, so let's just set the fields, and we're done, right?
Right. So what's the bug?
The bug that you have discovered is: as a cost savings, the C# compiler does not load the metadata for private fields of structs that are in referenced libraries. That metadata can be huge, and it would slow down the compiler for very little win to load it all into memory every time.
And now you should be able to deduce the cause of the bug you've found. When the compiler checks to see if the out parameter is definitely assigned, it compares the number of known fields to the number of fields that were definite initialized and in your case it only knows about the zero public fields because the private field metadata was not loaded. The compiler concludes "zero fields required, zero fields initialized, we're good."
Like I said, this bug has been around for more than a decade and people like you occasionally rediscover it and report it. It's harmless, and it is unlikely to be fixed because fixing it is of almost zero benefit but a large performance cost.
And of course the bug does not repro for private fields of structs that are in source code in your project, because obviously the compiler already has information about the private fields at hand. | unknown | |
d17912 | val | Try to implement your getPhaseTasks service method using a promise
flowAdminApp.factory('taskData', [ '$resource','$q'
function ($resource,$q) {
return {
getPhaseTasks: function (phase_id) {
var defer = $q.defer();
$resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'})
.query({phase_id:phase_id},
function(data){
defer.resolve(data);
},
function(error) {
defer.reject(error);
});
return defer.promise;
}
}
}]);
I think the problem currently is that the $resource api is async in nature and returns an array, which gets filled in the future. Since there is no promise available for your $state routes the resolve function does not wait. | unknown | |
d17913 | val | For both CoreData tread safety and responsiveness of your UI, I'd go with doing the thread switch at the insert point:
for track in allTracks
{
if let i = allObjects.index(where: { $0.sid == ddTools().md5("\(track.song_name)\(track.artist_name)") } ) {
self.log("[NEW][\(i)] Already in DB : \(track.song_name)")
} else {
DispatchQueue.main.async {
self.insert_track(track)
}
}
}
A: Both snippets of code are wrong. allTracks are core-data objects that are attached to a particular context - which is not thread safe. You cannot access these objects - neither reading or writing - from the main thread. You can save the information - and then pass that to the main thread.
If you doing the fetch to use on the main thread, you shouldn't be using a background thread in the first place. It is better to just do the fetch on the main thread. | unknown | |
d17914 | val | Unfortunately, it is not possible to do this at this time with the New Relic User Interface. We always appreciate insight into the needs of our customers so we have submitted a feature request on your behalf and should such functionality become available you will be notified.
Thanks!
Dana
New Relic - Tech Support
A: If you only need it to support users within your company, a firefox/chrome extension that injects the relevant content into the page could work. | unknown | |
d17915 | val | Based on Audio Channel Manipulation you could try splitting into n separate streams the amerge them back together:
-filter_complex "\
[0:a]pan=mono|c0=c0[a0];\
[0:a]pan=mono|c0=c1[a1];\
[0:a]pan=mono|c0=c2[a2];\
[0:a]pan=mono|c0=c3[a3];\
[0:a]pan=mono|c0=c4[a4];\
[0:a]pan=mono|c0=c5[a5];\
[0:a]pan=mono|c0=c6[a6];\
[0:a]pan=mono|c0=c7[a7];\
[0:a]pan=mono|c0=c8[a8];\
[0:a]pan=mono|c0=c9[a9];\
[0:a]pan=mono|c0=c10[a10];\
[0:a]pan=mono|c0=c11[a11];\
[0:a]pan=mono|c0=c12[a12];\
[0:a]pan=mono|c0=c13[a13];\
[0:a]pan=mono|c0=c14[a14];\
[0:a]pan=mono|c0=c15[a15];\
[0:a]pan=mono|c0=c16[a16];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9][a10][a11][a12][a13][a14][a15][a16]amerge=inputs=17"
A: Building on the answer from @aergistal, and working with an mxf file with 10 audio streams, I had to modify the filter in order to specify the input to every pan filter. Working with "pan=mono" it only uses one channel identified as c0
-filter_complex "\
[0:a:0]pan=mono|c0=c0[a0];\
[0:a:1]pan=mono|c0=c0[a1];\
[0:a:2]pan=mono|c0=c0[a2];\
[0:a:3]pan=mono|c0=c0[a3];\
[0:a:4]pan=mono|c0=c0[a4];\
[0:a:5]pan=mono|c0=c0[a5];\
[0:a:6]pan=mono|c0=c0[a6];\
[0:a:7]pan=mono|c0=c0[a7];\
[0:a:8]pan=mono|c0=c0[a8];\
[0:a:9]pan=mono|c0=c0[a9];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9]amerge=inputs=10" | unknown | |
d17916 | val | Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results.
User DateTime.ParseExact to ensure consistent results. I.E.
DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null); | unknown | |
d17917 | val | Rewriting URLs with query strings is slightly more complicated than rewriting plain URLs. You'll have to write something like this:
RewriteCond %{REQUEST_URI} ^/viewthread\.php$
RewriteCond %{QUERY_STRING} ^tid=12345$
RewriteRule ^(.*)$ http://mydomain.site/abc.php [R=302,L]
See those articles for more help:
*
*http://www.simonecarletti.com/blog/2009/01/apache-query-string-redirects/
*http://www.simonecarletti.com/blog/2009/01/apache-rewriterule-and-query-string/
A: i think because you have missed the ? in the rule...
RewriteRule ^viewthread.php?tid=12345$ abc.php
A: Shouldn't it be:
RewriteRule ^/viewthread\.php\?tid=12345$ /abc.php | unknown | |
d17918 | val | This should provide an outline of what you're trying to do.
--Build Test Data
CREATE TABLE #Rates(Int_Eff_Date DATE
, Int_Rate FLOAT)
CREATE TABLE #Transactions(TransID INT
,MemberID INT
,Trans_Date DATE
,Trans_Value INT)
INSERT INTO #Rates
VALUES ('20160101',7)
,('20161001',7.5)
,('20170110',8)
INSERT INTO #Transactions
VALUES
(1,1,'20160415',150)
,(2,1,'20161018',200)
,(3,1,'20161124',200)
,(4,1,'20170115',250)
;WITH cte_Date_Rates
AS
(
SELECT
S.Int_Eff_Date
,ISNULL(E.Int_Eff_Date,'20490101') AS "Expire"
,S.Int_Rate
FROM
#Rates S
OUTER APPLY (SELECT TOP 1 Int_Eff_Date
FROM #Rates E
WHERE E.Int_Eff_Date > S.Int_Eff_Date
ORDER BY E.Int_Eff_Date) E
)
SELECT
T.*
,R.Int_Rate
FROM
#Transactions T
LEFT JOIN cte_Date_Rates R
ON
T.Trans_Date >= R.Int_Eff_Date
AND
T.Trans_Date < R.Expire | unknown | |
d17919 | val | You can manually specify the tick labels with an array:
ticks: [[0, "0"], [1, ""], [2, ""], [3, ""], [4, ""], [5, "5"]],
Or, you can specify a function to do it:
ticks: function(axis) {
var tickArray = [[0,"0"]];
for(var i=axis.min; i<axis.max+1; i++) {
var label = i%5?"":i;
tickArray.push([i, label]);
}
return tickArray;
},
Demo: http://jsfiddle.net/jtbowden/gryozh7x/
You can also use a tickFormatter:
tickSize: 1,
tickFormatter: function (val, axis) {
return val%5?"":val;
}
Demo: http://jsfiddle.net/jtbowden/gryozh7x/1/ | unknown | |
d17920 | val | Here is code for Afnetworking 3.0 and Swift that worked for me. I know its old thread but might be handy for someone!
let manager: AFHTTPSessionManager = AFHTTPSessionManager()
let URL = "\(baseURL)\(url)"
let request: NSMutableURLRequest = manager.requestSerializer.multipartFormRequestWithMethod("PUT", URLString: URL, parameters: parameters as? [String : AnyObject], constructingBodyWithBlock: {(formData: AFMultipartFormData!) -> Void in
formData.appendPartWithFileData(image!, name: "Photo", fileName: "photo.jpg", mimeType: "image/jpeg")
}, error: nil)
manager.dataTaskWithRequest(request) { (response, responseObject, error) -> Void in
if((error == nil)) {
print(responseObject)
completionHandler(responseObject as! NSDictionary,nil)
}
else {
print(error)
completionHandler(nil,error)
}
print(responseObject)
}.resume()
A: You can use multipartFormRequestWithMethod to create a multipart PUT request with desired data.
For example, in AFNetworking v3.x:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSError *error;
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *value = @"qux";
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:@"baz"];
} error:&error];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
return;
}
// if you want to know what the statusCode was
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
NSLog(@"statusCode: %ld", statusCode);
}
NSLog(@"%@", responseObject);
}];
[task resume];
If AFNetworking 2.x, you can use AFHTTPRequestOperationManager:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSError *error;
NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *value = @"qux";
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:@"baz"];
} error:&error];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
[manager.operationQueue addOperation:operation];
Having illustrated how one could create such a request, it's worth noting that servers may not be able to parse them. Notably, PHP parses multipart POST requests, but not multipart PUT requests.
A: You can create an NSURLRequest constructed with the AFHTTPRequestSerialization's multipart form request method
NSString *url = [[NSURL URLWithString:path relativeToURL:manager.baseURL] absoluteString];
id block = ^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:media
name:@"image"
fileName:@"image"
mimeType:@"image/jpeg"];
};
NSMutableURLRequest *request = [manager.requestSerializer
multipartFormRequestWithMethod:@"PUT"
URLString:url
parameters:nil
constructingBodyWithBlock:block
error:nil];
[manager HTTPRequestOperationWithRequest:request success:successBlock failure:failureBlock];
A: I came up with a solution that can handle any supported method. This is a solution for PUT, but you can replace it with POST as well. This is a method in a category that I call on the base model class.
- (void)updateWithArrayOfFiles:(NSArray *)arrayOfFiles forKey:(NSString *)key params:(NSDictionary *)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
id block = [self multipartFormConstructionBlockWithArayOfFiles:arrayOfFiles forKey:key failureBlock:failure];
NSMutableURLRequest *request = [[self manager].requestSerializer
multipartFormRequestWithMethod:@"PUT"
URLString:self.defaultURL
parameters:nil
constructingBodyWithBlock:block
error:nil];
AFHTTPRequestOperation *operation = [[self manager] HTTPRequestOperationWithRequest:request success:success failure:failure];
[operation start];
}
#pragma mark multipartForm constructionBlock
- (void (^)(id <AFMultipartFormData> formData))multipartFormConstructionBlockWithArayOfFiles:(NSArray *)arrayOfFiles forKey:(NSString *)key failureBlock:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
id block = ^(id<AFMultipartFormData> formData) {
int i = 0;
// form mimeType
for (FileWrapper *fileWrapper in arrayOfFiles) {
NSString *mimeType = nil;
switch (fileWrapper.fileType) {
case FileTypePhoto:
mimeType = @"image/jpeg";
break;
case FileTypeVideo:
mimeType = @"video/mp4";
break;
default:
break;
}
// form imageKey
NSString *imageName = key;
if (arrayOfFiles.count > 1)
// add array specificator if more than one file
imageName = [imageName stringByAppendingString: [NSString stringWithFormat:@"[%d]",i++]];
// specify file name if not presented
if (!fileWrapper.fileName)
fileWrapper.fileName = [NSString stringWithFormat:@"image_%d.jpg",i];
NSError *error = nil;
// Make the magic happen
[formData appendPartWithFileURL:[NSURL fileURLWithPath:fileWrapper.filePath]
name:imageName
fileName:fileWrapper.fileName
mimeType:mimeType
error:&error];
if (error) {
// Handle Error
[ErrorManager logError:error];
failure(nil, error);
}
}
};
return block;
}
Aso it uses FileWrapper Interface
typedef NS_ENUM(NSInteger, FileType) {
FileTypePhoto,
FileTypeVideo,
};
@interface FileWrapper : NSObject
@property (nonatomic, strong) NSString *filePath;
@property (nonatomic, strong) NSString *fileName;
@property (assign, nonatomic) FileType fileType;
@end
A: For RAW Body :
NSData *data = someData;
NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self getURLWith:urlService]]];
[reqeust setHTTPMethod:@"PUT"];
[reqeust setHTTPBody:data];
[reqeust setValue:@"application/raw" forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}];
[task resume];
A: .h
+ (void)PUT:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
success:(void (^)(NSURLResponse *response, id responseObject))success
failure:(void (^)(NSURLResponse * response, NSError *error))failure
error:(NSError *__autoreleasing *)requestError;
.m:
+ (void)PUT:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
success:(void (^)(NSURLResponse * _Nonnull response, id responseObject))success
failure:(void (^)(NSURLResponse * _Nonnull response, NSError *error))failure
error:(NSError *__autoreleasing *)requestError {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:@"PUT"
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
error:(NSError *__autoreleasing *)requestError];
AFURLSessionManager *manager = [AFURLSessionManager sharedManager];//[AFURLSessionManager manager]
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
failure(response, error);
} else {
success(response, responseObject);
}
}];
[uploadTask resume];
}
Just like the classic afnetworking.
Put it to your net work Util :) | unknown | |
d17921 | val | This is an apache timeout error. If you run your PHP script from the command line (instead of through apache), you shouldn't get this timeout error. If you need to run the script through apache, you can increase the FcgidIOTimeout setting in /etc/httpd/conf.d/fcgid.conf, and restart apache, and that should solve the problem.
A: Try using curl, forcing timout
set_time_limit(400);// to infinity for example
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://vcdn8.yobt.tv/content/a8/68/e6/a868e6dc4688ecfc0c26de00ed08db7f871427/vid/1_1024x576.mp4");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
$response = curl_exec($ch);
curl_close($ch);
Then save it to the file. | unknown | |
d17922 | val | To generate n numbers whose sum is m, you can think permutation of m o and n - 1 |, then count o between | and the number of o will be the numbers generated.
For example, given that m = 10 and n = 4, the permutation may be
o|oooo|ooo|oo
Then, the results are 1, 4, 3, 2.
To generate this permutation, you should do shuffle.
You only have to consider position of |, so the implementation may be like this:
int[] generateNumbers(int m, int n) {
if(m < 0 || n <= 0) throw new IllegalArgumentException();
if (n == 1) return new int[]{m};
int separatorNum = n - 1;
int permutationLength = m + n - 1;
int[] positions = new int[separatorNum];
int[] result = new int[n];
// shuffle array of o and |
for (int i = 0; i < separatorNum; i++) {
int p = (int)(Math.random() * (permutationLength - i)) + i;
if (p >= separatorNum) {
// o will be swapped with | if the number was not swapped to | before
boolean dupe = false;
for (int j = 0; j < i; j++) {
if (positions[j] == p) {
dupe = true;
break;
}
}
positions[i] = (dupe ? i : p);
} else {
// another | will be swapped with |, so | will be here
positions[i] =i;
}
}
// sort the positions
for (int i = positions.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (positions[j] > positions[j + 1]) {
int temp = positions[j];
positions[j] = positions[j + 1];
positions[j + 1] = temp;
}
}
}
// decode the positions
result[0] = positions[0];
for (int i = 1; i < n - 1; i++) {
result[i] = positions[i] - positions[i - 1] - 1;
}
result[n - 1] = permutationLength - positions[n - 2] - 1;
return result;
} | unknown | |
d17923 | val | Try this Active Records it'll let you know what you were doing along with query
function update($data = array(), $where = '') {
$where = array('pay_id'=>1,'status'=>'y');
$data = array('awarded' => '129');
$this->db->where($where);
$res = $this->db->update($this->main_table, $data);
$rs = $this->db->affected_rows();
return $rs;
}
A: Here is the query you need in your model function.
class my_model extends CI_Model {
function __construct(){
parent::__construct();
}
/*Model function*/
function update_by($condition = array(),$updateJob=array())
{
if($condition && $updateJob)
{
$this->db->where($condition);
$this->db->update('pay_project', $updateJob );
}
}
}
Now you can use your existing code from controller for your desired purpose.
$updateJob = ['awarded' => '129'];
$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'), $updateJob);
A: use this codeigniter active records for doing database operations
$data = array(
'awarded' => '129'
);
$where = array(
'pay_id'=>1,
'status'=>'y'
);
$this->db->where($where);
$this->db->update('pay_project', $data);
For documentation refer this link
codeigniter active records update
A: Use this
$query = $this->db->query("UPDATE pay_project SET awarded = '129' WHERE pay_id = '1' and status ='y' ");
$result = $query->result_array();
return $result;
A: If you are using Codeigniter My_model class, then you need to change your model like this to work the update_by() function
class Pay_project_model extends MY_Model {
protected $table='pay_project';
function update_by($where = array(),$data=array())
{
$this->db->where($where);
$query = $this->db->update($this->table,$data);
return $query;
}
}
In My_model class there is not a default option to update the class by multiple where conditions, So you need to write update_by() function. Simple copy paste the function inside your class, and this will be work perfectly. | unknown | |
d17924 | val | PyInstaller (version 3.2) works for Python 3.5, according to their website. | unknown | |
d17925 | val | Notifications can be batched for performance optimizations and the delay to deliver notifications can vary based on service load and other factors.
While debugging you should also make sure there's no blocking conditions set by the IDE (like a break point for instance) that might block other incoming requests.
Lastly, it's pretty rare, but service outages can happen, in that case the best thing to do it to contact support. | unknown | |
d17926 | val | Check if the domain user exists before use the EnsureUser method.
If you want to add SharePoint user to group in remote server, we can use CSOM with PowerShell to achieve it.
$url="http://sharepoint.company.com/dev"
$userName="administrator"
$password="**"
$domain="test"
$sGroup="test_group"
$sUserToAdd="domain\user"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object System.Net.NetworkCredential($userName,$password,$domain)
$ctx.Credentials = $credentials
$groups=$ctx.Web.SiteGroups
$ctx.Load($groups)
#Getting the specific SharePoint Group where we want to add the user
$group=$groups.GetByName($sGroup)
$ctx.Load($group)
#Ensuring the user we want to add exists
$user = $ctx.Web.EnsureUser($sUserToAdd)
$ctx.Load($user)
$userToAdd=$group.Users.AddUser($user)
$ctx.Load($userToAdd)
$ctx.ExecuteQuery() | unknown | |
d17927 | val | fn flatten<T>(x: Option<Option<T>>) -> Option<T> {
x.unwrap_or(None)
}
In my case, I was dealing with an Option-returning method in unwrap_or_else and forgot about plain or_else method.
A: These probably already exist, just as different names to what you expect. Check the docs for Option.
You'll see flat_map more normally as and_then:
let x = Some(1);
let y = x.and_then(|v| Some(v + 1));
The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option:
trait MyThings {
fn more_optional(self) -> Option<Self>;
}
impl<T> MyThings for Option<T> {
fn more_optional(self) -> Option<Option<T>> {
Some(self)
}
}
fn main() {
let x = Some(1);
let y = x.more_optional();
println!("{:?}", y);
}
For flatten, I'd probably write:
fn flatten<T>(opt: Option<Option<T>>) -> Option<T> {
match opt {
None => None,
Some(v) => v,
}
}
fn main() {
let x = Some(Some(1));
let y = flatten(x);
println!("{:?}", y);
}
But if you wanted a trait:
trait MyThings<T> {
fn flatten(self) -> Option<T>;
}
impl<T> MyThings<T> for Option<Option<T>> {
fn flatten(self) -> Option<T> {
match self {
None => None,
Some(v) => v,
}
}
}
fn main() {
let x = Some(Some(1));
let y = x.flatten();
println!("{:?}", y);
}
Would there be a way to allow flatten to arbitrary depth
See How do I unwrap an arbitrary number of nested Option types? | unknown | |
d17928 | val | The Django tutorial explains very well how to do this Part 07:
# Admin.py
class QuestionsOfTestInline(admin.StackedInline):
model = QuestionsOfTest
extra = 3
class Test_Admin(admin.ModelAdmin):
inlines = [QuestionsOfTestInline]
admin.site.register(Test, Test_Admin)
This answer was posted as an edit to the question Django Admin - Create an object and Create+Add a many other object (ForeignKey) by the OP Hugo under CC BY-SA 3.0. | unknown | |
d17929 | val | Casting away the const will lead to undefined behavior if the move constructor for bar modifies anything. You can probably work around your issue like this without introducing undefined behavior:
struct wrapped_bar {
mutable bar wrapped;
};
bar buz()
{
return foo<wrapped_bar>().wrapped;
}
Having the wrapped member be mutable means that the member is non-const even though the wrapped_bar object as a whole is const. Based on how foo() works, you may need to add members to wrapped_bar to make it work more like a bar.
A: Technically speaking, you are exposing your program to undefined behavior. Since original object C (a temporary) was declared const, const-casting and modifying it is illegal and against the standard. (I assume, move constructor does some modifications to the movee).
That being said, it probably works in your environment and I do not see a better workaround.
A: As result of function call is by definition an R-Value itself, you do not need to apply std::move on it in return statement - const_cast<bar&&>(foo<bar>()) should be enough. That make code a little bit simpler to read.
Still - there is no standard guarantee that this will always work for all bar types. Even more - this might in some cases lead to undefined behavior.(Imagine some very intrusive optimization, which completely eradicates foo and makes its result an object in "static data" segment of memory - like if foo was a constexpr. Then calling moving constructor, which probably modifies its argument, might lead to access violation exception).
All you can do is either switch to different library (or, if possible, ask library maintainer to fix API) or create some unit test and include it in your build process - as long as test passes, you should be OK (remember to use same optimization settings as in "production" build - const_cast is one of those things which strongly depends on compilation settings). | unknown | |
d17930 | val | For client side validation use jquery and jquery validation. Also enabled client side validation from the web.config:
add key="UnobtrusiveJavaScriptEnabled" value="true"
** Also ensure your styles are being applied using the IE developer toolbar. | unknown | |
d17931 | val | Try
listView.Width = 5;
or
listView.Size = new Size(5, listView.Height);
Size is a struct, so accessing its property will get a copy of it; hence modifying it is not actually modifying the original struct. You're modifying the copy of it. So compiler complains that this is not what you intended.
A: Try the following lines instead.
ListView lvi = new ListView();
MyStruct ms;
ms.Width = 5;
lvi.Size = ms; | unknown | |
d17932 | val | It isn't working because $user->staff() doesn't fetch deleted staff. That's how relationships work by default.
Just replace it with this:
static::restoring(function ($user) {
$user->staff()->withTrashed()->restore();
});
A: "static::restoring" event is never triggered when restoring a batch of models.
If you're doing something like:
Yourmodel::whereIn('id', [1,2,3])->restore();
It will restore your models but "static::restoring or restored" will never be triggered, instead you could do something like this:
$models = Yourmodel::whereIn('id', [1,2,3])->get();
foreach($models as $model) {
$model->restore();
} | unknown | |
d17933 | val | Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.
A: From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise']; | unknown | |
d17934 | val | I think the issue is the parameters of the URL you are constructing for AWS Logout endpoint. (you haven't set logout_uri)
https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html example 1 shows the required parameters to logout and redirect back to the client.
Here is how I've done it.
options.Events = new OpenIdConnectEvents()
{
OnRedirectToIdentityProviderForSignOut = context =>
{
context.ProtocolMessage.IssuerAddress =
GetAbsoluteUri(Configuration["Authentication:Cognito:EndSessionEndPoint"], Configuration["Authentication:Cognito:Authority"]);
context.ProtocolMessage.SetParameter("client_id", Configuration["Authentication:Cognito:ClientId"]);
context.ProtocolMessage.SetParameter("logout_uri", "https://localhost:5001");
return Task.CompletedTask;
}
};
The logout_uri must match exactly the configured signout url on AWS app client settings.
Helper method
private string GetAbsoluteUri(string signoutUri, string authority)
{
var signOutUri = new Uri(signoutUri, UriKind.RelativeOrAbsolute);
var authorityUri = new Uri(authority, UriKind.Absolute);
var uri = signOutUri.IsAbsoluteUri ? signOutUri : new Uri(authorityUri, signOutUri);
return uri.AbsoluteUri;
}
Logging out is done with the two lines below. As you worked out, the first line is logging you out locally by clearing out the local authentication cookie, the second line ordinarily would call off to an end_session endpoint on your IDP to log out of your IDP, however as cognito doesn't have and end_session endpoint, you override that when you configure the middleware via OnRedirectToIdentityProviderForSignOut event, instructing it instead to call off to the logout endpoint that cognito does have, and that's where this URL is used. Since you hadn't constructed that correctly it never logs out of cognito.
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
}
and the configuration values
...
"EndSessionEndPoint": "logout",
"ClientId": "<your client id>",
"Authority": "https://<your domain>.auth.<your region>.amazoncognito.com"
...
hopefully that helps. | unknown | |
d17935 | val | NOT IN is now supported in Hive. See https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF.
A: Try this:
SELECT * FROM table1 WHERE NOT array_contains(array(7,6,5,4,2,12), id)
A: According to the documentation it says you can use not in:
The negated forms can be written as follows:
from DomesticCat cat where cat.name not between 'A' and 'B'
from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )
Are you getting an error when you try your query in the question?
Please try based on the references as well.
*
*Reference 1.
*NOT IN Clause in HQL. | unknown | |
d17936 | val | if (e.KeyCode.ToString() == "w")
should be
if (e.KeyCode == Keys.W)
and so on.
It's in the System.Windows.Forms namespace (see the documentation).
Also check that MoveTriggerTick is correctly registered as timer handler. | unknown | |
d17937 | val | Just wanted to confirm what DesignatedNerd said, about having to have a paid app agreement with Apple before testing can work. I had that yesterday, where we were using our account to test in app products on an app we're doing for a client. After a lot of web searching and other attempts, I happened to notice the text that said that we didn't have an agreement in place. We entered all our bank details in itunesconnect, and a little while later the message was gone, and my in app testing started to work.
A: Wound up having to get everything moved over to the final account, which did have banking and tax info. Exact same code that returned invalid product IDs was totally fine once I set the IAP up with the same name in the other account's app.
So yeah, you need the banking and tax info to even test in the sandbox. Boo-urns. | unknown | |
d17938 | test | Read about size: https://developer.mozilla.org/en-US/docs/Web/CSS/@page/size
Add these code to your HTML file:
<div class="page">...</div>
Add these code to your CSS file
@page {
size: 21cm 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
@media print {
body{
width: 21cm;
height: 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
}
In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:
*
*72 dpi (web) = 595 X 842 pixels
*300 dpi (print) = 2480 X 3508 pixels
*600 dpi (high quality print) = 4960 X 7016 pixels
Yet, I would avoid the hassle and simply use cm (centimetres) or mm (millimetres) for sizing as that avoids rendering glitches that can arise depending on which client you use.
A: You should define size within an @page rule in your CSS stylesheet. It is not intended to be an attribute as you have done in your example.
https://developer.mozilla.org/en-US/docs/Web/CSS/@page
@page {
size: A4;
}
size as an attribute is used to define the width of <input> and <select> elements, either by pixels or number of characters depending on type | unknown | |
d17939 | test | TL;DR: Command substitution $(...) is a shell feature, therefore you must run your commands on a shell:
subprocess.call('docker stop $(docker ps -a -q)', shell=True)
subprocess.call('docker rm $(docker ps -a -q)', shell=True)
Additional improvements:
It's not required, but I would suggest using check_call (or run(..., check=True), see below) instead of call(), so that if an error occurs it doesn't go unnoticed:
subprocess.check_call('docker stop $(docker ps -a -q)', shell=True)
subprocess.check_call('docker rm $(docker ps -a -q)', shell=True)
You can also go another route: parse the output of docker ps -a -q and then pass to stop and rm:
container_ids = subprocess.check_output(['docker', 'ps', '-aq'], encoding='ascii')
container_ids = container_ids.strip().split()
if container_ids:
subprocess.check_call(['docker', 'stop'] + container_ids])
subprocess.check_call(['docker', 'rm'] + container_ids])
If you're using Python 3.5+, you can also use the newer run() function:
# With shell
subprocess.run('docker stop $(docker ps -a -q)', shell=True, check=True)
subprocess.run('docker rm $(docker ps -a -q)', shell=True, check=True)
# Without shell
proc = subprocess.run(['docker', 'ps', '-aq'], check=True, stdout=PIPE, encoding='ascii')
container_ids = proc.stdout.strip().split()
if container_ids:
subprocess.run(['docker', 'stop'] + container_ids], check=True)
subprocess.run(['docker', 'rm'] + container_ids], check=True)
A: There is nice official library for python, that helps with Docker.
https://docker-py.readthedocs.io/en/stable/index.html
import docker
client = docker.DockerClient(Config.DOCKER_BASE_URL)
docker_containers = client.containers.list(all=True)
for dc in docker_containers:
dc.remove(force=True)
We've received all containers and remove them all doesn't matter container status is 'started' or not.
The library could be useful if you can import it into code. | unknown | |
d17940 | test | Complex datatype handling and stuff is to you, this is a 5 minute before-lunch sample to show how much winforms sucks and how much WPF rules:
namespace WpfApplication5
{
public partial class MainWindow : Window
{
private List<Item> _items;
public List<Item> Items
{
get { return _items ?? (_items = new List<Item>()); }
}
public MainWindow()
{
InitializeComponent();
Items.Add(new Item() {Description = "Base metal Thickness"});
for (var i = 32; i > 0; i--)
{
Items.Add(new Item() {Description = "Metal Specification " + i.ToString()});
}
Items.Add(new Item() { Description = "Base metal specification" });
DataContext = this;
}
}
public class Item: INotifyPropertyChanged
{
private List<string> _values;
public List<string> Values
{
get { return _values ?? (_values = new List<string>()); }
}
public event PropertyChangedEventHandler PropertyChanged;
public string Description { get; set; }
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public Item()
{
Values.Add("Value1");
Values.Add("Value2");
Values.Add("Value3");
Values.Add("Value4");
Values.Add("Value5");
Values.Add("Value6");
}
}
}
XAML:
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Description}" Width="130"/>
<ItemsControl ItemsSource="{Binding Values}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=.}" Margin="2" Width="90"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
I see that you have several other requirements here, such as hiding texboxes and stuff. It doesn't matter if these rows are a different data type, you just need to do a ViewModel (which in this case would be my public class Item, which hold the data you want to show in the screen, and let the user be able to interact with.
For example, you could replace the List<string> inside the Item class with something more complex, and add some properties like public bool IsVisible {get;set;} and so on.
I strongly suggest you take a look at WPF (at least for this screen in particular).
Copy and paste my code in a new -> WPF project and you can see the results for yourself.
A: We can't use a grid as the text boxes have to be hidden on a case-by-case basis.
I don't understand why this precludes the use of a DataGridView. A specific DataGridViewCell can be made read-only by setting the ReadOnly property to true. You could then use the DataGridView.CellFormatting event to hide the value of the read-only cells. If I recall correctly, the code would be similar to this:
private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView grid = (DataGridView)sender;
if (grid[e.ColumnIndex, e.RowIndex].ReadOnly)
{
e.Value = string.Empty;
e.FormattingApplied = true;
}
} | unknown | |
d17941 | test | Per wikipedia (https://en.wikipedia.org/wiki/ScaleBase) it is a distributed MySQL implementation. It supports SQL. So, by definition, it doesn't qualify as "NoSQL" | unknown | |
d17942 | test | You should first need to create a PropertySet object because the attachment information is not loaded automatically.
## Target Path Folder
$TargetPath = "c:\temp\attachments"
## Create a PropertySet with the Attachments metadata
$ItemPropetySet = [Microsoft.Exchange.WebServices.Data.PropertySet]::new(
[Microsoft.Exchange.Webservices.Data.BasePropertySet]::IdOnly,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments
)
Then:
## Iterate the items and find messages with attachments
foreach ($item in $fiItems.Items)
{
## Load the Message attachment metadata using the PropertySet Created
$message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind(
$service, $item.Id, $ItemPropetySet)
if ($message.HasAttachments)
{
foreach ($attachment in $message.Attachments)
{
if ($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment])
{
$FilePath = Join-Path $TargetPath $attachment.Name
$attachment.Load($FilePath)
}
}
}
} | unknown | |
d17943 | test | Itβs because when you $unwind a two dimensional array once you end up with just an array and $sum gives correct results when applied to numerical values in $group pipeline stage otherwise it will default to 0 if all operands are non-numeric.
To remedy this, you can use the $sum in a $project pipeline without the need to $unwind as $sum traverses into the array to operate on the numerical elements of the array to return a single value if the expression resolves to an array.
Consider running the following pipeline to get the correct results:
db.collection.aggregate([
{ '$project': {
'answerTotal': {
'$sum': {
'$map': {
'input': '$answers',
'as': 'ans',
'in': { '$sum': '$$ans' }
}
}
}
} }
]) | unknown | |
d17944 | test | "sources":["customDomain.js"] should be relative to the customDomain.map.js file.
Make sure they are in the same directory on your server if this is the case for you.
"file":"customDomain.js" should be changed to the name of the map file, in your case this would be "file":"customDomain.map.js".
Here's a map file example taken from treehouse (sourceRoot may be unnecessary in your case):
{
version: 3,
file: "script.js.map",
sources: [
"app.js",
"content.js",
"widget.js"
],
sourceRoot: "/",
names: ["slideUp", "slideDown", "save"],
mappings: "AAA0B,kBAAhBA,QAAOC,SACjBD,OAAOC,OAAO..."
} | unknown | |
d17945 | test | Found out the answers from wxWidget forum:
this->StatusBar->SetForegroundColour(wxColour(wxT("RED")));
wxStaticText* txt = new wxStaticText( this->StatusBar, wxID_ANY,wxT("Validation failed"), wxPoint(10, 5), wxDefaultSize, 0 );
txt->Show(true); | unknown | |
d17946 | test | The Dreamweaver design view sucks, it usually never gives an accurate representation of how things look in a real browser.
As an alternative and a helpful answer to your issues you can try the live view from dreamweaver that was implemented after CS5.
Here is a video explaining how to set it up.
http://tv.adobe.com/watch/creating-time/dreamweavers-live-view-helps-you-save-time/
As a final note, try not to use the design view and tey to get more into the code... once you get used to it you can read the code and visualize almost exactly (usually always better than design view) how things look. So please do not trust design view in dreamweaver for development. | unknown | |
d17947 | test | I think a CvLinIterator does what you want.
A: Another dirty but efficient way to find the number of points of intersection between circles and line without iterating over all pixels of the line is as follows:
# First, create a single channel image having circles drawn on it.
CircleImage = np.zeros((Height, Width), dtype=np.uint8)
CircleImage = cv2.circle(CircleImage, Center, Radius, 255, 1) # 255-color, 1-thickness
# Then create an image of the same size with only the line drawn on it
LineImage = np.zeros((Height, Width), dtype=np.uint8)
LineImage = cv2.line(LineImage, PointA, PointB, 255, 1) # 255-color, 1-thickness
# Perform bitwise AND operation
IntersectionImage = cv2.bitwise_and(CircleImage, LineImage)
# Count number of white pixels now for the number of points of intersection.
Num = np.sum(IntersectionImage == 255)
This method is also fast as instead of iterating over pixels, it is using OpenCV and numpy libraries.
On adding another circle in the image "CircleImage", you can find the number of interaction points of both the circles and the line AC. | unknown | |
d17948 | test | You can use
SET FMTONLY ON
EXEC dbo.My_Proc
SET FMTONLY OFF
You'll need to capture the error(s) somehow, but it shouldn't take much to put together a quick utility application that takes advantage of this for finding invalid stored procedures.
I haven't used this extensively, so I don't know if there are any side-effects to look out for.
A: You used to get a warning message when you tried to create a stored procedure like that. It would say:
Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object 'dbo.nonexistenttable'. The stored procedure will still be created.
For some reason I'm not getting it now, I'm not sure if it's been changed or if there's just some setting that turns the warning on or off. Regardless, this should give you a hint as to what's happening here.
SQL Server does track dependencies, but only dependencies which actually exist. Unfortunately, none of the dependency tricks like sp_depends or sp_MSdependencies will work here, because you're looking for missing dependencies.
Even if we could hypothetically come up with a way to check for these missing dependencies, it would still be trivial to concoct something to defeat the check:
CREATE PROCEDURE usp_Broken
AS
DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM NonExistentTable'
EXEC sp_executesql @sql
You could also try parsing for expressions like "FROM xxx", but it's easy to defeat that too:
CREATE PROCEDURE usp_Broken2
AS
SELECT *
FROM
NonExistentTable
There really isn't any reliable way to examine a stored procedure and check for missing dependencies without actually running it.
You can use SET FMTONLY ON as Tom H mentions, but be aware that this changes the way that the procedure is "run". It won't catch some things. For example, there's nothing stopping you from writing a procedure like this:
CREATE PROCEDURE usp_Broken3
AS
DECLARE @TableName sysname
SELECT @TableName = Name
FROM SomeTable
WHERE ID = 1
DECLARE @sql nvarchar(4000)
SET @sql = N'SELECT * FROM ' + @TableName
EXEC sp_executesql @sql
Let's assume you have a real table named SomeTable and a real row with ID = 1, but with a Name that doesn't refer to any table. You won't get any errors from this if you wrap it inside a SET FMTONLY ON/OFF block.
That may be a contrived problem, but FMTONLY ON does other weird things like executing every branch of an IF/THEN/ELSE block, which can cause other unexpected errors, so you have to be very specific with your error-handling.
The only truly reliable way to test a procedure is to actually run it, like so:
BEGIN TRAN
BEGIN TRY
EXEC usp_Broken
END TRY
BEGIN CATCH
PRINT 'Error'
END CATCH
ROLLBACK
This script will run the procedure in a transaction, take some action on error (in the CATCH), and immediately roll back the transaction. Of course, even this may have some side-effects, like changing the IDENTITY seed if it inserts into a table (successfully). Just something to be aware of.
To be honest, I wouldn't touch this problem with a 50-foot pole.
A: No (but read on, see last line)
It's by design: Deferred Name Resolution
Erland Sommarskog raised an MS Connect for SET STRICT_CHECKS ON
The connect request has a workaround (not tried myself):
Use check execution plan. The only
weakness is that you may need
permissions to see the execution plan
first
A: You could run sp_depends (see http://msdn.microsoft.com/en-us/library/ms189487.aspx) and use that information to query the information schema (http://msdn.microsoft.com/en-us/library/ms186778.aspx) to see if all objects exist. From what I read here (http://msdn.microsoft.com/en-us/library/aa214346(SQL.80).aspx) you only need to check referenced tables, which is doable.
A: You could check information_schema.tables to check whether a table exist or not and then execute the code
here is quickly slung function to check
create function fnTableExist(@TableName varchar(64)) returns int as
begin
return (select count(*) from information_schema.tables where table_name=@tableName and Table_type='Base_Table')
end
go
if dbo.fnTableExist('eObjects') = 0
print 'Table exist'
else
print 'no suchTable'
like wise you can check for existance of Stored procs / functions in
.INFORMATION_SCHEMA.ROUTINES.Routine_name for th name of the Stored proc/function
A: In SQL 2005 or higher, you can test a stored procedure using transactions and try/catch:
BEGIN TRANSACTION
BEGIN TRY
EXEC (@storedproc)
ROLLBACK TRANSACTION
END TRY
BEGIN CATCH
WHILE @@TRANCOUNT > 0
ROLLBACK
END CATCH
The algorithm to test all stored procedures in a database is a bit more complicated, as you need to workaround SSMS restrictions if you have many SPs which return many result sets. See my blog for complete solution.
A: I've just discovered that VS2010 with database projects will do syntax and name reference checking. Seems like the best option. | unknown | |
d17949 | test | By setting the noclasses attribute to True, only inline styles will be generated. Here's a snippet that does the job just fine:
formatter = HtmlFormatter(style=MyStyle)
formatter.noclasses = True
print highlight(content,PythonLexer(),formatter)
A: @Ignacio: quite the opposite:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
code = 'print "Hello World"'
print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
[ ref.: http://pygments.org/docs/formatters/, see HtmlFormatter ]
( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) )
PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service.
A: Pass full=True to the HtmlFormatter constructor.
A: Usually, your code is only one of many things on a web page. You often want code to look different from the other content. You, generally, want to control the style of the code as part of the overall page style. CSS is your first, best choice for this.
However, you can embed the styles in the HTML if that seems better. Here's an example that shows the <style> tag in the <head> tag.
http://www.w3schools.com/TAGS/tag_style.asp | unknown | |
d17950 | test | I took a look at your questions. This one can be scrutinized by changing the random number.
using np.random.uniform(0,1) does not need any() if you just want random number. But if it is important to have specific numbers for each i you must use any().
for i in range (1,3):
r=np.random.uniform(0,3)
x=np.random.uniform(0,9)
h=np.random.uniform(0,1)
l=r+x
if l<1.0:
q=r
elif l>1.0:
q=10
print("q= ",q,"l= ",l) | unknown | |
d17951 | test | I was able to work around the proxy by using the following:
$wc = New-Object System.Net.WebClient
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc.Proxy.Address = "http://proxyurl"
Once I did this I was able to use Install-PackageProvider Nuget to install the proivder. | unknown | |
d17952 | test | You could try something like this:
front-end
<div class="js-form-message form-group" style="text-align: center">
<div style="display: inline-block;" class="g-recaptcha" data-sitekey="yourkey"></div>
</div>
back-end
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
// not a robot
} else {
// robot
}
The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha. | unknown | |
d17953 | test | You have to set the origin of the Rotation:
Speed_Needle.qml :--
import QtQuick 2.0
Item {
property int value: 0
width: 186
height: 36
Image
{
id: root
source: "files/REE Demo images/pointer_needle2.png"
x : 0
y : 0
transform: Rotation {
id: needleRotation
angle : value
origin.x: root.width / 2 // here!
origin.y: root.height / 2
Behavior on angle {
SmoothedAnimation { velocity: 50 }
}
}
}
} | unknown | |
d17954 | test | It seems that if I explicitly pass in a pandas dataframe object, it solves this error:
source = ColumnDataSource(pd.DataFrame(grouped))
A: Looks like wrong parameter value has passed in groupby() method or in ColumnDataSource()
Syntax:
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)
Parameter by-> list, str, dict
And the code snippet of the constructer of ColumnDataSource is below -
def __init__(self, *args, **kw):
''' If called with a single argument that is a dict or
pandas.DataFrame, treat that implicitly as the "data" attribute.
'''
if len(args) == 1 and "data" not in kw:
kw["data"] = args[0]
# TODO (bev) invalid to pass args and "data", check and raise exception
raw_data = kw.pop("data", {})
if not isinstance(raw_data, dict):
if pd and isinstance(raw_data, pd.DataFrame):
raw_data = self._data_from_df(raw_data)
elif pd and isinstance(raw_data, pd.core.groupby.GroupBy):
raw_data = self._data_from_groupby(raw_data)
else:
raise ValueError("expected a dict or pandas.DataFrame, got %s" % raw_data)
super(ColumnDataSource, self).__init__(**kw)
self.data.update(raw_data)
A: Your version of Bokeh is too old. Support for passing Pandas GroupBy objects was added in version 0.12.7. If you want to be able to pass GroupBy objects directly to initialize a CDS (e.g. to access all the automatic summary statistics that creates), you will need to upgrade to a newer release. | unknown | |
d17955 | test | You can set a property with some unique key for each consumer. Then when you consume messages, use a selector. The link you refer to have already an example selector, `symbol=KZNG', but you could use whatever key/value that suits your need.
Something like receiver=CentralAvenueOffice or receiver=theOldFishFactory | unknown | |
d17956 | test | This is currently not yet possible in Agda due to technical limitations: 'rewrite' is just syntactic sugar for a pattern match on refl, and currently pattern matching on irrelevant arguments is not permitted. In our paper at POPL '19 we describe a criterion for which datatypes in Prop are 'natural' and can thus be pattern matched on. I hope to add this criterion to Agda before the release of 2.6.1, but I cannot make any promises (help on the development of Agda is always welcome). | unknown | |
d17957 | test | Could you try to replace:
#define va_arg( args, type ) *( (type *) args )++
with
#define va_arg( args, type ) *( (type *) args ), args += sizeof (type)
Explanation:
You get the compilation error because this expression:
((type *) args )++
is invalid in C: the result of a cast is not a lvalue and the postfix ++ operator requires its operand to be a lvalue. A lot of compilers are lax with this constraint but apparently yours is not (or the new version is stricter).
Also note that the proposed workaround should work in you program with simple assignment expressions like:
unum = va_arg( args, unsigned int );
because = has higher precedence than the comma operator.
EDIT:
another (maybe even better) solution: you should be able to bypass the fact the result of a cast is not a lvalue using this solution:
#define va_arg( args, type ) *( *(type **) &args )++ | unknown | |
d17958 | test | I incorporated Karan S Warraich's comment about the bool type. I also removed the file parameter to findProducts. But the big issue was the while loop ran forever when it did not find anything. I got rid of it. Also, it was important to get out of the for before the good numbers were lost again and fail was reset. As you note, a number of code cleanups are possible (like found now does nothing, and fail need not be set within findproducts), but here is something that works
bool findproducts (int array[20], int& n1, int& n2, int count, int sum, int& accesses, bool fail)
{
bool found = true;
for( i = 0; i < count; i++)
{
pos1++;
n1 = array[i];
pos2 = 0;
for( x = 0; x < count; x++)
{
pos2++; accesses++;
n2 = array[x];
if(sum == n1 + n2)
{
found = false;
fail = false;
return false;
}
}
}
return true;
}
A: In your findproduct function you are returning bool value while your function is of int type that is either make your function a bool return type or return 1 for true and 0 for false | unknown | |
d17959 | test | One solution would be to "fake" the underline with a bottom border. It might not work depending on the structure of your HTML, but something like this:
text-decoration: none;
border-bottom: 1px solid #FF0000;
A: You cannot isolate the underline color and control it separate from text color; it inherits the same color from the text.
However, you can use border, instead.
nav a {
color: white
text-decoration: none;
border-bottom: 1px solid salmon;
background-color: salmon;
}
nav a.active {
color: #333;
border-bottom: 1px solid #333;
}
A: Use inline-block as display value for each link and apply a bottom border:
ul li a{
display:inline-block;
border-bottom:2px solid #eeeeee;
float:left;
padding: 10px;
background-color:red;
color:#ffffff;
text-decoration:none;
}
change padding, background color and font color as per your style.
A: This is another solution. Put the mouse over the element!
ul{
margin: 0;
padding: 0;
}
ul li a{
height: 50px;
position: relative;
padding: 0px 15px;
display: table-cell;
vertical-align: middle;
background: salmon;
color: black;
font-weight: bold;
text-decoration: none;
}
ul li a:hover:after{
display: block;
content: '\0020';
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 3.5px;
background: #000000;
z-index: 9;
}
<ul>
<li><a href='#'>Menu Item</a></li>
</ul> | unknown | |
d17960 | test | One option to isolate the data is to have a separate schema per tenant. And you can measure the size of the schema using below script.
SET NOCOUNT ON
declare @SourceDB sysname
DECLARE @sql nvarchar (4000)
IF @SourceDB IS NULL BEGIN
SET @SourceDB = DB_NAME () -- The current DB
END
CREATE TABLE #Tables ( [schema] sysname
, TabName sysname )
SELECT @sql = 'insert #tables ([schema], [TabName])
select TABLE_SCHEMA, TABLE_NAME
from ['+ @SourceDB +'].INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = ''BASE TABLE'''
EXEC (@sql)
---------------------------------------------------------------
-- #TabSpaceTxt Holds the results of sp_spaceused.
-- It Doesn't have Schema Info!
CREATE TABLE #TabSpaceTxt (
TabName sysname
, [Rows] varchar (11)
, Reserved varchar (18)
, Data varchar (18)
, Index_Size varchar ( 18 )
, Unused varchar ( 18 )
)
---------------------------------------------------------------
-- The result table, with numeric results and Schema name.
CREATE TABLE #TabSpace ( [Schema] sysname
, TabName sysname
, [Rows] bigint
, ReservedMB numeric(18,3)
, DataMB numeric(18,3)
, Index_SizeMB numeric(18,3)
, UnusedMB numeric(18,3)
)
DECLARE @Tab sysname -- table name
, @Sch sysname -- owner,schema
DECLARE TableCursor CURSOR FOR
SELECT [SCHEMA], TabNAME
FROM #tables
OPEN TableCursor;
FETCH TableCursor into @Sch, @Tab;
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @sql = 'exec [' + @SourceDB
+ ']..sp_executesql N''insert #TabSpaceTxt exec sp_spaceused '
+ '''''[' + @Sch + '].[' + @Tab + ']' + '''''''';
Delete from #TabSpaceTxt; -- Stores 1 result at a time
EXEC (@sql);
INSERT INTO #TabSpace
SELECT @Sch
, [TabName]
, convert(bigint, rows)
, convert(numeric(18,3), convert(numeric(18,3),
left(reserved, len(reserved)-3)) / 1024.0)
ReservedMB
, convert(numeric(18,3), convert(numeric(18,3),
left(data, len(data)-3)) / 1024.0) DataMB
, convert(numeric(18,3), convert(numeric(18,3),
left(index_size, len(index_size)-3)) / 1024.0)
Index_SizeMB
, convert(numeric(18,3), convert(numeric(18,3),
left(unused, len([Unused])-3)) / 1024.0)
[UnusedMB]
FROM #TabSpaceTxt;
FETCH TableCursor into @Sch, @Tab;
END;
CLOSE TableCursor;
DEALLOCATE TableCursor;
select [SCHEMA],SUM(ReservedMB)SizeInMB from #TabSpace
group by [SCHEMA] | unknown | |
d17961 | test | You defined the function two to work with an argument so if you try to type two(), Python will output TypeError: two() missing 1 required positional argument: 'x'.
Now, if you try to type two(x)without having defined x before, you will get a NameError.
Maybe you wanted to write pass_two = two(pass_one) | unknown | |
d17962 | test | Syntastic uses the location list (a window-local variant of the quickfix list), so a :lclose will close it, but keep the other buffers.
As per syntastic's help pages, the initial height can be configured:
:let g:syntastic_loc_list_height=5
But I suspect that your intrusive Janus distribution has a hand in that. Vim "distributions" like spf-13 and Janus lure you with a quick install and out of the box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.
A: Syntastic gets confused when you're juggling multiple buffers on one screen so here's a script that will collect information about the situation, then do the right thing:
function JustCloseSyntasticWindow()
"Check which buffer we are in, and if not, return to the main one:
if &ft == "qf"
normal ZZ
endif
"Since different buffers have different command spaces, check if we've
"escaped the other buffer and then tell syntastic to stop.
if &ft != "qf"
SyntasticReset
" --- or ----
SyntasticToggleMode
endif
endfunction
au FileType buffer1_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>
au FileType main_win_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>
Don't be shy on the duct tape for this job, it's the only thing holding the unit together.
A: The command to close the Syntastic error window is:
:SyntasticReset
A: You can use :lclose to close it. | unknown | |
d17963 | test | This would be pointless. To use the variables in the code you'd need to know what the user had entered. (Hacks like reflection aside.)
Almost certainly what you want is a Map keyed on the String entered. You still have the problem of the type of the maps value, which will depend upon exactly how you are going to use it. | unknown | |
d17964 | test | They changed signature of the method in SignalR 2.1
It now looks like
public override Task OnDisconnected(bool stopCalled) | unknown | |
d17965 | test | A quick swift 4 update to the previous answers:
func encodeVideo(videoUrl: URL, outputUrl: URL? = nil, resultClosure: @escaping (URL?) -> Void ) {
var finalOutputUrl: URL? = outputUrl
if finalOutputUrl == nil {
var url = videoUrl
url.deletePathExtension()
url.appendPathExtension(".mp4")
finalOutputUrl = url
}
if FileManager.default.fileExists(atPath: finalOutputUrl!.path) {
print("Converted file already exists \(finalOutputUrl!.path)")
resultClosure(finalOutputUrl)
return
}
let asset = AVURLAsset(url: videoUrl)
if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) {
exportSession.outputURL = finalOutputUrl!
exportSession.outputFileType = AVFileType.mp4
let start = CMTimeMakeWithSeconds(0.0, 0)
let range = CMTimeRangeMake(start, asset.duration)
exportSession.timeRange = range
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously() {
switch exportSession.status {
case .failed:
print("Export failed: \(exportSession.error != nil ? exportSession.error!.localizedDescription : "No Error Info")")
case .cancelled:
print("Export canceled")
case .completed:
resultClosure(finalOutputUrl!)
default:
break
}
}
} else {
resultClosure(nil)
}
}
A: Swift 5.2 Update Solution
// Don't forget to import AVKit
func encodeVideo(at videoURL: URL, completionHandler: ((URL?, Error?) -> Void)?) {
let avAsset = AVURLAsset(url: videoURL, options: nil)
let startDate = Date()
//Create Export session
guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) else {
completionHandler?(nil, nil)
return
}
//Creating temp path to save the converted video
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
let filePath = documentsDirectory.appendingPathComponent("rendered-Video.mp4")
//Check if the file already exists then remove the previous file
if FileManager.default.fileExists(atPath: filePath.path) {
do {
try FileManager.default.removeItem(at: filePath)
} catch {
completionHandler?(nil, error)
}
}
exportSession.outputURL = filePath
exportSession.outputFileType = AVFileType.mp4
exportSession.shouldOptimizeForNetworkUse = true
let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
let range = CMTimeRangeMake(start: start, duration: avAsset.duration)
exportSession.timeRange = range
exportSession.exportAsynchronously(completionHandler: {() -> Void in
switch exportSession.status {
case .failed:
print(exportSession.error ?? "NO ERROR")
completionHandler?(nil, exportSession.error)
case .cancelled:
print("Export canceled")
completionHandler?(nil, nil)
case .completed:
//Video conversion finished
let endDate = Date()
let time = endDate.timeIntervalSince(startDate)
print(time)
print("Successful!")
print(exportSession.outputURL ?? "NO OUTPUT URL")
completionHandler?(exportSession.outputURL, nil)
default: break
}
})
}
A: Minor refactoring of previous examples:
import AVFoundation
extension AVURLAsset {
func exportVideo(presetName: String = AVAssetExportPresetHighestQuality,
outputFileType: AVFileType = .mp4,
fileExtension: String = "mp4",
then completion: @escaping (URL?) -> Void)
{
let filename = url.deletingPathExtension().appendingPathExtension(fileExtension).lastPathComponent
let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
if let session = AVAssetExportSession(asset: self, presetName: presetName) {
session.outputURL = outputURL
session.outputFileType = outputFileType
let start = CMTimeMakeWithSeconds(0.0, 0)
let range = CMTimeRangeMake(start, duration)
session.timeRange = range
session.shouldOptimizeForNetworkUse = true
session.exportAsynchronously {
switch session.status {
case .completed:
completion(outputURL)
case .cancelled:
debugPrint("Video export cancelled.")
completion(nil)
case .failed:
let errorMessage = session.error?.localizedDescription ?? "n/a"
debugPrint("Video export failed with error: \(errorMessage)")
completion(nil)
default:
break
}
}
} else {
completion(nil)
}
}
}
Also: AVAssetExportPresetHighestQuality preset works when video is played on Android / Chrome.
P.S. Be aware that the completion handler of exportVideo method might not be returned on the main thread.
A: I made some modifications to the following 2 answers to make it compatible with Swift 5:
https://stackoverflow.com/a/40354948/2470084
https://stackoverflow.com/a/39329155/2470084
import AVFoundation
func encodeVideo(videoURL: URL){
let avAsset = AVURLAsset(url: videoURL)
let startDate = Date()
let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough)
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let myDocPath = NSURL(fileURLWithPath: docDir).appendingPathComponent("temp.mp4")?.absoluteString
let docDir2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL
let filePath = docDir2.appendingPathComponent("rendered-Video.mp4")
deleteFile(filePath!)
if FileManager.default.fileExists(atPath: myDocPath!){
do{
try FileManager.default.removeItem(atPath: myDocPath!)
}catch let error{
print(error)
}
}
exportSession?.outputURL = filePath
exportSession?.outputFileType = AVFileType.mp4
exportSession?.shouldOptimizeForNetworkUse = true
let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
let range = CMTimeRange(start: start, duration: avAsset.duration)
exportSession?.timeRange = range
exportSession!.exportAsynchronously{() -> Void in
switch exportSession!.status{
case .failed:
print("\(exportSession!.error!)")
case .cancelled:
print("Export cancelled")
case .completed:
let endDate = Date()
let time = endDate.timeIntervalSince(startDate)
print(time)
print("Successful")
print(exportSession?.outputURL ?? "")
default:
break
}
}
}
func deleteFile(_ filePath:URL) {
guard FileManager.default.fileExists(atPath: filePath.path) else{
return
}
do {
try FileManager.default.removeItem(atPath: filePath.path)
}catch{
fatalError("Unable to delete file: \(error) : \(#function).")
}
}
A: Here is some code that you can use to convert the recorded video into MP4:
func encodeVideo(videoURL: NSURL) {
let avAsset = AVURLAsset(URL: videoURL, options: nil)
var startDate = NSDate()
//Create Export session
exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough)
// exportSession = AVAssetExportSession(asset: composition, presetName: mp4Quality)
//Creating temp path to save the converted video
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let myDocumentPath = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent("temp.mp4").absoluteString
let url = NSURL(fileURLWithPath: myDocumentPath)
let documentsDirectory2 = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let filePath = documentsDirectory2.URLByAppendingPathComponent("rendered-Video.mp4")
deleteFile(filePath)
//Check if the file already exists then remove the previous file
if NSFileManager.defaultManager().fileExistsAtPath(myDocumentPath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(myDocumentPath)
}
catch let error {
print(error)
}
}
url
exportSession!.outputURL = filePath
exportSession!.outputFileType = AVFileTypeMPEG4
exportSession!.shouldOptimizeForNetworkUse = true
var start = CMTimeMakeWithSeconds(0.0, 0)
var range = CMTimeRangeMake(start, avAsset.duration)
exportSession.timeRange = range
exportSession!.exportAsynchronouslyWithCompletionHandler({() -> Void in
switch self.exportSession!.status {
case .Failed:
print("%@",self.exportSession?.error)
case .Cancelled:
print("Export canceled")
case .Completed:
//Video conversion finished
var endDate = NSDate()
var time = endDate.timeIntervalSinceDate(startDate)
print(time)
print("Successful!")
print(self.exportSession.outputURL)
default:
break
}
})
}
func deleteFile(filePath:NSURL) {
guard NSFileManager.defaultManager().fileExistsAtPath(filePath.path!) else {
return
}
do {
try NSFileManager.defaultManager().removeItemAtPath(filePath.path!)
}catch{
fatalError("Unable to delete file: \(error) : \(__FUNCTION__).")
}
}
Source: https://stackoverflow.com/a/39329155/4786204
A: Run on iOS11, we will always received the nil value for the AVAssetExportSession. Do we have any solution for this case?
if let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) {
//work on iOS 9 and 10
} else {
//always on iOS 11
} | unknown | |
d17966 | test | Create the $resource object with:
function branchResource($resource){
ΜΆrΜΆeΜΆtΜΆuΜΆrΜΆnΜΆ ΜΆ$ΜΆrΜΆeΜΆsΜΆoΜΆuΜΆrΜΆcΜΆeΜΆ(ΜΆ"ΜΆ/ΜΆaΜΆpΜΆiΜΆ/ΜΆuΜΆsΜΆeΜΆrΜΆ/ΜΆGΜΆeΜΆtΜΆAΜΆlΜΆlΜΆUΜΆsΜΆeΜΆrΜΆBΜΆrΜΆaΜΆnΜΆcΜΆhΜΆeΜΆsΜΆ?ΜΆfΜΆeΜΆdΜΆeΜΆrΜΆaΜΆtΜΆeΜΆdΜΆUΜΆsΜΆeΜΆrΜΆNΜΆaΜΆmΜΆeΜΆ=ΜΆ:ΜΆuΜΆsΜΆeΜΆrΜΆ"ΜΆ)ΜΆ ΜΆ
return $resource("/api/user/GetAllUserBranches")
}}
Call the $resource object with:
branchResource.query({"federatedUserName": vm.user}, function (data) {
vm.branches = data;
});
//OR
vm.branches = branchResource.query({"federatedUserName": vm.user});
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
For more information, see AngularJS ngResource $resource API Reference. | unknown | |
d17967 | test | This will happen if you have two sessions (in your case, Java threads) that try to insert the same ORDER_REF_ID. Consider the following scenario:
1) Session 1 executes this MERGE statement (without committing it):
merge into ORDER_LOCK al
using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t
on (al.ORDER_REF_ID = t.ORDER_REF_ID)
when not matched then
insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT)
values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT);
2) Session 2 starts the same MERGE statement:
merge into ORDER_LOCK al
using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t
on (al.ORDER_REF_ID = t.ORDER_REF_ID)
when not matched then
insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT)
values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT);
(this will try to insert the row, since Session 2 doesn't "see" the uncommitted changes from Session 1. Session 2 will block, since it is waiting for the lock held by Session 1):
3) Session 1 commits
=> Session 2 now tries to perform the insert, which will raise an ORA-00001: UNIQUE CONSTRAINT VIOLATION since the ORDER_REF_ID 1 already exists
UPDATE
To fix this problem, I'd suggest you modify your application and introduce some kind of affinity between Java threads and ORDER_REF_IDs - each ORDER_REF_ID should "belong" to exactly one thread, and that thread should exclusively insert / update data for its ORDER_REF_ID. | unknown | |
d17968 | test | Change this line
FileOutputStream file= new FileOutputStream(filename);
to this
FileOutputStream file= new FileOutputStream(filename, true)
The true stands for append enable or disable. In default it is disabled. | unknown | |
d17969 | test | The Fix is to apply scaling to mouse coordinates too:
let scale = 1;
$(document).ready(function ($) {
$(window).resize(function () {
nsZoomZoom();
});
//Get screen resolution.
origHeigth = window.screen.height * window.devicePixelRatio;
origWidth = window.screen.width * window.devicePixelRatio;
nsZoomZoom();
function nsZoomZoom() {
//Calculating scalse
let htmlWidth = $(window).innerWidth();
var htmlHeigth = $(window).height();
var xscale = htmlWidth / origWidth;
var yscale = htmlHeigth / origHeigth;
//This is done to handle both X and Y axis slacing
scale = Math.min(xscale, yscale);
//Add 10% to scale because window always less than screen resolution
scale += scale / 10;
//Change Cuacamole Display scale
guac.getDisplay().scale(scale);
}
});
...
guac = new Guacamole.Client(tunnel);
const guacEl = guac.getDisplay().getElement();
rootEl.appendChild(guacEl);
mouse = new Guacamole.Mouse(guacEl);
mouse.onmousedown = mouse.onmouseup = (state) => guac.sendMouseState(state);
//The fix is here
mouse.onmousemove = (state) => {
updateMouseState(state);
};
//Handle mouse coordinates scaling
let updateMouseState = (mouseState) => {
mouseState.y = mouseState.y / scale;
mouseState.x = mouseState.x / scale;
guac.sendMouseState(mouseState);
}
I hope it'll help someone.
A: kban,When drag and drop browserβs right-down corner,gua display zone will left a blank(down or right direction),this seems only executing browserβs guacamole js's scale function,how to solute this problem ?enter image description here | unknown | |
d17970 | test | You simply add the stylers to your map options (as the links in the comments explains) :
var stylers = [{
"stylers": [{
"hue": "#ff0022"
}, {
"saturation": -16
}, {
"lightness": -5
}]
}];
var myOptions = {
...
styles: stylers
};
Here is your code from above in a fiddle using the stylers -> http://jsfiddle.net/cKQxb/ producing this :
A: From the first example in the documentation:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<div style="overflow:hidden;height:500px;width:700px;">
<div id="gmap_canvas" style="height:500px;width:700px;"></div>
<a class="google-map-data" href="http://www.addmap.org" id="get-map-data">google maps</a>
<iframe src="http://www.embed-google-map.com/map-embed.php"></iframe>
<a class="google-map-data" href="http://www.nuckelino.de" id="get-map-data">http://www.nuckelino.de</a></div>
<script type="text/javascript"> function init_map(){
var styles =[
{
"stylers": [
{ "hue": "#ff0022" },
{ "saturation": -16 },
{ "lightness": -5 }
]
}
]
var myOptions = {
zoom:15,
center:new google.maps.LatLng(51.8476894,-1.355176799999981),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"),
myOptions);
map.setOptions({styles: styles});
marker = new google.maps.Marker({
map: map,position: new google.maps.LatLng(51.8476894, -1.355176799999981)});
infowindow = new google.maps.InfoWindow({
content:"<div style='position:relative;line-height:1.34;overflow:hidden;white-space:nowrap;display:block;'><div style='margin-bottom:2px;font-weight:500;'>1 Market Street</div><span>1 Market Street <br> OX4 2JR Woodstock</span></div>"
});
google.maps.event.addListener(marker, "click", function(){
infowindow.open(map,marker);});infowindow.open(map,marker);}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
Or when you create the map:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<div style="overflow:hidden;height:500px;width:700px;">
<div id="gmap_canvas" style="height:500px;width:700px;"></div>
<a class="google-map-data" href="http://www.addmap.org" id="get-map-data">google maps</a>
<iframe src="http://www.embed-google-map.com/map-embed.php"></iframe>
<a class="google-map-data" href="http://www.nuckelino.de" id="get-map-data">http://www.nuckelino.de</a></div>
<script type="text/javascript"> function init_map(){
var styles =[
{
"stylers": [
{ "hue": "#ff0022" },
{ "saturation": -16 },
{ "lightness": -5 }
]
}
]
var myOptions = {
styles: styles,
zoom:15,
center:new google.maps.LatLng(51.8476894,-1.355176799999981),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"),
myOptions);
marker = new google.maps.Marker({
map: map,position: new google.maps.LatLng(51.8476894, -1.355176799999981)});
infowindow = new google.maps.InfoWindow({
content:"<div style='position:relative;line-height:1.34;overflow:hidden;white-space:nowrap;display:block;'><div style='margin-bottom:2px;font-weight:500;'>1 Market Street</div><span>1 Market Street <br> OX4 2JR Woodstock</span></div>"
});
google.maps.event.addListener(marker, "click", function(){
infowindow.open(map,marker);});infowindow.open(map,marker);}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
A: You should put it on Option Object that you contruct your map. Or set this option with map.set("styles", stylesOpts).
Change your code to this:
var myOptions = {
zoom:15,
center:new google.maps.LatLng(51.8476894,-1.355176799999981),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [ // The correct is STYLES not STYLERS
{ hue: "#00ffe6" },
{ saturation: -20 }
]
};
https://developers.google.com/maps/documentation/javascript/reference#MapOptions
A: The accepted answer explains how to implement styles. To generate the styles, there's a very useful styling tool which allows you to visually tweak map settings, which then spits out the JSON you need:
https://mapstyle.withgoogle.com/ | unknown | |
d17971 | test | You're correct, (0,0) is indeed the top left corner of the SVG area (at least before you start transforming the coordinates).
However, your text element <text x="0" y="0">hello</text> is positioned with the leftmost end of its baseline at (0,0), which means the text will appear entirely off the top of the SVG image.
Try this: change your text tag to <text x="0" y="0">goodbye</text>. You should now be able to see the descending parts of the 'g' and 'y' at the top of your SVG.
You can shift your text down by one line if you provide a y coordinate equal to the line height, for example:
<svg width="200" height="100">
<text x="0" y="1em">hello</text>
</svg>
Here's a JSFiddle link for you to play with.
A: To make <text> behave in a more standard way, you can use dominant-baseline: hanging like so:
<text x="0" style="dominant-baseline: hanging;">Hello</text>
You can see examples of different values of this property here. | unknown | |
d17972 | test | Just add your JAR to classpath or build your project with Maven and include dependencies
A: Open the project properties -> Java Build Path -> Order and Export and check item Android Dependencies are checked to be exported to the result APK.
And if .jar exist in Library tab under Android Dependencies item.
If you have .jar in the "libs" folder it should be included by default.
A: Try generating the jar in a different way. Basically jar is a zipped file of all class files with an extension of .jar.
*
*Select all your class files that needs to be included in a jar file.
*Right click and send to compressed (Zip File).
*you will have a zipped file which will contain all the class files.
*Rename this zipped file with having an extension .jar
Now include this jar file into your project whichever you want to use.
Or if you want to zip all the files by a different method then make sure all the files are zipped together without a folder. So when you unzip the files you should get all the files without contained in a folder.
A: It looks similar with this topic. Follow the very clear instructions written by Russ Bateman. | unknown | |
d17973 | test | As @ChrisWagner states in his comment, you shouldn't need to do any of this in iOS8, at least for UIAlertView since there is a new UIAlertViewController that uses closures without any delegates. But from an academic point of view, this pattern is still interesting.
I wouldn't use anonymous class at all. I would just create a class that can be assigned as the delegate and accept closures to execute when something happens.
You could even upgrade this to accept a closure for each kind of action: onDismiss, onCancel, etc. Or you could even make this class spawn the alert view, setting itself as the delegate.
import UIKit
class AlertViewHandler: NSObject, UIAlertViewDelegate {
typealias ButtonCallback = (buttonIndex: Int)->()
var onClick: ButtonCallback?
init(onClick: ButtonCallback?) {
super.init()
self.onClick = onClick
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
onClick?(buttonIndex: buttonIndex)
}
}
class ViewController: UIViewController {
// apparently, UIAlertView does NOT retain it's delegate.
// So we have to keep it around with this instance var
// It'll be nice when all of UIKit is properly Swift-ified :(
var alertHandler: AlertViewHandler?
func doSoemthing() {
alertHandler = AlertViewHandler({ (clickedIndex: Int) in
println("clicked button \(clickedIndex)")
})
let alertView = UIAlertView(
title: "Test",
message: "OK",
delegate: alertHandler!,
cancelButtonTitle: "Cancel"
)
}
}
Passing around closures should alleviate the need for anonymous classes. At least for the most common cases.
A: Unfortunately as far as I understand it, no you cannot effectively create anonymous inner classes. The syntax you suggest would be really nice IMO though.
Here is my attempt at getting something close to what you want, it's no where near as clean though.
import UIKit
class AlertViewDelegate: NSObject, UIAlertViewDelegate {
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, willDismissWithButtonIndex buttonIndex: Int) {
}
func alertViewCancel(alertView: UIAlertView!) {
}
func alertViewShouldEnableFirstOtherButton(alertView: UIAlertView!) -> Bool {
return true
}
}
class ViewController: UIViewController {
var confirmDelegate: AlertViewDelegate?
func doSoemthing() {
confirmDelegate = {
class ConfirmDelegate: AlertViewDelegate {
override func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
println("clicked button \(buttonIndex)")
}
}
return ConfirmDelegate()
}()
let alertView = UIAlertView(title: "Test", message: "OK", delegate: confirmDelegate, cancelButtonTitle: "Cancel")
}
} | unknown | |
d17974 | test | If you're looking to develop on Cloud9, you'll need to make sure you use process.env.IP instead of localhost and process.env.PORT (or port 8080) instead of 3000.
That being said, Cloud9 is not a hosting solution. If you use it as such, your account will be deactivated. Consider something like Heroku for deployment. | unknown | |
d17975 | test | Your implementation indeed removes the M factor, at least if we consider only simple graphs (no multiple edges between two vertices). It is O(N^2)! The complexity would be O(N*M) if you would iterate through all the possible edges instead of vertices.
EDIT: Well, it is actually O(M + N^2) to be more specific. Changing value in some vertex takes O(1) time in your algorithm and it might happen each time you consider an edge, in other words, M times. That's why there is M in the complexity.
Unfortunately, if you want to use simple heap, the complexity is going to be O(M* log M) (or M log N). Why? You are not able to quickly change values in heap. So if dist[v] suddenly decreases, because you've found a new, better path to v, you can't just change it in the heap, because you don't really know it's location. You may put a duplicate of v in your heap, but the size of the heap would be then O(M). Even if you store the location and update it cleverly, you might have O(N) items in the heap, but you still have to update the heap after each change, which takes O(size of heap). You may change the value up to O(M) times, what gives you O(M* log M (or N)) complexity | unknown | |
d17976 | test | I think you have to remove the line:
$rows = mysqli_num_rows($query);
It is in beginning of the script.
Another way is if you modify the first line like this:
$sql = "SELECT * FROM basic WHERE status='active'";
And remove the next 3 rows
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
You have to choice one of above, but not both :) | unknown | |
d17977 | test | productList.get(0).setDrawableId(R.drawable.new_cloth_id); Type any position what you want instead of '0'. And then notify adapter.
A: Please make model(get/set) class of InfoProduct and in onClick of item you'll get the position. On that position you can set drawable to different drawable. | unknown | |
d17978 | test | You can use a so-called array formula to achieve this. As an illustration, I simulated your situation in this image:
The important cell is H1, which contains the index of the offending cell in column E. For the sake of simplicity, I introduced two named ranges items, containing cells E1:E9 and lookup containing cells K2:K10. The formula in H1 is
=MAX(IF(ISBLANK(items),0,IF(ISERROR(MATCH(items,lookup,0)),ROW(INDIRECT("1:"&ROWS(items))),0)))
This is an array formula, which means that you have to confirm with Ctrl-Shift-Enter. If you did that right, the formula will show curly brackets around it -- you do not type those yourself. This formula goes over all cells in the range called items, creates an array with the value 0 for all cells that are blank or that have a match in the range called lookup. For the remaining cells, the value inserted is equal to the row number. Then the maximum is taken over that.
As a result, H1 will contain the index of the last offending item. If all items are OK, then the value 0 is displayed.
Cell G1 shows Error if any offending item has been found, and OK otherwise. The formula is
=IF(H1=0,"OK","Error")
Finally, I1 displays the actual offending item via
=IF(H1>0,INDEX(items,H1),"")
If you do not want to use the named ranges, then replace items with $E$1:$E$9 and lookup with $K$2:$K$10.
If the offending cell is an empty cell, then I1 will contain the value 0.
I think the value in H1 is useful for analysis, but if you do not want it, you can hide it. Or you can fold that formula in the ones used in G1 and I1, but the formulas become pretty complicated.
A workbook containing this answer is uploaded here
As a note on the side: are you aware that you can use Excel's data validation feature with a drop-down list to avoid these kinds of typos you are looking at. That might be useful for you. An example is given in the article Drop-Down Using Data Validation in Microsoft Excel
A: The Easiest way to do this is; to use the filter "Does not contain"
Excel 2010 solution, similar for 2003
*
*Select the whole column
*Select Data
*Select Filter
*Select filter option (triangle at top of column)
*Select text filters
*Select Does not contain
*Enter type
*Modify and rerun as needed. | unknown | |
d17979 | test | As explain in "Git & Working on multiple branches", the two practical solutions when applying commits to multiple branches (which is what you would do with your "feature branches" option) are:
*
*merge (which should allow you to keep reusing that feature branch, as it would keep track of what has already been merge to a specific banch): a rebase --interactive might be in order for you to re-order the commits, putting first the ones you want to merge, and then the ones you are nnot ready yet to merge.
*cherry-picking (and it now supports a range of commits), but I always have been wary of cherry-picking. | unknown | |
d17980 | test | add some js to your page
document.addEventListener('DOMContentLoaded', ()=>{document.body.scrollIntoView()}); | unknown | |
d17981 | test | Just use a more precise regular expression:
SELECT REGEXP_SUBSTR(STR, 'Date-([0-9]{2}-[0-9]{2}-[0-9]{4})', 1, 1, 'i', 1)
FROM x;
Or for less accuracy but more conciseness:
SELECT REGEXP_SUBSTR(STR, 'Date-([-0-9]{10})', 1, 1, 'i', 1)
A: You are zero-padding the date values so each term has a fixed length and have a fixed prefix so you do not need to use (slow) regular expressions and can just use simple string functions:
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY')
FROM table_name;
(Note: if you still want it as a string, rather than as a date, then just use SUBSTR without wrapping it in TO_DATE.)
For example:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Outputs:
DATE_VALUE
08-JAN-21
db<>fiddle here
If the Date- prefix is not going to always be at the start then use INSTR to find it:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'Trans-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, INSTR(value, 'Date-') + 5, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Which outputs:
DATE_VALUE
08-JAN-21
08-FEB-21
If you can have multiple Date- substrings and you want to find the one that is either at the start of the string or has a - prefix then you may need regular expressions:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'TransDate-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(
REGEXP_SUBSTR(value, '(^|-)Date-(\d\d-\d\d-\d{4})([-.]|$)', 1, 1, 'i', 2),
'DD-MM-YYYY'
) AS date_value
FROM table_name;
db<>fiddle here | unknown | |
d17982 | test | It's pretty big hacking. gwt-dnd handles mouse events by MouseDragHandler class and it's tightly coupled with AbstractDragController, so you must provide your own implementation of this handler (just extend it) which will call onMouseDown and onMouseUp methods on your click events. But you must also override AbstractDragController, so you end up rewriting half of the library. | unknown | |
d17983 | test | Found the problem:
The root layout for the items had layout_height = match_parent, setting it to layout_height = ?listPreferredItemHeight solved it all. | unknown | |
d17984 | test | The answer to my question appears to be that there is no problem; Threading Building Blocks can work fine in this scenario. Eliminating the parallel_reduce didn't change the behavior, and further investigation shows that the problem was confined to the managed code; didn't have anything to do with TBB at all. | unknown | |
d17985 | test | You can directly use the bitwise or and xor commands.
or_result = bitmap1 | bitmap2
xor_result = bitmap1 ^ bitmap2
If this will not work because of how you've defined your bitmap1 and bitmap2 (which is unclear, is it a struct or an int or a char or something less useful like an array or something strange like a class with an operator[] defined? We need more information) then you'll probably have to change how you're storing your data. | unknown | |
d17986 | test | Try looking into CSS and media queries, seems like it would be a neater solution than trying to do this with JS.
A: You would use something like this:
function resizeFn() {
var width = window.width();
// ...
}
$(function() {
$(window).resize(resizeFn).trigger('resize');
});
Not possible to do an inverse with CSS, I don't think (I thought maybe through calc(), but I don't think it lets you do unit manipulations like that).
Fair warning, this doesn't sound like a good design unless you're trying to make it look nuts. | unknown | |
d17987 | test | Twilio developer evangelist here.
First up, you have nothing to worry about here. As you say, you are receiving the callbacks and doing what you need to. You probably want to stop the debugger icon flashing at you in your Twilio console though.
From what I can see, this is a small oversight in the case of the Node.js example that you linked to.
Just calling res.end() closes the stream. It appears that if nothing else has been set, this means the response will get a status code of 200 and no body. While Twilio doesn't expect a response to callbacks like this, it seems it still wants to know something happened.
The error message says that the response didn't have a content type. You can remedy this by setting a content type on the response by calling res.set('Content-Type', 'text/plain') before you call res.end() and that seems to please the Twilio HTTP client.
Alternatively, you can use the express response method sendStatus to set the status and content type of the response in one call. Just call res.sendStatus(200) and the response will be set to text/plain, the status will be 200 and there will be a body of "OK". The Twilio HTTP client will happily accept all of that.
I recommend you change your calls to res.end() to res.sendStatus(200) and I'm going to go fix that in the Node.js example too.
A: You should respond with HTTP status code 204:
res.status(204).end();
The 204 status is still a success, like 200, but specifically means you are not sending any content back (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
Note that the following also works, and doesn't need the end():
res.sendStatus(204); | unknown | |
d17988 | test | I would like to clarify that there is no way for the form recipient ([email protected]) to receive the contact form from the value of the email field (user entered). It will always be sent by the authenticated email in my settings.py, which at this point is my personal email?
You're setting the sender of the email to sender but using EMAIL_HOST, correct? If this is the case, be careful that your SMTP account will let you send email from users other than your domain. Normally, providing you have an authenticated account on that server, you'll be able to set the From: field to whatever you like.
So in short, this email will hit your inbox appearing to be from the sender variable. So when you hit reply, you'll be able to email them back, which is I think what you want. However, it will be sent using the SMTP server whose authentication details you provide. There is a disconnect between being able to send email (SMTP) and being able to receive it, which I think has got you confused.
I've never tried it, but to add extra headers I believe you need to use the EmailMessage object. According to the docs, you would:
e = EmailMessage(headers={'Reply-To':...
e.send()
Be careful doing this; specifically, be careful to strip out newlines in the reply to field. I do not know if the default clean methods would do this.
Finally, there isn't much wrong with your django/python at all. The only thing I'd say, by way of awareness, is not to use this:
return redirect('/thanks/')
but instead:
return HttpResponseRedirect(reverse('myapp.views.method',args=tuple,kwargs=dict))
This gives you the ability to not hardcode urls into your application. The reverse method will look them up from urls.py for you, so you can move your application around/change urls and it will still work.
A: Here is signature of send_mail from django documentation:
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None)
As you can see it does not have headers argument.
You will need to use EmailMessage object directly.
It would also be nice to remove email-formatting from view. I would write everything something more like this:
from django.core.mail.message import EmailMessage
from django.conf import settings
class ContactsEmailMessage(EmailMessage):
def __init__(self, sender, subject, message, cc_myself):
super(ContactEmailMessage, self).__init__(
subject=subject,
body=self._get_message(self, sender, message),
from=settings.DEFAULT_FROM_EMAIL,
to=settings.CONTACT_RECIPIENTS,
headers=self._get_headers(sender),
cc=(sender, ) if cc_myself else None
)
def _format_message(self, sender, message):
return "%s\n\n%s" % (sender, message)
def _get_headers(self, sender):
return {
'reply-to': sender
}
Now you can write clean and easy to read view:
from myproject.mail.message import ContactsEmailMessage, BadHeaderError
from django.core.exceptions import SuspiciousOperation
def contact(request):
...
form = ContactForm(request.POST or None)
if form.is_valid(): # All validation rules pass
try:
message = ContactsEmailMessage(**form.cleaned_data)
message.send()
except BadHeaderError:
# django will raise this error if user will try to pass suspicious new-line
# characters to "sender" or other fields. This is safe-guard from
# header injections
raise SuspiciousOperation()
return redirect('/thanks/')
... | unknown | |
d17989 | test | Note that this idiom exists in other programming languages as well. C didn't have an intrinsic bool type, so all booleans were typed as int instead, with canonical values of 0 or 1. Takes this example (parentheses added for clarity):
!(1234) == 0
!(0) == 1
!(!(1234)) == 1
The "not-not" syntax converts any non-zero integer to 1, the canonical boolean true value.
In general, though, I find it much better to put in a reasonable comparison than to use this uncommon idiom:
int x = 1234;
if (!!x); // wtf mate
if (x != 0); // obvious
A: It returns true if the object on the right is not nil and not false, false if it is nil or false
def logged_in?
!!@current_user
end
A: It's useful if you need to do an exclusive or. Copying from Matt Van Horn's answer with slight modifications:
1 ^ true
TypeError: can't convert true into Integer
!!1 ^ !!true
=> false
I used it to ensure two variables were either both nil, or both not nil.
raise "Inconsistency" if !!a ^ !!b
A: It is "double-negative", but the practice is being discouraged. If you're using rubocop, you'll see it complain on such code with a Style/DoubleNegation violation.
The rationale states:
As this is both cryptic and usually redundant, it should be avoided
[then paraphrasing:] Change !!something to !something.nil?
A: Not not.
It's used to convert a value to a boolean:
!!nil #=> false
!!"abc" #=> true
!!false #=> false
It's usually not necessary to use though since the only false values to Ruby are nil and false, so it's usually best to let that convention stand.
Think of it as
!(!some_val)
One thing that is it used for legitimately is preventing a huge chunk of data from being returned. For example you probably don't want to return 3MB of image data in your has_image? method, or you may not want to return your entire user object in the logged_in? method. Using !! converts these objects to a simple true/false.
A: ! means negate boolean state, two !s is nothing special, other than a double negation.
!true == false
# => true
It is commonly used to force a method to return a boolean. It will detect any kind of truthiness, such as string, integers and what not, and turn it into a boolean.
!"wtf"
# => false
!!"wtf"
# => true
A more real use case:
def title
"I return a string."
end
def title_exists?
!!title
end
This is useful when you want to make sure that a boolean is returned. IMHO it's kind of pointless, though, seeing that both if 'some string' and if true is the exact same flow, but some people find it useful to explicitly return a boolean.
A: Understanding how it works can be useful if you need to convert, say, an enumeration into a boolean. I have code that does exactly that, using the classy_enum gem:
class LinkStatus < ClassyEnum::Base
def !
return true
end
end
class LinkStatus::No < LinkStatus
end
class LinkStatus::Claimed < LinkStatus
def !
return false
end
end
class LinkStatus::Confirmed < LinkStatus
def !
return false
end
end
class LinkStatus::Denied < LinkStatus
end
Then in service code I have, for example:
raise Application::Error unless !!object.link_status # => raises exception for "No" and "Denied" states.
Effectively the bangbang operator has become what I might otherwise have written as a method called to_bool.
A: Other answers have discussed what !! does and whether it is good practice or not.
However, none of the answers give the "standard Ruby way" of casting a value into a boolean.
true & variable
TrueClass, the class of the Ruby value true, implements a method &, which is documented as follows:
Returns false if obj is nil or false, true otherwise.
Why use a dirty double-negation when the standard library has you covered? | unknown | |
d17990 | test | I agree on the fact that it isn't very clear where to store these classes in Laravel 4.
A simple solution would be creating repositories/services folders in your main app/ folder and updating your main composer.json file to have them autoloaded:
{
"require": {
"laravel/framework": "4.0.*"
},
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/tests/TestCase.php",
"app/repositories",
"app/services"
]
},
"minimum-stability": "dev"
}
Note: everytime you create a new class you have to run composer dump-autoload.
In case of repositories, you can have Laravel inject them into your controllers automatically. I find this a good screencast on this subject.
A: I found this collection of tutorials to be a great introduction on the proper place to store your custom service providers and other files that you want to inject into your project:
*
*http://fideloper.com/laravel-4-application-setup-app-library-autoloading
*http://fideloper.com/laravel-4-where-to-put-bindings
*http://fideloper.com/error-handling-with-content-negotiation
These tutorials come from this collection:
http://fideloper.com/tag/laravel-4
A: The first thing that I do when I get a fresh install of Laravel is:
*
*Remove the "models" folder
*Create a src folder
*Under the src, create a Application folder (or the name of the app)
*On Application folder, create Entities, Repositories, Services and Tests
So, in this case your namespace will be Application\Entities, Application\Repositories and Application\Services
In composer.json:
{
"require": {
"laravel/framework": "4.0.*"
},
"autoload": {
"psr-0": {
"Application": "app/src/"
},
"classmap": [
"app/commands",
"app/controllers",
"app/database/migrations",
]
},
"minimum-stability": "dev"
}
To each one of those you'll need to create the classes and a service provider to bind a repository to an entity.
Here is a tutorial explaining how to create the repositories:
http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/
Anyway, I'm still looking for the best architecture. If anyone has a better idea, I'll be glad to hear it! | unknown | |
d17991 | test | The content of a RichTextBox is not HTML, so an incompatible clipboard format may be part of the issue. If you are happy with the text only, try assigning the plain text to the clipboard:
Clipboard.SetText(RichTextBox1.Text);
If you want formatted text, you will need to convert the RTF to HTML. This article may help: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
A: Because your page html is null,try this example
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<html><body></body></html>";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Body.InnerText = richTextBox1.Text;
}
} | unknown | |
d17992 | test | In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from ( (select 'abc' as x, '' as y)
union all (select 'def' as x, 'ghi' as y)
union all (select '' as x, 'jkl' as y)
union all (select null as x, 'mno' as y)
union all (select 'pqr' as x, null as y)
) q
gives:
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
A: case when field1>0 then field2/field1 else 0 end as field3
A: As stated in PostgreSQL docs here:
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.
Code snippet specifically answering your question:
SELECT field1, field2,
CASE
WHEN field1>0 THEN field2/field1
ELSE 0
END
AS field3
FROM test | unknown | |
d17993 | test | You don't use this at all:
config.AddPSSnapIn("your snapin here", out psEx);
instead.... just use a connection as follows:
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://yourdomainhere/Powershell/Microsoft.Exchange"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", PsCreds);
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
Now run your commands and you're good to go.
Quick notes:
*
*Make sure you're app is targeting x64 not Any CPU or x86
*If you're using .net 4.5 (or 4) make sure you're app pools are set properly (v4.0 not v2.0) and that you have Enable 32bit apps set to false | unknown | |
d17994 | test | You should checkout chgems. chgems is like chroot for RubyGems. chgems can spawn a sub-shell or run a command with PATH, GEM_HOME, GEM_PATH set to install gems into $directory/.gem/$ruby/$version/.
$ chgems $directory gem install $user_gem
$ chgems $directory $user_command | unknown | |
d17995 | test | If you are using Open Directory (which you probably should with that amount of users) one option is to use dscl which is probably a little easier to automate. There's a thread at Apple Discussions describing how to add users to a group.
A: Workgroup Manager (part of the Server Admin Tools package) can import tab-delimited text files with a little work. When you do the import, you'll need to tell it the file's format -- what the record and field delimiters are (generally newline and tab), then what data each field contains. See this video for an example of the process.
If you need to set attributes that aren't in the file, you can either select all of the imported accounts and set the attribute for all of them at once (the video shows doing this for the home directory location), or (if you think of it before doing the import) create a template account with the relevant settings, save it as a preset (there's a pop-up menu at the bottom of WGM's window), then select that preset in the import dialog box.
A: Try using Passenger http://macinmind.com/?area=app&app=passenger&pg=info
If you have more than 20 users you might want to buy it for $60 or do what I do and group them by 20 users and run it 5 times. | unknown | |
d17996 | test | I am guessing that I am missing out on some event or registration.
I don't think you are.
The a lost focus event would be too soon since it happens before the page changes.
The Child Control's VisibleChanged event only fires when the parent TabPage is shown and not when it is hidden which is not what you want.
You can handle either the TabPage.VisibleChanged or the TabControl.SelectedIndexChanged. This of course is from the Parent not the Child, which is also not what you want.
Incidently I believe the TCM_SETCURSEL message is sent to the control on tab change (again not helping with the "not in the Parent requriement" | unknown | |
d17997 | test | Finally the job worked in both Client and Cluster mode
Cluster Mode via Spark Submit
./spark-submit \
--master k8s://https://xxxx:6443 \
--deploy-mode cluster \
--name prateek-ceph-pyspark \
--conf spark.kubernetes.namespace=jupyter \
--conf spark.executor.instances=1 \
--conf spark.executor.cores=3 \
--conf spark.executor.memory=55g \
--conf spark.kubernetes.container.image=spark-executor-3.0.1 \
--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \
--conf spark.kubernetes.authenticate.executor.serviceAccountName=spark \
--conf spark.kubernetes.container.image.pullPolicy=Always \
--conf spark.kubernetes.container.image.pullSecrets=gcr \
--conf spark.kubernetes.authenticate.submission.caCertFile=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
--conf spark.kubernetes.authenticate.submission.oauthTokenFile=/var/run/secrets/kubernetes.io/serviceaccount/token \
--conf spark.hadoop.fs.s3a.access.key=<ACCESS_KEY> \
--conf spark.hadoop.fs.s3a.secret.key=<SECRET_KEY> \
--conf spark.hadoop.fs.s3a.aws.credentials.provider=org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider \
--conf spark.hadoop.fs.s3a.endpoint=http://xxxx:8080 \
--conf spark.hadoop.fs.s3a.connection.ssl.enabled=false \
--conf spark.hadoop.fs.s3a.path.style.access=true \
--conf spark.eventLog.enabled=false \
s3a://ceph-bucket/scripts/Ceph_PySpark.py
Client Mode in Jupyter Notebook -
Spark Config with AWS Credential Provider - org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("prateek-pyspark-ceph") \
.config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \
.config("spark.kubernetes.namespace", "jupyter") \
.config("spark.kubernetes.container.image", "spark-executor-3.0.1") \
.config("spark.kubernetes.container.image.pullPolicy" ,"Always") \
.config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \
.config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \
.config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \
.config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \
.config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \
.config("spark.hadoop.fs.s3a.access.key", "xxxxx") \
.config("spark.hadoop.fs.s3a.secret.key", "xxxxx") \
.config("spark.hadoop.fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider") \
.config("spark.hadoop.fs.s3a.endpoint", "{βββββββ}βββββββ:{βββββββ}βββββββ".format("http://xxxx", "8080")) \
.config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
.config("spark.hadoop.fs.s3a.path.style.access", "true") \
.config("spark.executor.instances", "2") \
.config("spark.executor.cores", "6") \
.config("spark.executor.memory", "55g") \
.getOrCreate()
Spark Config with AWS Credential Provider - com.amazonaws.auth.EnvironmentVariableCredentialsProvider
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("prateek-pyspark-ceph") \
.config("spark.kubernetes.driver.master", "k8s://https://xxxx:6443") \
.config("spark.kubernetes.namespace", "jupyter") \
.config("spark.kubernetes.container.image", "spark-executor-3.0.1") \
.config("spark.kubernetes.container.image.pullPolicy" ,"Always") \
.config("spark.kubernetes.container.image.pullSecrets" ,"gcr") \
.config("spark.kubernetes.authenticate.driver.serviceAccountName", "spark") \
.config("spark.kubernetes.authenticate.executor.serviceAccountName", "spark") \
.config("spark.kubernetes.authenticate.submission.caCertFile", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") \
.config("spark.kubernetes.authenticate.submission.oauthTokenFile", "/var/run/secrets/kubernetes.io/serviceaccount/token") \
.config("spark.hadoop.fs.s3a.aws.credentials.provider", "com.amazonaws.auth.EnvironmentVariableCredentialsProvider") \
.config("spark.hadoop.fs.s3a.endpoint", "{βββββββ}βββββββ:{βββββββ}βββββββ".format("http://xxxx", "8080")) \
.config("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
.config("spark.hadoop.fs.s3a.path.style.access", "true") \
.config("spark.executor.instances", "2") \
.config("spark.executor.cores", "6") \
.config("spark.executor.memory", "55g") \
.getOrCreate()
To solve the issue in Writing to Ceph in Client Mode, add all properties related to fs.s3a.committer.staging.* mentioned here - https://hadoop.apache.org/docs/current/hadoop-aws/tools/hadoop-aws/committers.html in your core-site.xml file in both Driver and Executor image | unknown | |
d17998 | test | I am able to print the strings in seperate line by using '\n'. I am adding demo below. Can you please update that as per the issue you are facing so that we can look into that.
Demo :
const answer = {
questions: [{
questionId: 1,
answers: ['answer1', 'answer2', 'answer3']
}]
};
const employmentAnswerMap = [
{
answerKVs: [{
id: 1,
text: 'healthNeed1'
}, {
id: 2,
text: 'healthNeed2'
}, {
id: 3,
text: 'healthNeed3'
}]
}
];
const result = [];
for (let l=0; l<answer.questions.length; l++) {
var questionMap = [answer.questions[l].questionId, answer.questions[l].answers];
let resultElem = '';
for (let m =0; m < employmentAnswerMap[l].answerKVs.length; m++){
if (questionMap[1].find((elem) => elem.includes(employmentAnswerMap[l].answerKVs[m].id)).length > 0) {
resultElem = resultElem + employmentAnswerMap[l].answerKVs[m].text + ' ' + '\n';
}
}
result.push(resultElem);
}
console.log(result[0]);
A: HTML doesn't really like to add line breaks, even if you include them. If you have to include them, template literals are the easiest way. To use those, use backticks(`) instead of single(') or double quotes("). Template Literals take literally what you type as the string, and can only be escaped at the end of the string, or by encapsulating your escaped javascript with ${}. It looks like this:
let bob=true;
`Look at me,
I'm using backticks! ${bob ? "No literals here!" : "But you
can use the 'ternary operator'!"}`
Unfortunately, it doesn't look like the code sample likes backticks. But I assure you, they work! Of course, even with the return inside the template literals, HTML is going to mostly ignore them unless you use the new CSS white-space property. You could also add append a new <p> tag for each one, which can be styled however you like, including to make them have a new line.
A: I had to wrap my HTML around this div in order for the newlines ("/n") to display properly
<div style={{whiteSpace: "pre-wrap"}}> | unknown | |
d17999 | test | A NullPointerException is a rather trivial exception and has actually nothing to do with JSP/Servlets, but with basic Java in general (look, it's an exception of java.lang package, not of javax.servlet package). It just means that some object is null while your code is trying to access/invoke it using the period . operator.
Something like:
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!
The 1st line of the stacktrace tells you in detail all about the class name, method name and line number where it occurred.
Fixing it is relatively easy. Just make sure that it's not null or bypass the access altogether. You should rather concentrate on why it is null and/or why your code is trying to deal with null. | unknown | |
d18000 | test | You should use
// Parses the string argument as a signed decimal integer
Integer.parseInt(intObject.toString());
instead of
// Determines the integer value of the system property with the specified name.
// (Hint: Not what you want)
Integer.getInteger(...) | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.