id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23533400
|
library(readxl)
library(tidyverse)
rm(list = ls())
DK1 <- read_excel("DK1.xlsx")
time_index <- as.POSIXct(DK1$Datetime, format="%Y/%m/%d %H:%M:%S", tz=Sys.timezone())
test <- xts(DK1[,-1], order.by = time_index)
This is just one of many ways I've tried to index it in XTS to no avail. The index row looks wrong and I do not know what to do.
UPDATE 1: dput(head(DK1))
A: It appears that read_excel is converting your time column into a datetime, but with all the dates set to "1899-12-31". This can be seen by running:
> str(DK1)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 8760 obs. of 6 variables:
$ Date : POSIXct, format: "2019-01-01" "2019-01-01" "2019-01-01" "2019-01-01"...
$ Hours : POSIXct, format: "1899-12-31 00:00:00" "1899-12-31 01:00:00" "1899-12-31 02:00:00" "1899-12-31 03:00:00" ...
$ Datetime : chr "2019-01-01 00:00:00" "2019-01-01 01:00:00" "2019-01-01 02:00:00" "2019-01-01 03:00:00" ...
$ DK1 : num 211.5 75.2 -30.5 -74 -55.3 ...
This is more of a data import problem and the Datetime concat in excel can be performed in R. Generally it's simpler to have all data manipulation performed in a single spot.
library(readxl)
library(xts)
DK1 <- read_excel("DK1.xlsx")
# pasting date and time together in new column name for comparison
# note the use of strftime to remove the date information discussed earlier
DK1$Datetime2 <- paste(DK1$Date, strftime(DK1$Hours, "%H:%M:%S", tz = "UTC"))
# the format / in excel need to change to - for how it's displayed in R
DK1$time_index <- as.POSIXct(DK1$Datetime, format = "%Y-%m-%d %H:%M:%S", tz = Sys.timezone())
# filtering out the NA value of 2019-03-10 02:00:00 which is when daylight savings occurred
DK1 <- DK1[!is.na(DK1$time_index), ]
DK1a <- xts(DK1[, "DK1"], order.by = DK1$time_index)
> head(DK1a)
DK1
2019-01-01 00:00:00 211.48
2019-01-01 01:00:00 75.20
2019-01-01 02:00:00 -30.47
2019-01-01 03:00:00 -74.00
2019-01-01 04:00:00 -55.33
2019-01-01 05:00:00 -93.72
A: We can select the numeric column and then order.by the 'Date' which is already a Datetime class
library(xts)
xts(DK1$DK1, order.by = DK1$Date)
as the format is in the default format, we don't have to specify the format
| |
doc_23533401
|
When I click the addbtn, and the textInput boxes create, the values in the txtInput box needs to clear so that I can add more textInput boxes.
This is the code:
ui:
ibrary(shiny)
shinyUI(
# Use a fluid Bootstrap layout
fluidPage(
# Generate a row with a sidebar
sidebarLayout(
# Define the sidebar with one input
sidebarPanel(
sliderInput("capacity", "Current Capacity:",
min=0, max=100, value=10),
c(list(
textInput("service", "Application Component Name", ""),
actionButton("addbtn", "Add Component"))),
#lapply(seq(10), function(i) uiOutput(paste0("ui", i)))
br(),
br(),
br(),
br(),
br(),
actionButton("calcbtn", "Calculate Projection")
),
# Create a spot for the barplot
mainPanel(
textInput("inputWork","Volume", width="200px"),
textInput("inputGrowth","Growth Rate", width="100px"),
lapply(seq(10), function(i) uiOutput(paste0("ui", i)))
#tags$p("Web"),
#verbatimTextOutput("input_type_text")
)
)
)
)
server <- function(input, output)
{
observeEvent(input$addbtn, {
n <- isolate(input$addbtn)
if (n == 0) return()
# create n-th pair of text input and output
output[[paste0("ui", n)]] <- renderUI(
list(textInput(paste0("textin", n), isolate(input$service)),
textOutput(paste0("textout", n))))
updateTextInput(input$service, "Application Component Name", value="")
})
}
with this code, I am getting these errors:
Warning: Error in $: $ operator is invalid for atomic vectors
Stack trace (innermost first):
64: updateTextInput
63: observeEventHandler [C:\shiny\bcl/server.R#11]
1: shiny::runApp
ERROR: [on_request_read] connection reset by peer
A: All your problem in updateTextInput
in help
Arguments
session The session object passed to function given to shinyServer.
inputId The id of the input object.
label The label to set for the input object.
value The value to set for the input object.
so your need server like :
shinyServer(function(input, output,session) {
observeEvent(input$addbtn, {
n <- isolate(input$addbtn)
if (n == 0) return()
# create n-th pair of text input and output
output[[paste0("ui", n)]] <- renderUI(
list(textInput(paste0("textin", n), isolate(input$service)),
textOutput(paste0("textout", n))))
updateTextInput(session,"service", "Application Component Name", value="")
})
})
If your dont want to change label of textInput you can drop it in update :
updateTextInput(session,"service", value="")
| |
doc_23533402
|
For eg: sbit a = P0 ^ 0;
But when I set a = 1, then I get the pin in a gray color in proteus where I run the program on simulated hardware. For high, the pin should be red. I'm trying to interface the LM041L LCD. Please help. I'm very new to this and I don't understand what is casing this
A: The 8 pins on P0 are in open drain mode by default. When you use these 8 pins as outputs, you should imply a pull up resistor in order to output a high signal.
| |
doc_23533403
|
HTML
<section class="st" id="item1">
Item 1<p>
<a id="prevItem" href="#">Previous Item</a>
<a id="nextItem" href="#">Next Item</a>
</section>
<section class="st" id="item2">
Item 2
<p>
<a id="prevItem" href="#">Previous Item</a>
<a id="nextItem" href="#">Next Item</a>
</section>
JS
$("#item2").hide()
$("#nextItem").click(function(){
if($('#item1').is(':visible')) {
$("#item1").hide();
$("#item2").show();
}
else if($('#item2').is(':visible')) {
$("#item1").show();
$("#item2").hide();
}
});
Jsfiddle here: http://jsfiddle.net/by0bze5e/
A: You can't have two elements with the same id and expect it to work. Change them to classes and it will most likely work fine.
<a class="prevItem" href="#">Previous Item</a>
<a class="nextItem" href="#">Next Item</a>
$("#item2").hide()
$(".nextItem").click(function(){
$("#item1, #item2").toggle();
});
http://jsfiddle.net/by0bze5e/2/
A: You must have unique IDs on a HTML page for it to be valid. Use classes instead to match the buttons:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/by0bze5e/4/
$("#item2").hide()
$(".prevItem").click(function(){
if($('#item1').is(':visible')) {
$("#item1").hide();
$("#item2").show();
}
else if($('#item2').is(':visible')) {
$("#item1").show();
$("#item2").hide();
}
});
| |
doc_23533404
|
My structure will be as follows:
www.domaina.com/query(folder)/?123,456,789
To redirect to
www.domainb.com/query(folder)/?123,456,789
But I wish to keep the URL in the address bar reading as domaina.com not domainb.com.
The sites are on different servers and htacces rules will differ from site to site (some may be static sites in the root and some maybe wordpress etc) and will sometimes be on different servers.
Thanks
A: Look into iFrames instead of doing this with htaccess code.
Edit|Update: Use iframes and not frameset. frameset is not supported in HTML5. See this w3schools tutorial page. Adding an iframe is very simple so keep everything very simple - http://www.w3schools.com/tags/tag_iframe.asp
A: <frameset rows="100%">
<frameset cols="100%">
<frame src="http://www.domain.com/page-i-want-to-display" frameborder="0" scrolling="yes">
</frameset>
</frameset>
| |
doc_23533405
|
I noticed that a Property (say MyProp) in my program is being invoked continuously by the main thread. In spite of a breakpoint is inserted at its get accessor scope, the code isn't broken at that point! (Why?)
So I couldn't check the call stack to find out which part of my code is invoking that property on and on. I tried to chack the stack trace manually as follows:
public static MyType MyProp {
get {
string threadName = Thread.CurrentThread.Name;
string MTID = Thread.CurrentThread.ManagedThreadId;
Debug.WriteLine("» MyProp");
Debug.Indent();
Debug.WriteLine("Current Thread : MTID = " + MTID + ", Name = " + threadName);
StackTrace stack = new StackTrace();
Debug.WriteLine("Frame Count : " + stack.FrameCount);
for (int index = 0; index < stack.FrameCount; index++)
{
StackFrame frame = st.GetFrame(index);
string methodName = frame.GetMethod().Name;
Debug.WriteLine(string.Format("Frame [{0}]: Method = '{1}'", index + 1, methodName));
}
Debug.Unindent();
// Rest of code..
}
}
Also, I searched the MyProp symbol in entire solution and then used the System.Diagnostics.Debug.WriteLine method wherever this property is invoked, but none of them is written at the Output window!! (How could this be possible?)
By pressing F11 key, (i.e. to start my prog from the very beginning point) and right after required dll-s were loaded, I see the following lines in the Output window:
'MyProg.vshost.exe' (Managed): Loaded 'C:\Windows\assembly\GAC_MSIL\System....dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
:
'MyProg.vshost.exe' (Managed): Loaded 'D:\...\My Prog\bin\Debug\MyProg.exe', Symbols loaded.
'MyProg.vshost.exe' (Managed): Loaded 'D:\...\My Prog\bin\Debug\part1.dll', Symbols loaded.
:
'MyProg.vshost.exe' (Managed): Loaded 'D:\...\My Prog\bin\Debug\partn.dll', Symbols loaded.
» MyProp
Current Thread : MTID = '9', Name = '' // <- Main thread
Frame Count : 6
Frame [1]: Method = 'get_MyProp' // <- How???
Frame [2]: Method = 'Main'
Frame [3]: Method = '_nExecuteAssembly'
Frame [4]: Method = 'RunUsersAssembly'
Frame [5]: Method = 'Run'
Frame [6]: Method = 'ThreadStart'
The annoying thing is that every once I go one step ahead (By pressing F10 or F11 key), I see the » MyProp log section again!!!
What could be causeing this and how can I treat this issue? _Thanks
A: It's really hard to tell what could cause your property to be accessed multiple times without more code.
For now, I would recommend adding
System.Diagnostics.Debugger.Break();
in your getter, which will break your program in the debugger when executed. Then look at the stack trace.
A: How to get all callers?
If you have ReSharper you can get all call stacks without debugging by placing cursor on your property and pressing Ctrl+Shift+Alt+A and selecting Incoming Calls. (See http://www.jetbrains.com/resharper/webhelp/Code_Analysis__Call_Tracking.html).
Here is an example of Inspection Results view:
Or just use Visual Studio built-in feature: Call Hierarchy. Right-click member and select View Call Hierarchy. Example view:
How to set break point within properties?
Update1: I can debug into properties on my machine (VS2010). My debugging options are:
and
| |
doc_23533406
|
i was wondering if there is a way that i can convert the UITableViewCell to be right-to-left.
I want everything to be in the opposite direction.
Any thoughts?
A: Hmm.. It's really interesting) I have no solution, but few suggestions. First of all, you can try to use CGAffineTransformInvert to mirror your table. If it wil be useless, you can customize your tableView cells(make an UIImageView at the left side and UILabel with UITextAlignmentRight at the right). This is about your table. If you want to go to another view, you can just change your table view with UIViewAnimationTransitionFlipFromLeft animation instead of using UINavigationController. It's not a pretty solution, but it may do the trick) Good luck)
A: Creating your own UITableViewCell subclass is not that hard to do and is probably the first thing you'll want to do to get a custom look. All you'll need is a custom XIB file and a bit of modified code in your cellForRowAtIndexPath function:
NSString *CellIdentifier = @"IndividualContractWithResult";
UITableViewCell *cell;
...
cell = [thisTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// TODO: improve code by avoiding the view controller creation
UIViewController *vc = [[UIViewController alloc] initWithNibName:@"IndividualContractWithResult" bundle:nil];
cell = (IndividualContractWithResult_Cell *) vc.view;
[vc release];
}
| |
doc_23533407
|
I can't see any database entries being displayed at all. Here is my code:
Entity:
class Comment(db.Model):
name = db.StringProperty(required=True)
comment = db.TextProperty(required=True)
created = time.strftime("%d/%m/%Y")
Main Handler:
class MainPage(Handler):
def render_front(self, name="", comment="", error=""):
comments = db.GqlQuery("SELECT * FROM Comment ORDER BY created DESC")
self.render("front.html", name=name, comment=comment, error=error, comments=comments)
def get(self):
self.render_front()
def post(self):
name = self.request.get("name")
comment = self.request.get("comment")
if name and comment:
c = Comment(name=name, comment=comment)
c.put()
time.sleep(0.5)
self.redirect("/")
So this will be displayed in the HTML:
{% for e in comments %}
<div class="comment">
<div class="comment-name">
{{e.name}}
</div>
<pre class="comment-content">
{{e.comment}}
<br>
on {{e.created}}
</pre>
</div>
{% endfor %}
The problem is that the program seems to completely ignore the above for block. I managed to make it work for a while but I checked it many times and can't see where the problem is.
Any help will be appreciated. Thanks in advance.
A: A few ways to check through this:
*
*Use the admin console to look at your Datastore. Do you have records in there?
*Are your datetime properties being stored correctly? For docs on DS and Datetime, see here: https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#DateTimeProperty
*Have you made the date a 'dateTimeProperty' type? See the example here: developers.google.com/appengine/docs/python/ndb/queries See also here: stackoverflow.com/questions/9700579/gql-select-by-date
*Try removing the ORDER BY clause in your GQL. I'm wondering if there's something funky with the date/time variable
*Try running locally using the App Engine SDK, and use the logs in that to see the behavior. When you're happy that everything works you can upload it to GAE.
*Don't use the templating engine -- for now just do the loop completely in Python -- and self.response.write stuff out. This will tell you if your query works properly.
Hope it works out for you! :)
| |
doc_23533408
|
def generator():
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# some data prep
...
while 1:
for i in range(1875): # 1875 * 32 = 60000 -> # of training samples
yield X_train[i*32:(i+1)*32], y_train[i*32:(i+1)*32]
If I pass this into the fit_generator() method or just pass all the data directly into the fit() method and define a batch_size of 32, would it make any difference regarding (GPU?)-memory whatsoever?
A: Yes the difference actually comes in when you need augmented data for better model accuracy.
For efficiency it allows realtime data augmentation on images with CPU. That means it can use the GPU for your model training and it updates, while delegating to the CPU the load of augmenting images and providing the batches to train.
| |
doc_23533409
|
String host = "jdbc:derby:PlayerScores";
String uName = "user1";
String uPass = "pass123";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver);
Connection conn = DriverManager.getConnection(host, uName, uPass);
When I test the application and try save the data, the following message comes up:
java.sql.SQLException: Database 'PlayerScores' not found
I have checked my libraries and already have the derby.jarand the derbyclient.jarfiles in place.
I have checked my database name and it is correct.
How can I try correct this problem?
A: Try to define an absolute path for your database... Example:
String host = "jdbc:derby:/my/database/path/PlayerScores;create=true";
See this link for more examples...
| |
doc_23533410
|
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
<source>
@type http
port 8888
bind 0.0.0.0
body_size_limit 32m
keepalive_timeout 10s
</source>
<match **>
type file
path /var/log/test/logs
format json
time_slice_format %Y%m%d
time_slice_wait 24h
compress gzip
include_tag_key true
utc
buffer_path /var/log/test/logs.*
</match>
This creates multiple gz file for every ~10min.
-rw-r--r-- 1 root root 256546 May 6 07:03 logs.20170506_0.log.gz
-rw-r--r-- 1 root root 260730 May 6 07:14 logs.20170506_1.log.gz
-rw-r--r-- 1 root root 261155 May 6 07:25 logs.20170506_2.log.gz
-rw-r--r-- 1 root root 258903 May 6 08:56 logs.20170506_10.log.gz
-rw-r--r-- 1 root root 282680 May 6 09:08 logs.20170506_11.log.gz
...
-rw-r--r-- 1 root root 261973 May 6 10:44 logs.20170506_19.log.gz
I want to know the way to create a single gzipped file for each day. Even setting time_slice_wait to 24h didn't help.
A: Missed a silly thing in configuration: https://docs.fluentd.org/output/file#append
Updated configuration
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
<source>
@type http
port 8888
bind 0.0.0.0
body_size_limit 32m
keepalive_timeout 10s
</source>
<match **>
type file
path /var/log/test/logs
format json
time_slice_format %Y%m%d
time_slice_wait 24h
compress gzip
include_tag_key true
utc
buffer_path /var/log/test/logs.*
append true
</match>
A: If anyone is continuing to get errors, in the match block, type should also be @type.
| |
doc_23533411
|
<script>
(function($){
$(document).ready(function(){
$('#related-products a').attr('target', '_blank');
});
})(jQuery);
</script>
However we are not going to be using jquery anymore and I was wondering how to do the same thing in javascript only?
Thanks!
A: let anchors = document.querySelectorAll(“#related-products a”);
Now, anchors is an array of DOM elements, we need to loop over them and set their target attribute:
for(let i=0; i<anchors.length; i++){
anchors[i].setAttribute(‘target’, ‘_blank’);
}
A: You can do it like the following code. But you need to put your <script></script> at the end of <body></body> tag to make sure that full document is loaded.
<div id="related-products">
<a href="www.google.com">It will open in new tab</a>
</div>
<a href="www.example.com">It will not open in new tab</a>
<script>
(function() {
var elems = document.querySelectorAll('#related-products a');
elems.forEach(function(elem) {
elem.setAttribute("target", "_blank");
});
})();
</script>
| |
doc_23533412
|
I have installed the correct OpenCV manager and the OpenCV binary pack. After trying to run a sample OpenCV app (e.g. the 15 puzzle) I get the following message:
"OpenCV library package was not found! Try to install it?"
Of course, I cannot install it, since there is no Google Play Store. How can I get the OpenCV library package onto the device and am I wrong to think that the OpenCV binary pack is exactly that?
| |
doc_23533413
|
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
A: Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
A: Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
A: The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
A: Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed
| |
doc_23533414
|
How would I go about checking each square using a table with Lua? I'm starting with the following table:
local sq = {
1, 1, 1,
1, 1, 1
1, 1, 1
}
How would I go about checking each table in the correct order? I'm able to draw out my thinking on paper, but I'm not completely sure how to translate it to code. I already created the function to check if the square is 'magic' (following), but I'm not sure how to increase each number in the correct fashion.
local isMagic = function(s)
return (
s[1] + s[2] + s[3] == 15 and
s[4] + s[5] + s[6] == 15 and
s[7] + s[8] + s[9] == 15 and
s[1] + s[4] + s[7] == 15 and
s[2] + s[5] + s[8] == 15 and
s[3] + s[6] + s[9] == 15 and
s[1] + s[5] + s[9] == 15 and
s[3] + s[5] + s[7] == 15
)
end
A: Based on what I am seeing here, there are three patterns:
1) if we can define step by 3, we compare columns:
sum(tab[x] for x in range(step)) == sum(tab[x] for x in xrange(step+1,step*2))== sum(tab[x] for x in xrange(2*step+1,step*3))
2) raws:
sum(tab[x] for x in range(step*step) if x%step==0) == sum(tab[x] for x in range(step*step) if x%step==1)== sum(tab[x] for x in range(step*step) if x%step==2) ===> till we x%step== step-1
3) Diagonales:
sum(tab[x] for x in range(step*step) if x%(step+1)==0) == sum(tab[x] for x in range(step*step) if x%(step+1)==step-1)
A: First of all, you have a 2D set, why do you use a 1D List?
I'd prefer your square to be like
square[1-3][1-3]
So you can just check every line at X and every line at Y and then check the 2 diagonals.
rather than
square[1-9]
You have to Hardcode the checkings in this solution, wich will not allow you to set other square sizes without coding stuff new.
Just like:
local square = {}
square[1] = {[1] = 2, [2] = 7, [3] = 6}
square[2] = {[1] = 9, [2] = 5, [3] = 1}
square[3] = {[1] = 4, [2] = 3, [3] = 8}
Here is my code for checking if a square is magic or not.
You can set the size as you wish.
#!/usr/local/bin/lua
function checkTheSquare(square, check_for)
local dia_sum = 0 -- we will add the diagonal(u.l. to l.r.) values here
local inv_dia_sum = 0 -- we will add the diagonal(u.r. to l.l.) values here
for i = 1, #square do -- for every [i] line in square
local temp_sum = 0 -- just holds the values for the [i] line temporary
for j = 1, #square do -- for every [j] line in square
temp_sum = temp_sum + square[i][j] -- add the square[i][j] value to temp
end
dia_sum = dia_sum + square[i][i]
-- this will go like: [1][1] -> [2][2] -> [3][3] ...
inv_dia_sum = inv_dia_sum + square[i][#square-i+1]
-- this will go like: [1][3] -> [2][2] -> [3][1] ...
if temp_sum ~= check_for then return false end
-- first possible find of wrong line -> NOT MAGIC
end
if dia_sum ~= check_for and inv_dia_sum ~= check_for then
return false
-- due its not magic
end
return true
-- ITS MAGIC! JUHUUU
end
local square = {}
square[1] = {[1] = 16, [2] = 3, [3] = 2, [4] = 13}
square[2] = {[1] = 5, [2] = 10, [3] = 11, [4] = 8}
square[3] = {[1] = 9, [2] = 6, [3] = 7, [4] = 12}
square[4] = {[1] = 4, [2] = 15, [3] = 14, [4] = 1}
local check_for = 34
print(checkTheSquare(square, check_for) == true)
compared to your very own code, it looks more complicated but:
*
*Yours isn't an algorithm, its a procedure.
*Mine is dynamic. One could also add random values in the square-fields, would be interisting how many tries it'll take in average, to provide a magic square.
| |
doc_23533415
|
NSString *oldPath = [NSString stringWithFormat:@"%@/Documents/", NSHomeDirectory()];
NSString *newPath = [NSMutableString stringWithFormat:@"%@/Library/Caches/", NSHomeDirectory()];
NSError *error = nil;
// get the list of all files and directories
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if(error != nil)
{
NSLog(@"\n\n\n1. There was an error in the file operation: %@", [error localizedDescription]);
return;
}
for(NSString *file in fileList)
{
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(@"The path for the file is: %@", path);
BOOL isDir = NO;
BOOL dirExists = [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir && dirExists)
{
//Move to the new location
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error != nil)
{
NSLog(@"\n\n\n2. There was an error in the file operation: %@", [error localizedDescription]);
}
else
{
[fileManager removeItemAtPath:path error:&error];
if(error != nil)
NSLog(@"\n\n\n3. There was an error in the file operation: %@", [error localizedDescription]);
}
}
}
The copy works fine. I can see all the directories copied to the new location.
The problem is that the empty directories still remain in the Documents folder. I read up on removeItemAtPath in the docs and it says there that the contents of the directory are deleted. Whether the actual directory itself is deleted or not has no mention.
Could someone tell me what could be going wrong in the code? Why do the empty directories still remain?
EDIT:
On the first pass, when the directories exist in Documents, but not in Library/Caches, removeItemAtPath does not throw an error. The empty directories still remain in Documents, though. On the second pass of the above code, it attempts to remove the empty directories and removeItemAtPath throws a cocoa error 516 which is basically file not found - this is weird, because I can still see those empty directories.
Also, I'm running this code on iPhone Simulator 4.3.2 and iPhone Simulator 5.0, and monitoring the directory structure on my Mac in /Users/Library/Application Support/iPhone Simulator/....
A: This may be happening because of the trailing "/" in "/Documents/". Try removing the trailing "/" from the first 2 lines, or use this:
NSString *oldPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *newPath = [NSString pathWithComponents:[NSArray arrayWithObjects:NSHomeDirectory() , @"Library", @"Caches", nil]];
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if (error) {
NSLog(@"\n\n\n1. There was an error in the file operation: %@", [error localizedDescription]);
return;
}
for (NSString *file in fileList) {
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(@"The path for the file is: %@", path);
BOOL isDir = NO;
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error) {
NSLog(@"\n\n\n2. There was an error in the file operation: %@", [error localizedDescription]);
} else {
[fileManager removeItemAtPath:path error:&error];
if (error) {
NSLog(@"\n\n\n3. There was an error in the file operation: %@", [error localizedDescription]);
}
}
}
}
| |
doc_23533416
|
Given:
var ppl = {
1: { name: 'Fred', age: 31 },
0: { name: 'Alice', age: 33 },
3: { name: 'Frank', age: 34 },
2: { name: 'Mary', age: 36 }
}
console.log(ppl);
It appears that the object when created is sorted by the key, the console shows this:
{
0: { name: 'Alice', age: 33 }
1: { name: 'Fred', age: 31 }
2: { name: 'Mary', age: 36 }
3: { name: 'Frank', age: 34 }
}
Then I use lodash to convert to an array like this:
var arr = _.toArray(ppl);
console.log(arr)
*
*I don't think the order of the initial object map is guaranteed, is
that correct?
*How can I ensure the array order is based on the object map's keys?
A: This is easy to do with a the _.chain() method:
var ppl = {
1: { name: 'Fred', age: 31 },
0: { name: 'Alice', age: 33 },
3: { name: 'Frank', age: 34 },
2: { name: 'Mary', age: 36 }
};
const output = _.chain(ppl)
.toArray()
.sortBy()
.value();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
| |
doc_23533417
|
async foo() : Promise<Object> {
if(...) throw new Error
}
How am I supposed to test that the error is thrown? Currently I'm doing this:
it("testing for error thrown", async function () {
expect(async() => await foo()).to.throw(Error)
})
A: You can do something like this and if the error is thrown, the test will fail.
const foo = async (): Promise<Object> => {
// If you want the test to fail increase x to 11
const x = 0
if (x > 10) {
throw Error('Test will fail')
}
// Add meaningful code this is just an example
return { some: 'object' }
}
it('testing for error thrown', async () => {
const object = await foo()
expect(object).toEqual({ some: 'object' })
})
A: Try this:
it("testing for error thrown", async function () {
await expect(foo()).rejects.toThrow(Error)
})
A: Since you mentioned chai-as-promised, you would use either:
expect(promise).to.eventually.be.rejected
or:
promise.should.be.rejected
There's also rejectedWith() which lets you specify the Error class/constructor.
Here's a demo:
mocha.setup('bdd');
mocha.checkLeaks();
let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* hack due to lack of UMD file, only for SO */
chai.use(chaiAsPromised);
async function foo(){
throw new Error();
}
describe('Asynchronous Function', function(){
it('Expect and Eventually', function(){
return expect(foo()).to.eventually.be.rejected;
})
it('With Should', function(){
return foo().should.be.rejected;
});
});
mocha.run();
.as-console {
display: none !important;
}
<script>
window.module = {}; function require(){ return {} }; /* hack due to lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/chai-as-promised@7.1.1/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/chai@4.3.4/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>
| |
doc_23533418
|
{
try
{
message = (String) input.readObject();
showMessage("\n" + message);
}
catch(ClassNotFoundException cnfe)
{
showMessage("\nI don't know that object type");
}
}
while(!message.equals("SERVER - END"));
Hello everyone,
I had trouble understanding how to solve this question so I had to send it here.
I would like to get a serious answer on what to do to fix this code.
Basically when I am reading on what server has sent me I get an EOFException on readObject().
My server sends message and client reads it
output.writeObject("SERVER - " + message);
output.flush();
My questions is should I use writeUTF and readUTF or can I make somehow readObject and writeObject work ?
A: EOFException can occur in ObjectOutputStream if you mix write/read modes e.g. if you writeUTF and readObject.
However, I would use writeUTF/readUTF with DataOutputStream and DataInputStream as these are much simpler.
| |
doc_23533419
|
Main which contains a function call when the application is launched
void main() async {
await FunctionCall().numberColumnFunction();
runApp(const MyApp());
}
Function in which the called function and variables are located:
class FunctionCall {
int numberColumn = 3;
int columnsPositioned = 5;
var visibilityColumn = false;
numberColumnFunction(){
if (numberColumn == 3) {
columnsPositioned = 8;
visibilityColumn = true;
}
else {
null;
}
}
}
And ColumnView in which I get variables from the Function for further work with them:
// More code
end: width / FunctionCall().columnsPositioned,
// More code
visible: FunctionCall().visibilityColumn,
// More code
The problem is that in ColumnView the variables declared by me with default values are always called
int columnsPositioned = 5;
var visibilityColumn = false;
Even if the function conditions are met and the values in the variables change, the call still goes to the old values. How do I make ColumnView take values after executing the function ?
A: The traditional and programming way I can think of right now is making that class a singleton. You can search and do more research on singleton classes and factory pattern. But for now, this code should solve your problem ->
class FunctionCall {
FunctionCall._sharedInstance(); //This is a private constructor.
static final FunctionCall _shared = FunctionCall._sharedInstance(); // This is the instance we want to send every time.
factory FunctionCall() => _shared; // This is where we send it every time the class is created!
int numberColumn = 3;
int columnsPositioned = 5;
var visibilityColumn = false;
numberColumnFunction(){
if (numberColumn == 3) {
columnsPositioned = 8;
visibilityColumn = true;
}
else {
null;
}
}
}
Basically, the problem was, Every time you called the class like this FunctionCall() It was creating a new class. And a new class would always have the default class data. Bcz the function didn't get called inside the new class. So to stop making a new instance of your class you can try this way of making your class a singleton. And returning the exact same instance of your class when it is initiated! And Done!
A: You are creating the FunctionCall() object inside the main function. The Visibility Column for this object is true. However, you are creating a new FunctionCall() object inside the ColumnView widget. The visibilityColumn value of this object is initially set to false. They are two different objects.
My suggestion:
FunctionCall functionCall = FuncitonCall();
Define the above code globally.
Edit this object in main and use the same object in ColumnView widget.
| |
doc_23533420
|
Here is what I am trying to match:
loop_loopStorage_rev='latest.integration'
I need to match loop and latest.integration.
This is my regex:
^(?!\#)(loop_.+rev).*[\'|\"](.*)[\'|\"]$
When I use this in a Perl script, $1 and $2 give me the appropriate output. If I do this:
perl -nle "print qq{$1 => $2} while /^(?!#)(loop_.+rev).+?[\'|\"](.+?)[\'|\"]$/g" non-hadoop.env
I get the error:
-bash: syntax error near unexpected token `('
I believe it has something to do with the beginning part of my regex. So my real question is would there be an easier solution using sed, egrep or awk? If so, does any one know where to begin?
A: Using single quotes around your arguments to prevent special processing of $, \, etc. If you need to include a single quote within, the generic solution is to use '\''. In this particular case, however, we can avoid trying to include a ' by using the equivalent \x27 in the regex pattern instead.
perl -nle'
print "$1 => $2"
while /^(?!#)(loop_.+rev).+?[\x27\"|](.+?)[\x27\"|]$/g;
' non-hadoop.env
[I added some line breaks for readability. You can actually leave them in if you want to, but you don't need to.]
Note that there are some problems with your regex pattern.
*
*(?!\#)(loop_.+rev) is the same as (loop_.+rev) since l isn't #, so (?!\#) isn't doing whatever you think it's doing.
*[\'|\"] matches ', " and |, but I think you only meant it to match ' and ". If so, you want to use [\'\"], which can be simplified to ['"].
*Don't use the non-greedy modifier (? after +, *, etc). It's used for optimization, not for excluding characters. In fact, the second ? in your pattern has absolutely no effect, so it's not doing what you think it's doing.
Fixed?
perl -nle'
print "$1 => $2"
while /^(loop_.+rev).+[\x27"]([^\x27"]*)[\x27"]$/g;
' non-hadoop.env
A: Double quotes cause Bash to replace variable references like $1 and $2 with the values of these shell variables. Use single quotes around your Perl script to avoid this (or quote every dollar sign, backtick, etc in the script).
However, you cannot escape single quotes inside single quotes easily; a common workaround in Perl strings is to use the character code \x27 instead. If you need single-quoted Perl strings, use the generalized single-quoting operator q{...}.
If you need to interpolate a shell variable name, a common trick is to use "see-saw" quoting. The string 'str'"in"'g' in the shell is equal to 'string' after quote removal; you can similarly use adjacent single-quoted and double-quoted strings to build your script ... although it does tend to get rather unreadable.
perl -nle 'print "Instance -> $1\nRevision -> $2"
while /^(?!#)('"$NAME"'_.+rev).+[\x27"]([^\x27"]*)[\x27"]$/g' non-hadoop.en
(Notice that the options -nle are not part of the script; the script is the quoted argument to the -e option. In fact perl '-nle script ...' coincidentally works, but it is decidedly unidiomatic, to the point of confusing.)
A: I ended up figuring out due to all of you guys help. Thanks again. Here is my final command
perl -nle 'print "$1 $2" while /^($ENV{NAME}_.+rev).+\x27(.+)\x27/g;' $ENVFILE
| |
doc_23533421
|
enum e : uint
{
a = 0x00000001,
b = 0x00000002,
c = 0x00001000,
d = 0x00002000
}
and uint v = 0x00003003.
How to convert 0x00003003 to string list like {'a', 'b', 'c', 'd'} ?
I tried
Console.WriteLine(Enum.ToObject(typeof(e), v));
but it prints nothing.
| |
doc_23533422
|
How to do it without controllers on directly inserting code in onclickbutton function?
A: Call the toFront() method of the window.
How you can find the window depends on your application, in your case you probably just store a reference to the window in a variable or find it by ID.
A: Here is what I have done for this use case:
/**
* Check to see if window already open with the specified ID.
* If window exists, bring it to front and expand if collapsed.
* @param id
*/
windowAlreadyOpen: function(id){
//Check for already opened window with the same ID
var windowOpen = Ext.ComponentQuery.query('window[id='+id+']'); //always returns array
if (windowOpen && windowOpen[0]){
try {
windowOpen[0].toFront(); //bring to front
if (windowOpen[0].collapsed){
windowOpen[0].toggleCollapse(); //expand window if collapsed
}
} catch (e) {
console.error(e);
}
return windowOpen[0];
}
return false;
}
| |
doc_23533423
|
When I try to spark-submit a job using ./spark-2.1.1-bin-hadoop2.7/bin/spark-submit --master yarn --deploy-mode cluster ip.py. I'm getting the following error.
Diagnostics: File does not exist:
hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_libs__1200479165381142167.zip
java.io.FileNotFoundException: File does not exist:
hdfs://ec2-54-153-50-11.us-west
1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_libs__1200479165381142167.zip
17/05/28 18:58:32 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/05/28 18:58:33 INFO client.RMProxy: Connecting to ResourceManager at ec2-54-153-50-11.us-west-1.compute.amazonaws.com/172.31.5.235:8032
17/05/28 18:58:34 INFO yarn.Client: Requesting a new application from cluster with 3 NodeManagers
17/05/28 18:58:34 INFO yarn.Client: Verifying our application has not requested more than the maximum memory capability of the cluster (8192 MB per container)
17/05/28 18:58:34 INFO yarn.Client: Will allocate AM container, with 1408 MB memory including 384 MB overhead
17/05/28 18:58:34 INFO yarn.Client: Setting up container launch context for our AM
17/05/28 18:58:34 INFO yarn.Client: Setting up the launch environment for our AM container
17/05/28 18:58:34 INFO yarn.Client: Preparing resources for our AM container
17/05/28 18:58:36 WARN yarn.Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
17/05/28 18:58:41 INFO yarn.Client: Uploading resource file:/tmp/spark-fbd6d435-9abe-4396-838e-60f19bc2dc14/__spark_libs__1200479165381142167.zip -> hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_libs__1200479165381142167.zip
17/05/28 18:58:45 INFO yarn.Client: Uploading resource file:/home/ubuntu/ip.py -> hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/ip.py
17/05/28 18:58:45 INFO yarn.Client: Uploading resource file:/home/ubuntu/spark-2.1.1-bin-hadoop2.7/python/lib/pyspark.zip -> hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/pyspark.zip
17/05/28 18:58:45 INFO yarn.Client: Uploading resource file:/home/ubuntu/spark-2.1.1-bin-hadoop2.7/python/lib/py4j-0.10.4-src.zip -> hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/py4j-0.10.4-src.zip
17/05/28 18:58:45 INFO yarn.Client: Uploading resource file:/tmp/spark-fbd6d435-9abe-4396-838e-60f19bc2dc14/__spark_conf__7895841687984145748.zip -> hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_conf__.zip
17/05/28 18:58:46 INFO spark.SecurityManager: Changing view acls to: ubuntu
17/05/28 18:58:46 INFO spark.SecurityManager: Changing modify acls to: ubuntu
17/05/28 18:58:46 INFO spark.SecurityManager: Changing view acls groups to:
17/05/28 18:58:46 INFO spark.SecurityManager: Changing modify acls groups to:
17/05/28 18:58:46 INFO spark.SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(ubuntu); groups with view permissions: Set(); users with modify permissions: Set(ubuntu); groups with modify permissions: Set()
17/05/28 18:58:46 INFO yarn.Client: Submitting application application_1495996836198_0003 to ResourceManager
17/05/28 18:58:46 INFO impl.YarnClientImpl: Submitted application application_1495996836198_0003
17/05/28 18:58:47 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:47 INFO yarn.Client:
client token: N/A
diagnostics: N/A
ApplicationMaster host: N/A
ApplicationMaster RPC port: -1
queue: default
start time: 1495997926073
final status: UNDEFINED
tracking URL: http://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:8088/proxy/application_1495996836198_0003/
user: ubuntu
17/05/28 18:58:48 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:49 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:50 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:51 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:52 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:53 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:54 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:55 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:56 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:57 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:58 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:58:59 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:59:00 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:59:01 INFO yarn.Client: Application report for application_1495996836198_0003 (state: ACCEPTED)
17/05/28 18:59:02 INFO yarn.Client: Application report for application_1495996836198_0003 (state: FAILED)
17/05/28 18:59:02 INFO yarn.Client:
client token: N/A
diagnostics: Application application_1495996836198_0003 failed 2 times due to AM Container for appattempt_1495996836198_0003_000002 exited with exitCode: -1000
For more detailed output, check application tracking page:http://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:8088/cluster/app/application_1495996836198_0003Then, click on links to logs of each attempt.
Diagnostics: File does not exist: hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_libs__1200479165381142167.zip
java.io.FileNotFoundException: File does not exist: hdfs://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:9000/user/ubuntu/.sparkStaging/application_1495996836198_0003/__spark_libs__1200479165381142167.zip
at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1309)
at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1301)
at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1301)
at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:253)
at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:63)
at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:361)
at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:421)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:358)
at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:62)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Failing this attempt. Failing the application.
ApplicationMaster host: N/A
ApplicationMaster RPC port: -1
queue: default
start time: 1495997926073
final status: FAILED
tracking URL: http://ec2-54-153-50-11.us-west-1.compute.amazonaws.com:8088/cluster/app/application_1495996836198_0003
user: ubuntu
Exception in thread "main" org.apache.spark.SparkException: Application application_1495996836198_0003 finished with failed status
at org.apache.spark.deploy.yarn.Client.run(Client.scala:1180)
at org.apache.spark.deploy.yarn.Client$.main(Client.scala:1226)
at org.apache.spark.deploy.yarn.Client.main(Client.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
17/05/28 18:59:02 INFO util.ShutdownHookManager: Shutdown hook called
17/05/28 18:59:02 INFO util.ShutdownHookManager: Deleting directory /tmp/spark-fbd6d435-9abe-4396-838e-60f19bc2dc14
ubuntu@ip-172-31-5-235:~$
A: I was setting the master to local (.setMaster('local')) in my source file. After I remove this, everything works fine.
A: I also had this problem. I tried the solution of removing the setMaster('local') in the source, however the error did not go away.
What finally solved my problem was actually quite simple: the sparkcontext needed to be initialized First (even before non-spark related variables).
Solution
From the post mentioned above, here is a python example. The same logic worked for me in scala
Hi there, If i follow your suggestions, it works.
Our code was like that :
Import numpy as np
Import SparkContext
foo = np.genfromtext(xxxxx)
sc=SparkContext(...)
#compute
===> It fails ...
Import numpy as np
Import SparkContext
sc=SparkContext(...)
foo = np.genfromtext(xxxxx)
#compute
===> It works perfectly ...
Note I also removed the setMaster('local'), because it makes sense that would interfere too.
| |
doc_23533424
|
I need help setting custom weights to a tiny custom Keras model for a 2D convolution. I have an input that looks like this:
X = [[[3, 2, -4],
[0, 5, 4],
[2, -1, -7],
[-7, 0, 1]],
[[-8, 9, 1],
[-3, 6, 0],
[0, -4, 2],
[5, 1, 1]]]
So, it can be think of a 4x3 image with only two channels. And my kernel looks like this:
kernel = [[[2, 1],
[0, -1],
[0, -1]],
[[1, 2],
[2, -1],
[2, -2]]]
So, a two dimensional 3x2 kernel. Doing by hand a 2D convolution with stride of 1 and no padding, yields:
[[10, 14],
[27, 16]]
Unfortunately, the following Keras code:
model = Sequential()
conv2d = Conv2D(filters=1, kernel_size=(3,2), strides=1, input_shape=(2,4,3), use_bias=False)
model.add(conv2d)
layer = model.layers[0]
layer.set_weights([np.array(kernel).reshape(3, 2, 2, 1)])
print(model.predict(np.array(X).reshape((1,) + np.shape(X))))
Outputs:
[[19, -6],
[-39, 16]]
I couldn't figure out how does Keras organize its kernels for the convolution. So far, looks very counterintuitive, but am probably missing something.
I am using Keras 2.0.9 with Tensorflow 1.4.0 as backend.
A: The kernels in keras follow this shape: (height, width, input_channels, output_channels) -- even when you're using channels_first.
You're right in thinking it uses a shape (3,2,2,1)
But your manual calculation is considering an inverted shape. In your manual calculation you're using (input_channels, height, width).
When you reshape the kernel, you're not reordering these dimensions properly. Just reshaping is not equivalent to "transposing" the array. Reshape simply regroups the data without any kind of reordering.
To achieve a correct result in keras, you need to swap the axes properly:
#start as (input_channels, height, width) = (2,3,2)
kernel = np.array([[[2, 1],
[0, -1],
[0, -1]],
[[1, 2],
[2, -1],
[2, -2]]])
#change to (height, input_channels, width) = (3,2,2)
kernel = kernel.swapaxes(0,1)
#change to (height, width, input_channels) = (3,2,2)
kernel = kernel.swapaxes(1,2)
#add output_channels
kernel = kernel.reshape((3,2,2,1))
| |
doc_23533425
|
S
public static void featuredItems(Player c) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter time = DateTimeFormatter.ofPattern("H"); //Gets hours
int currentTime = Integer.parseInt(time.format(now));
int start1 = 22017, id = 0, totalSales = 0;
List<ListedItem> items = getSalesForPlayer(c.getName().toLowerCase());
c.getPA().sendFrame126("Featured Items", 22004);
for (ListedItem sale : items) {
if (sale.soldAll())
continue;
c.getPA().sendFrame126(sale.getSeller(), start1);//this calls for the top variable in featured shops
start1++;
c.getPA().sendFrame126("Time: " + (24 - currentTime) + " (H)", start1);//this calls for bottom varriable
start1 ++;
start1 ++;
totalSales++;
Misc.print("Name:" +c.getName().toLowerCase());
c.lastTimeForPost = now.getDayOfMonth();
Misc.print("Time:" +c.lastTimeForPost);
if (totalSales == 10) {
Misc.print("Reached 10 featured sales");
break;
}
}
}
private static final Runnable SERVER_TASKS = () -> {
try {
itemHandler.process();
playerHandler.process();
npcHandler.process();
shopHandler.process();
Highpkarena.process();
Lowpkarena.process();
globalObjects.pulse();
CycleEventHandler.getSingleton().process();
events.process();
serverData.processQueue();
} catch (Throwable t) {
t.printStackTrace();
t.getCause();
t.getMessage();
t.fillInStackTrace();
System.out.println("Server tasks - Check for error");
PlayerHandler.stream().filter(Objects::nonNull).forEach(PlayerSave::save);
}
};
i know i have to call it in my server main but just not sure how to do it or load it :p
| |
doc_23533426
|
After several trials and debugging actions, I could isolate a single atomic change between a properly working behavior of the program (correct thread joining and termination) and the undesired one. In particular, I observed that the main program unexpectedly terminates after the end of a thread callback calling the Eigen method .row() on an Eigen matrix: the thread callback seems to correctly execute the related instruction (i.e., the output vector is successfully assigned to the selected row of the input matrix) and finish properly but, for some reason, the main thread is not able to join it and terminates immediately. If I substitute the call to the .row() method with an explicit element-wise assignment of the vector, this behavior does not occur, the main thread properly joins and the program continues and terminates as expected.
I don't really know if the issue that I'm experiencing is somehow caused by this Eigen method, but I couldn't find any other discriminating factor to debug the problem.
Does anybody have a possible idea or suggestion about the reason underlying this problem? I am aware that the formulation of my question is really general and could be due to a huge set of causes, but I am not even able to guess where I need to put the focus on to solve it.
Thanks in advance
| |
doc_23533427
|
However, I notice that the aliased object is placed "too soon" in the OrderedDict in the output.
How can I preserve the order of this mapping when read into Python, ideally as an OrderedDict? Is it possible to achieve this result without writing some custom parsing?
Notes:
*
*I'm not particularly concerned with the method used, as long as the end result is the same.
*Using sequences instead of mappings is problematic because they can result in nested output, and I can't simply flatten everything (some nestedness is appropriate).
*When I try to just use !!omap, I cannot seem to merge the aliased mapping (d1.dt) into the d2 mapping.
*I'm in Python 3.6, if I don't use this loader or !!omap order is not preserved (apparently contrary to the top 'Update' here: https://stackoverflow.com/a/21912744/2343633)
import yaml
import yamlordereddictloader
yaml_file = """
d1:
id:
nm1: val1
dt: &dt
nm2: val2
nm3: val3
d2: # expect nm4, nm2, nm3
nm4: val4
<<: *dt
"""
out = yaml.load(yaml_file, Loader=yamlordereddictloader.Loader)
keys = [x for x in out['d2']]
print(keys) # ['nm2', 'nm3', 'nm4']
assert keys==['nm4', 'nm2', 'nm3'], "order from YAML file is not preserved, aliased keys placed too early"
A:
Is it possible to achieve this result without writing some custom parsing?
Yes. You need to override the method flatten_mapping from SafeConstructor. Here's a basic working example:
import yaml
import yamlordereddictloader
from yaml.constructor import *
from yaml.reader import *
from yaml.parser import *
from yaml.resolver import *
from yaml.composer import *
from yaml.scanner import *
from yaml.nodes import *
class MyLoader(yamlordereddictloader.Loader):
def __init__(self, stream):
yamlordereddictloader.Loader.__init__(self, stream)
# taken from here and reengineered to keep order:
# https://github.com/yaml/pyyaml/blob/5.3.1/lib/yaml/constructor.py#L207
def flatten_mapping(self, node):
merged = []
def merge_from(node):
if not isinstance(node, MappingNode):
raise yaml.ConstructorError("while constructing a mapping",
node.start_mark, "expected mapping for merging, but found %s" %
node.id, node.start_mark)
self.flatten_mapping(node)
merged.extend(node.value)
for index in range(len(node.value)):
key_node, value_node = node.value[index]
if key_node.tag == u'tag:yaml.org,2002:merge':
if isinstance(value_node, SequenceNode):
for subnode in value_node.value:
merge_from(subnode)
else:
merge_from(value_node)
else:
if key_node.tag == u'tag:yaml.org,2002:value':
key_node.tag = u'tag:yaml.org,2002:str'
merged.append((key_node, value_node))
node.value = merged
yaml_file = """
d1:
id:
nm1: val1
dt: &dt
nm2: val2
nm3: val3
d2: # expect nm4, nm2, nm3
nm4: val4
<<: *dt
"""
out = yaml.load(yaml_file, Loader=MyLoader)
keys = [x for x in out['d2']]
print(keys)
assert keys==['nm4', 'nm2', 'nm3'], "order from YAML file is not preserved, aliased keys placed too early"
This has not the best performance as it basically copies all key-value pairs from all mappings once each during loading, but it's working. Performance enhancement is left as an exercise for the reader :).
| |
doc_23533428
|
Home@PC /c/rails/konkurranceportalen (master)
$ heroku db:push
Loaded Taps v0.3.19
Auto-detected local database: mysql://root@127.0.0.1/konkurranceportalen?encodin
g=utf8
Warning: Data in the app 'vinderhimlen' will be overwritten and will not be reco
verable.
! WARNING: Potentially Destructive Action
! This command will affect the app: vinderhimlen
! To proceed, type "vinderhimlen" or re-run this command with --confirm vind
erhimlen
> vinderhimlen
Sending schema
Schema: 100% |==========================================| Time: 00:01:07
Sending indexes
admins: 100% |==========================================| Time: 00:00:01
schema_migrat: 100% |==========================================| Time: 00:00:01
slugs: 100% |==========================================| Time: 00:00:02
Sending data
7 tables, 138 records
admins: 100% |==========================================| Time: 00:00:00
kategoris: 0% | | ETA: --:--:--
Saving session to push_201103182120.dat..
!!! Caught Server Exception
HTTP CODE: 503
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
g/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
html, body, iframe { margin: 0; padding: 0; height: 100%; }
iframe { display: block; width: 100%; border: none; }
</style>
<title>Application Error</title></head>
</head>
<body>
<iframe src="https://s3.amazonaws.com/heroku_pages/error.html">
<p>Application Error</p>
</iframe>
</body>
</html>
Home@PC /c/rails/konkurranceportalen (master)
$
My Heroku log http://pastie.org/1687466
A: The problem were that Amazon RDS firewall did block Heroku.
In Amazon AWS > Amazon RDS I did go into the security group and did add a EC2 Security Group.
With following details:
Security Group: default
AWS Account ID: 098166147350
| |
doc_23533429
|
The .vscontent file either contains invalid attributes or specifies a code snippet for a programming language that is not installed.
The .vscontent file is based on the documentation provided by Microsoft How to: Distribute Code Snippets
The sample on this site is the following:
<VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005">
<Content>
<FileName> </FileName>
<DisplayName> </DisplayName>
<Description> </Description>
<FileContentType> </FileContentType>
<ContentVersion>2.0</ContentVersion>
<Attributes>
<Attribute name="lang" value=""/>
</Attributes>
</Content>
</VSContent>
My file looks like this:
<VSContent xmlns="http://schemas.microsoft.com/developer/vscontent/2005">
<Content>
<FileName>SSDTTest.snippet</FileName>
<DisplayName>SSDTTest</DisplayName>
<Description>SSDTTest</Description>
<FileContentType>Code Snippet</FileContentType>
<ContentVersion>1.0</ContentVersion>
<Attributes>
<Attribute name="lang" value="SQL_SSDT"/>
</Attributes>
</Content>
</VSContent>
I'm using the value SQL_SSDT since this is the required value in the .snippet files (<Code Language="SQL_SSDT">).
The installation starts as expected (double clicking on the .vsi file), the VS Content Installer pops up, lists the included content. The error occurs after hitting Finish. (Installation starts, but the above error pops up after a few seconds.)
The snippet is working fine if I copy it to the default snippet folder for SSDT (Documents\Visual Studio 2012\Code Snippets\SQL_SSDT\My Code Snippets) or if I'm adding it via snippet manager in SSDT, but the .vsi installation fails using the above file.
Am I missing something?
Installed VS products on this box:
*
*SSDT
*SSDT-BI
*VS Express for Desktop (2012)
Update
I found the XML schema reference for the .vscontent files (VS2012), and it seems that the SQL_SSDT is not a valid value for the Lang attribute. It suggests that there are only four values available for the lang attribute. (csharp, jsharp, vb, xml).
Now the question is: Does SSDT add any extensions to this XML schema?
A: It seems that VS Content Installer has no support for deploying SSDT code snippets. There is a posted idea on visualstudio.uservoice.com which requests this feature, but it is still open.
I did not found any other resources related to this issue.
There is a possible workaround, which needs testing: You can create a PS/BAT which copies the snippet files into the VS's snippet folder for SSDT.
| |
doc_23533430
|
For the reference, this is what I'm trying to implement, this exact same UI has also been implemented on Myntra app.
Check out Myntra UI here: https://vimeo.com/707250315
I've tried searching for some alternatives for this and I found expandable package which does the same thing but is not exactly what I want to achieve. I managed to implement this for now:
If anyone of you have implemented this UI before, I would love to see how it's implemented.
A:
In my research for a solution to this, I concluded AnimatedContainer() would be the best suited for the primary tile. This first snippet is the general widget. At the very end, I have modeled a List of Map<String, dynamic> that represents a possible JSON response
import 'package:flutter/material.dart';
import '/widgets/category_item.dart';
class CategoriesPage extends StatefulWidget {
const CategoriesPage({Key? key}) : super(key: key);
@override
State<CategoriesPage> createState() => _CategoriesPageState();
}
class _CategoriesPageState extends State<CategoriesPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: _products.length,
itemBuilder: (ctx, index) => CategoryItem(product: _products[index]),
),
);
}
}
List<Map<String, dynamic>> _products = [
{
'categoryTitle': 'Summer Shop',
'categoryDescription': 'Turn up the heat in style',
'categoryImage':
'https://images.unsplash.com/photo-1600566752355-35792bedcfea?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Nnx8YmF0aHJvb218ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60',
'subCategory': [
{'categ': 'Top Brands'},
{'categ': 'Men'},
{'categ': 'Women'},
{'categ': 'Kids'},
{'categ': 'Footware'},
{'categ': 'Accessories'},
{'categ': 'Jewellery'},
{'categ': 'Beauty'},
],
},
{
'categoryTitle': 'Men',
'categoryDescription': 'T-shorts, Shirts,Jeans,Accessories',
'categoryImage':
'https://images.unsplash.com/photo-1603825491103-bd638b1873b0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8YmF0aHJvb218ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60',
'subCategory': [
{'categ': 'Top Brands'},
{'categ': 'Men'},
{'categ': 'Women'},
{'categ': 'Kids'},
{'categ': 'Footware'},
{'categ': 'Accessories'},
{'categ': 'Jewellery'},
{'categ': 'Beauty'},
],
},
{
'categoryTitle': 'Women',
'categoryDescription': 'T-shorts, Shirts,Jeans,Accessories',
'categoryImage':
'https://images.unsplash.com/photo-1603825491103-bd638b1873b0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8YmF0aHJvb218ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60',
'subCategory': [
{'categ': 'Top Brands'},
{'categ': 'Men'},
{'categ': 'Women'},
{'categ': 'Kids'},
{'categ': 'Footware'},
{'categ': 'Accessories'},
{'categ': 'Jewellery'},
{'categ': 'Beauty'},
],
},
{
'categoryTitle': 'Kids',
'categoryDescription': 'T-shorts, Shirts,Jeans,Accessories',
'categoryImage':
'https://images.unsplash.com/photo-1603825491103-bd638b1873b0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8OXx8YmF0aHJvb218ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60',
'subCategory': [
{'categ': 'Top Brands'},
{'categ': 'Men'},
{'categ': 'Women'},
{'categ': 'Kids'},
{'categ': 'Footware'},
{'categ': 'Accessories'},
{'categ': 'Jewellery'},
{'categ': 'Beauty'},
],
},
];
This is the builder part. Update with Expandable packge
import 'package:flutter/material.dart';
import 'package:expandable/expandable.dart';
class CategoryItem extends StatefulWidget {
final Map<String, dynamic> product;
const CategoryItem({required this.product, Key? key}) : super(key: key);
@override
State<CategoryItem> createState() => _CategoryItemState();
}
class _CategoryItemState extends State<CategoryItem> {
final _controller = ExpandableController();
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return ExpandablePanel(
controller: _controller,
theme: const ExpandableThemeData(hasIcon: false),
header: Container(
height: deviceSize.height * .13,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(widget.product['categoryImage']),
),
),
),
collapsed: const SizedBox(height: 0),
expanded: ListView.builder(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
itemCount: widget.product['subCategory'].length,
itemBuilder: (ctx, index) => ExpansionTile(
childrenPadding: const EdgeInsets.symmetric(vertical: 5),
title: Text(widget.product['subCategory'][index]['categ']),
children: List<Widget>.generate(
widget.product['subCategory'].length,
(index) => Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(widget.product['subCategory'][index]['categ']),
],
),
),
),
),
);
}
}
| |
doc_23533431
|
I have tried changing the themes, deleting all the pages and starting over. Even when I delete all the pages, including the main page from the pages tab, the custom link is still live and can be seen when visiting the domain. I have also not messed with the filesystem at wp-admin. Also, menu doesn't appear on the pages and I'm suspecting it has to do with the same issue. Please help with this. Thanks.
| |
doc_23533432
|
The deviceMotion property is only available on devices having both an accelerometer and a gyroscope. This is because its sub-properties are the result of a sensor fusion algorithm i.e. both signals are evaluated together in order to decrease the estimation errors.
Emm, my question is where is the internal implementation, or algorithm that CMMotionManager use to do the calculation. I want some detail about this so called "senser fusion algorithm"
Popular fusion algorithms are for instance the Kalman filter and derivatives but I guess the CMMotionManager's internal implementation is based on simpler and thus faster algorithms. I expect some simple but good enough math calculation upon the senser data from accelerometer and gyroscope to finally calculate the roll, yaw and pitch
A: It is not clear what is actually implemented in Core Motion.
As for filters other than the Kalman filter: I have implemented sensor fusion for Shimmer 2 devices based on this manuscript.
You may find this answer on Complementrary Filters also helpful, see especially filter.pdf
I would not use roll, pitch and yaw for two reasons: (1) it messes up the stability of your app and (2) you cannot use it for interpolation.
| |
doc_23533433
|
I searched the stack overflow and found some questions which they were similar to mine but I'm getting some error which I'll post it below.
This and This are the two references that I read for my problem
[![These are the keys that I'm supposed to send][3]][3]
Cannot convert value of type 'Int' to expected argument type 'Data'
even I tried the code below:
let memberIdData = memberID.data(using: String.Encoding.utf8) ?? Data()
let data = ["id":0,
"AddressLine":EntAddressLine.text,
"CityId":selectedCity,
"Mobile":EntMobile.text,
"PostalCode":EntPostalCode.text,
"ProvinceId":selectedProvince,
"Tel":EntTelephone.text] as [String : Any]
how exactly should I fix this
UPDATE:
case .AddAddress(let data):
var multipartData = [MultipartFormData]()
for (key, value) in params! {
let Provience = MultipartFormData.init(provider: .data("\(data)".data(using: String.Encoding.utf8)!), name: "id")
multipartData.append(Provience)
}
return .uploadMultipart(multipartData)
A: Multipart Form Data cant have other types than Data.
So it'd be better to hold a dictionary with type [String:String] and convert it to Data.
Example:
var task: Task {
case .... {
let params: [String:String] = ["id":"0", //convert to string
"AddressLine":EntAddressLine.text,
"CityId":"\(selectedCity)", //convert to string
"Mobile":EntMobile.text,
"PostalCode":EntPostalCode.text,
"ProvinceId":"\(selectedProvince)",//convert to string
"Tel":EntTelephone.text]
var multipartData = [MultipartFormData]()
for (key, value) in params {
let formData = MultipartFormData(provider: .data(value.data(using: .utf8)!), name: key)
multipartData.append(formData)
}
return .uploadMultipart(multipartData)
}
....
}
===============
EDIT:
For non-multipart requests:
var task: Task {
case .... {
let params: [String:Any] = ["id":0,
"AddressLine":EntAddressLine.text,
"CityId":selectedCity,
"Mobile":EntMobile.text,
"PostalCode":EntPostalCode.text,
"ProvinceId":selectedProvince,
"Tel":EntTelephone.text]
return .requestParameters(parameters: param, encoding: JSONEncoding.default)
}
....
}
var headers: [String : String]? {
return ["Content-Type":"application/json"]
}
A: nothing special you should do!!!
public var task: Task {
switch self {
case .AddAddress(let data):
return .requestParameters(parameters: data, encoding: URLEncoding.default)
}
}
try this , this should help
| |
doc_23533434
|
And saving them in a folder.
Using below logic:
How to Access attachments from Notes mail?
But problem i am facing here is.
Attachment having same type and name but different content.
In current situation it is replacing old file with new one.
How i can uniquely manage this attachment for different mails.
A: There is several ways:
1) Always generate a random filename, for every attachment ( Negative here is that you will use "more" storage space
2) Generate a hash like SH-256 of the content of the file, and give it a name after this ( Negative here is hashing can take a while, depending on file size)
Depending on what your doing, i would off course save the original filename somewhere so it can be found based on the filename in the email. Perhaps also if you choose the hashing method, you should store what emails that file is attached to.
A: A few other ideas:
*
*You could add the Notes Document Unique ID to the file name. Then you'd also have a way to determine which Notes Document the file came from.
*In the past, I just handled this the way I see most programs handle it. I appended _x to the file name where x is a number. So if there were three files with the same name, they'd show up in the folder as file.txt, file_1.txt, file_2.txt.
A: You can use the File.Exists(path) to verify if the file exists before extracting and if it does then add something to the name to make it unique.
| |
doc_23533435
|
I'm working with ControlTemplates as described in this article.
Creating the controlTemplate went without a hitch, as did applying it and even binding to it. The problem is that while most of the binding still works in my ContentPage, the EventToCommand in my ListView has broken (tapping no longer invokes the command).
Have you seen this before? Is this a known problem? Is there a fix?
Thanks!!
jesse
A: I've established that when templates are used the ItemSelected event never fires. I will file a bug report.
| |
doc_23533436
|
When you run a delayed job, it doesn't seem to load anything from ApplicationController. We have some code in ApplicationController to use a custom logger:
def setup_logger
logfile = File.open("#{RAILS_ROOT}/log/audit.log", 'a')
@audit_log = Logger.new(logfile)
$audit_log = @audit_log
end
We then reference $audit_log all through our code. But because DelayedJob doesn't load the ApplicationController this variable is nil and we get errors.
So Delayed_job is just running the specified method blindly, which could also be dangerous
if you rely on before_filters for checking data or validating things.
How can we fix our problem of getting DelayedJob to know about our global logging variable? We don't want to explicitly define the logger all through our code.
How else are people dealing with this problem, as it seems like it should be common, but its not talked about much.
Thanks
A: Why you think, a Job must run ApplicationController ?
A Job, precisely the worker running that job, loads the environment, sure, but not a controller...
If you don't want have it in a initializer, why not using a kind of config object for storing such data and reference to it in the job ?
And instead of do it in each job individually, I would suggest set up the logger in the BaseJob, and use it in the inherited jobs for what you need.
And another suggestion, please if you can, don't use delayed job, please use http://mperham.github.io/sidekiq/ or at least https://github.com/resque/resque
| |
doc_23533437
|
You are given the results of a presidential election. Each ballot is presented one by one, and on each ballot the name of a candindate is written(Let's assume candidates name's are represented by numbers). Before announcement of the result, the total number of candidates and the number of people who voted, are unknown.All valid ballots are presented on by one as input, and this process repeats 2 times total. We only have 2 simple varibles we can use for the whole process. You have to design an algorithm which can decide if there is a candidate that has gathered the majority of the votes(meaning more than 50%) of the people who voted, or not. If such a candidate exists, print the candidates name otherwise print "blah blah blah"
Now what first got into my mind, is to use the Boyer-Moore majority algorithm and keep updating the majority and the counter variables as soon as the next result comes in. In case i haven't made that clear, the results aren't stored in an array or anywhere else. You get informed of one ballot, then you calculate(and this goes on until all the ballots have been used, meaning i don't have access to any previous information). Whether this information is stored in array or not, i know i can still run the first iteration of this algorithm to get a "possible" majority result, since the algorithm always produces one. My problem lies in the second iteration.I see the results one more time one by one. How am i supposed to verify if my original result is indeed the majority or not? Is there any other way i can get around it with only 2 variables?
A: You can do a first iteration and keep track of the votes in a single variable. Now the value of this variable "may be" a majority. Now do a second iteration and count the number of occurrences in a second variable of the majority candidate indicated by the first iteration. This is for verifying if the candidate indicated by the first pass is indeed in majority. Overall you just need 2 variables and 2 iterations. By the way, here's a good introduction to the Boyer Moore's voting algorithm - https://satyadeepmaheshwari.medium.com/boyer-moore-voting-algorithm-in-plain-english-4a343fb4c6a1
A: I assume that we are allowed to use loops and loop variable to iterate over a list.
Let's assume that the election information are stored in votes. It contains the candidate number which the people have voted. We will think each of the candidate as winner and store each candidate number as the winner in each iteration. If we can find any candidate number more or equal to 50% of the number of votes, we can infer the candidate is the winner. Thus we can only use two variables count and winner to get the winner's name.
def get_winner(votes):
count = None
winner = None
for i in range(len(votes)):
winner = votes[i]
count = 0
for j in range(i, len(votes)):
if votes[i] == votes[j]:
count += 1
if count >= len(votes)*0.5:
return winner
return "blah blah blah"
if __name__ == "__main__":
votes = [1, 3, 3, 3, 3, 3, 3, 2, 4, 1, 8]
print(get_winner(votes))
Output:
3
| |
doc_23533438
|
When I select a row (with a button or selectionchanged) I want to store that row's columns in variables like
dim email as string
dim name as string
email = dgCustomers.theselectedrow.theselectedcell
name = dgCustomers.theselectedrow.theselectedcell
If I have a datatable with only one row I know I can get column data with:
dim email as string = CustomerDataTableInstance.rows(0).Item("Email")
I don't know how to get the selected row number though when I have several rows and the user clicks one/uses the keyboard.
The datagrid is bound to a datatable, not a class with object collections.
Any help is appreciated!
A: Did you try the SelectedItem or SelectedIndex properties?
I don't know much about using datatables, but I suspect you can get some kind of row object that represents a row from the datatable, by using SelectedItem, which you can then use to get each of the columns you want--which is just like binding to a collection of objects works.
If that doesn't work, try the SelectedIndex property. I'm pretty sure it exists, but I might be wrong since I never use it--I always just bind my data to SelectedItem.
A: I just answered a similar question for someone else. Please see VB.NET WPF How to get the column value from datagrid? for more detail, but Benny Jobigan is correct, you would use the SelectedIndex to get at your row, then use the Item collection to get at your column values. It would look something similar to this:
Dim View As DataView = TryCast(DataGrid1.ItemsSource, DataView)
If View IsNot Nothing Then
Dim ViewRow As DataRowView = View.Item(DataGrid1.SelectedIndex)
Dim ColumnValue As Object = ViewRow.Item("ID") ' or ViewRow.Item(0) for positional value.
' do something with ColumnValue here.
End If
Hope that helps!
| |
doc_23533439
|
static void Main()
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.LiterateConsole(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message} [{Properties}]{NewLine}")
.CreateLogger();
using (LogContext.PushProperty("A", 5))
{
Log.Information("Message using context {A}");
var b = 1;
Log.Information("Message usign context {A} and custom {b}", b);
}
Console.ReadLine();
}
Output
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 1 and custom {b} [{}]
Expected output
//output:
//2017-11-14 15:47:03 [Information] Message using context 5 [{}]
//2017-11-14 15:47:54 [Information] Message usign context 5 and custom 1 [{}]
Is there any way to achieve this?
A: In Serilog's API, any method that accepts a message template expects an exact number of matching arguments.
Serilog won't blow up if the number of placeholders in the template and the provided argument count doesn't match, but there's no guarantee this will work predictably - as you see here.
So in this case, it's necessary to include both A and b in the arguments to Information() in order to get the output you expect.
| |
doc_23533440
|
I can get the sum of two cells if there are two different cells, as shown in the photo, but what formula or is there a formula where you can get the sum of two numbers from one cell? And they contain letters as well. 10:30am-04:30pm is = how many hours(formula).
See photo below
A: If you have dates in column A, you can use this formula in Column B to get time difference value in HH:MM output.
=TEXT((TRIM(MID(A1,FIND("-",A1,1)+1,10))-(LEFT(A1,FIND("-",A1,1)-3))),"hh:mm")
| |
doc_23533441
|
Answers to other questions suggest that you can use window.open(url, "_blank") to achieve this, and this works for me, but I am looking for something I can unit test.
Based on an answer to a different question, I have tried injecting the Document and calling document.open(url, "_blank") like so:
import { Component, OnInit, Input, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
@Component( ........ )
export class MyClass implements OnInit {
private externalLink = "https://bbc.co.uk";
constructor(@Inject(DOCUMENT) private readonly document: Document) { }
ngOnInit() {
}
public navigate() {
this.document.open(this.externalLink, "_blank");
}
}
However, when this runs the screen goes immediately white and nothing else happens. No errors are logged to the console and placing a breakpoint in the method shows that the document is injected correctly as far as I can tell.
If this can't be resolved I am tempted to wrap a service around window.open() and inject that.
A: Use the this code
window.open(this.externalLink, "_blank");
instead of
this.document.open(this.externalLink, "_blank");
Hope this will help!!!
A: With no other answers being given, I did as I suggested I might in my question. I wrapped a small service around window.open like so:
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class NewTabService {
constructor() { }
public open(url: string, newTab: boolean = false) {
if (newTab) {
window.open(url, "_blank");
return;
}
window.location.href = url;
}
}
| |
doc_23533442
|
it get warning message :
PHP Fatal error: Maximum execution time of 30 seconds exceeded in F:\xampp\htdocs\test\S3.php on line 2341, referer: https://127.0.0.1/test/upload.php
the video size is (20 Mo) max.
A: You can use
ini_set('max_execution_time',500); // 500 Seconds
above code for limiting execution time.
A: Your PHP is configured with a max execution time of 30s
you can change it with set_time_limit
| |
doc_23533443
|
<label class="control-label" for="inputgaveabonnement">
Gaveabonnement <b>*</b>
</label>
<div class="controls">
<div class="fieldrow_horz">
<div class="fieldgroup">
<label>
Gaveabonnement tekst <b>*</b>
</label>
</div>
<div class="fieldgroup">
<label>
utm_source <b>*</b>
</label>
</div>
</div>
// Save to array so that we can loop it out later =)
$result = db2_getsub( array('campaigns_id' => $this_id) );
if (!is_null($result))
{
$numsub = 0;
while ( $row = $result->fetch_object() )
{
$numsub = $numsub +1;
array_push($arrFornavn, $row->sub_name);
array_push($arrEtternavn, $row->sub_code);
}
$formcountfld=$numsub;
}
else
{
$numsub=1;
$formcountfld=1;
}
$i = 1;
if (1==1) {
for ($i = 1; $i <= $numsub; $i++)
{
?>
<div class="fieldrow_horz">
<div class="fieldgroup">
<input type="text" id="fornavn_<?= $i ?>" name="fornavn_<?= $i ?>" value="<?= $arrFornavn[$i-1] ?>" />
</div>
<div class="fieldgroup">
<input type="text" id="etternavn_<?= $i ?>" name="etternavn_<?= $i ?>" value="<?= $arrEtternavn[$i-1] ?>" />
</div>
</div>
<?php
}
} else {
?>
<div class="fieldrow_horz">
<div class="fieldgroup">
<input type="text" id="fornavn_<?= $i ?>" name="fornavn_<?= $i ?>" value="" />
</div>
<div class="fieldgroup">
<input type="text" id="etternavn_<?= $i ?>" name="etternavn_<?= $i ?>" value="" />
</div>
</div>
<?php
}
?>
<?php
$thisId = "countfld";
$thisVar = $formcountfld;
?>
<input type="hidden" name="<?= strtolower($thisId) ?>" class="input-medium" id="input<?= $thisId ?>" value="<?= htmlspecialchars($thisVar, ENT_QUOTES) ?>" />
<p>
<a href="#" id="linkAdd">+ Legg til flere</a>
</p>
</div>
</div>
</div>
$(document).ready(function(){
$("#linkRemove").click(function(){
$("#fornavn_<?= $i ?>").remove();
$("#etternavn_<?= $i ?>").remove();
});
});
How can i remove textbox after addding it through loop if anybody can help thanks
in advance this code is adding textbox after clicking on + Legg til flere this but if want
to remove textbox can you suggest me how can i remove a textbox ?
A: With the help of jquery you can remove an element by simply calling remove();
$("#fornavn_1").remove();
This is obviously done from the client side, your question doesn't specify where the removal has to be done from. If you want to remove it before sending to the browser it self. Then you may need to enable output buffering and parse the html with a dom parser and remove the element.
To use jquery make sure you include the following, preferably in the head section of your html.
<script src='http://code.jquery.com/jquery-1.10.1.min.js'></script>
| |
doc_23533444
|
How can i process click inside UITextView not assuming tap on link?
P.S. Setting
myTextView.userInteractionEnabled = NO
looks fine, but links are not detected
A: No need to disable user interaction. Instead, make the textView non-editable:
myTextView.editable = NO;
| |
doc_23533445
|
While learning about JavaScript Module Pattern, as an example I saw code below:
var singletone1 = function() {
function sayHello() {
console.log("Hello")
}
return {
sayHello: sayHello
}
}()
This code works well as an example of revealing module pattern. But I realized that this makes the same result as IIFE version:
var singletone2 = (function() {
function sayHello() {
console.log("Hello")
}
return {
sayHello: sayHello
}
})()
The reason why I felt odd was that, as long as I know, running function declaration directly will make an error.
// Immediately Invoked Function Declaration
function(){
console.log('test');
}()
// => Uncaught SyntaxError: Unexpected token )
To run this, I have to embrace it with parenthesis. By that way, it becomes IIFE. But what is strange to me is the singletone1 example works as usual.
So my question is is there any difference on whether putting parenthesis between the function declaration or not? In other words, is there any difference between Revealing Module Pattern without parenthesis(singletone1) and IIFE version(singletone2)?
If they are same, then is that a matter of operator priority - so that the parenthesis are optional?
A:
Nice possible answer for this question:
"Explain the encapsulated anonymous function syntax"
So I conclude that the reason why singletone1 works properly with no problem at all and seems equivalent to singletone2 is because the statement on the right of the equal operator is interpreted as function expression, not function declaration, although it seems like declaration.
And also I learned that using anonymous function solely is not syntactically allowed, because sole anonymous function(without assigning to any variable) will be interpreted as function declaration, but function declaration must have name identifier. By this, I conclude that anonymous function can be used only after assigned to any variable, or used as IIFE.
If the situation is that a anonymous function can only be interpreted as function expression, then there is no need to put parenthesis around them. That can be optional in this case.
A: Comments explain.
var myLibrary = (function() {
// reference document only once for performance
var doc = document;
// object to expose as public properties and methods
var pub = {};
//myLibrary.color
pub.color = 'red';
//myLibrary.hello
pub.hello = function (name) {
alert('Hello ' + name);
};
//API
return pub;
}());
| |
doc_23533446
|
*
*QT Lite Overview
*QT Lite and Configuration changes`
*QT Lite project information
*QT Lite as lightweight developer framwork
and many more links available on internet giving basic information about the QT Lite framework, from these links
Qt 5.8 will include IoT-oriented “Qt Lite” technology that enables
fine-grained configuration and supports small-footprint IoT gizmos
without OpenGL. The Qt Company announced a Qt Lite project that aims
to extend the Qt development framework to smaller footprint Internet
of Things devices with as little as 16MB RAM and flash. The Qt Lite
technology will initially appear in Qt 5.8, including a more flexible
configuration system for the cross-platform development framework, as
well as a new 2D renderer for devices that can’t run OpenGL. Qt Lite
also provides a more accessible, lightweight set of development tools.
From above links getting feel that QT lite can be used for Devices with less RAM(< 16MB), Devices that require programs with low memory footprint and/or IoT kind of devices.
My Question is Can we use QT Lite for Android and iOS application development? If yes, where can i get steps to port and build existing QT 5.8 project to QT Lite project. Reference link will be helpful.
A: My Question is Can we use QT Lite for Android and iOS application development?
Shortly, Yes. But Qt Lite it is your own build of Qt (from 5.8). You simply disable some unimportant for you features and in result you get smaller qt libs.
Also seems like it is dublicated question to this: Qt Lite and configuration changes in Qt 5.8
| |
doc_23533447
|
git checkout dc8a2c845c615598b2be6a3a0f109f18c44dd836
to go back to the last commit and temporaly discard the changes after the commit,but the changes are still there,do I missed somenthing?
A: What you want to use instead of git checkout:
If you have some uncommited changes, you can "stash" them temporarily using git stash (Documentation). To retrieve them, use git stash apply or git stash pop. The first one will apply the changes and keep them stashed, allowing you to apply them again, while the latter will apply them and remove them from the stash stack. In both cases, your changes will be back as unstaged changes.
If you would use git reset --hard, your changes would be lost, so be careful with that.
EDIT:
Why git checkout did not do what you thought it would:
git checkout dc8a2c845c615598b2be6a3a0f109f18c44dd836 will checkout the given commit, i.e. move the HEAD pointer of your current branch to that commit. Alas, since the changes you made on top of your branch are not yet commited, your branches HEAD already points to that commit! So, the command changes nothing, since your unstaged changes are not affected by changing the branches HEAD pointer.
More detailed: git knows three trees: The working directory, the Index and HEAD. See this article about git reset for further explanation on that. Now, according ti its' documentation, git checkout will
To prepare for working on branch, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept
So, as stated above, the files in the index and the working tree will be updated to the state in the provided commit, the branches HEAD will point to the commit, but local changes (exactly those you wanted to get rid of) are kept!
| |
doc_23533448
|
<form id="form" method="POST">
<input name="image" type="file" />
<br/>
<input type="submit" />
</form>
and also using the following .js code
$("#form").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: "uploadimage.php",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
});
return false
});
but I need to put rules before you submit out the form and so I need use the validation.
Example:
$("#form").validate({
submitHandler: function(form) {
$("#form").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: "uploadimage.php",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
});
return false
});
},rules: {
image: "required"
},
messages: {
image: "image is required"
}
});
but this code does not work
A:
"but this code does not work"
That's because you've put a .submit() handler inside of the plugin's submitHandler...
submitHandler: function(form) {
$("#form").submit(function(e) { ....
The plugin's submitHandler already properly handles the default submit event by only firing on button click when the form is valid.
By putting another .submit() handler inside, it never fires because the form's only submit event has already occurred.
Remove the extra .submit() handler
submitHandler: function (form) {
$.ajax({
// your options
});
return false;
},
Validation DEMO: http://jsfiddle.net/8tebdxn4/
Also, if you want to upload files, you'll need the proper enctype attribute on your <form> tag...
<form id="form" method="POST" enctype="multipart/form-data">
| |
doc_23533449
|
We have no idea where it's comming from.
As you can see:
589 admin localhost psa Sleep
1440 gwingocm localhost gwingo Sleep
1442 gwingocm localhost gwingo Sleep
1441 amfbcm localhost amfb Sleep
1444 gwingocm localhost gwingo Sleep
1446 gwingocm localhost gwingo Sleep
1447 gwingocm localhost gwingo Sleep
1448 gwingocm localhost gwingo Sleep
1449 amfbcm localhost amfb Sleep
1450 amfbcm localhost amfb Sleep
1498 admin localhost mysql Query
This was the proccesslist at a time that the usage was really high.
Any one a good idea how to find out the problem?
Best regards,
Tim
| |
doc_23533450
|
Here is my XAML code for MainWindow:
<UI:HandledWindow x:Class="Diamond.Executor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:Diamond.Core.UI;assembly=Diamond.Core"
Title="MainWindow"
Height="250"
Width="500"
Style="{DynamicResource WindowStandard}"
WindowStartupLocation="CenterScreen"
Loaded="Initialise">
Here is where base type HandledWindow:
namespace Diamond.Core.UI
{
public class HandledWindow : Window
{
What is wrong here? When I run my application anything works, the bindings, The style and it's template.
But suddenly the designer says "'UI' doesn't map to a namespace". I just don't get it. It stops my development really without a reason. Perhaps a VS2012 bug, But I want to insure I am doing everything right and if there is a way to pass that bug and continue using the designer?
A: I've discovered what just causes the issue, But I don't know why, Because by syntax it's okay and logically it works. But XAML's desginer fails to work properly with such data binding expression:
FontSize="{Binding Path=(UI:HandledWindow.FontSizeTitle), Mode=OneWay}"
(It's part of a style inside the UI namespace that XAML declined in a whole because of this expression)
Then I've changed it to this expression:
FontSize="{Binding FontSizeTitle, RelativeSource={RelativeSource TemplatedParent}}"
It does exactly the same, But now the XAML designer works again and stops ignoring the whole namespace UI because of a single data binding expression.
Anyway, The issue is finally resolved.
| |
doc_23533451
|
var interval = setInterval(function () {
clearInterval(interval);
var formattedBodyText = bodyText.replace(/\n/g, '%0d');
var mailTask = Email.SendNewMail.sendEmail(emailAddress, subject, formattedBodyText);
}, 500);
And the sendEmail function:
sendEmail: function sendEmail(addess, subject, body) {
var mailto = new Windows.Foundation.Uri("mailto:?to=" + addess + "&subject=" + subject + "&body=" + body);
return Windows.System.Launcher.launchUriAsync(mailto);
}
Oddly, this seems to launch Chrome (I assume because that's my default browser). How can I get it to launch the mail app? Has this changed since the 8.1 upgrade?
EDIT:
It looks like the default program for opening mails was changed to Chrome. So, I suppose my question is now: is it possible to FORCE the mail app to open, rather than whatever is associated with the mailto: url? I noticed there was an ms-mail uri - would that be safer to use?
A: You can't determine which is default mail app in Windows Store app. Moreover there's no way to open Mail app forcefully in Windows Store app. It doesn't make sense. Some user (Like me!) might not like default mail app. So I would recommend to stick to share charm for sending emails.
| |
doc_23533452
|
Before we implement DSC in PROD environment, our management need to integrate this with ITSM/Change management. So that everything has a Change Ticket (we are using ServiceNow). We can take care of this during the creation and deployment of DSC Configurations.
However, the actual problem is when DSC Configuration is deployed and it is in action. How do we integrate the ITSM/Change management and logging mechanism?
Let me give an example, suppose we have SERVER1 for which we have created a configuration to make sure that ‘TapiSrv’ is always in ‘Stopped’ state. Now due to some requirement user X has created a change ticket to Start this service. He has started the service as per the Change Ticket successfully. Now, when the LCM triggers DSC Configuration to restore the service to it’s original state i.e. ‘Stopped’. User don’t have a clue why this has happened and we don’t have any Change ticket before LCM restores the service to it’s original state. This change was happened without a Change Ticket or any logging mechanism.
Can we integrate some code to be executed before LCM restores/reverts the changes made to the Service so that we can do two things, create a Change Ticket programmatically and creating a DB entry before actually restoring the configuration.
We can take care of writing code to create a change ticket and making DB entry but how we can trigger that code before LCM restores the configuration.
This will also help us generate a report about how many times the server drifted from the configuration and LCM has restored it back.
I don't know how to trigger some code before LCM brings anything back to it's original state.
A: You can do this by having LCM in consistency check only and then when reports arrive at your db connected to dsc server you create ticket, after procesing change ticket you will just invoke dsc apply manualy.
| |
doc_23533453
|
HTTP Status 500 - Provider org.glassfish.json.JsonProviderImpl not found
type Exception report
message Provider org.glassfish.json.JsonProviderImpl not found
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.json.JsonException: Provider org.glassfish.json.JsonProviderImpl not found
javax.json.spi.JsonProvider.provider(JsonProvider.java:97)
javax.json.Json.createObjectBuilder(Json.java:266)
NewServlet.doGet(NewServlet.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.ClassNotFoundException: org.glassfish.json.JsonProviderImpl
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1284)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1132)
java.lang.Class.forName0(Native Method)
java.lang.Class.forName(Class.java:190)
javax.json.spi.JsonProvider.provider(JsonProvider.java:94)
javax.json.Json.createObjectBuilder(Json.java:266)
NewServlet.doGet(NewServlet.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.3 logs.
Apache Tomcat/8.0.3
A: I managed to make it work in my webapp in NetBeans by manually installing the JSON Processing RI jar.
The complete procedure is:
*
*Download the jar: JSON Processing RI jar
*Right-click on Project --> Dependencies and add new dependency providing dummy Group ID, Artifact ID and Version number.
*Right-click on the newly created dependency and select "Manually install artifact", provide the downloaded jar
*Rebuild project, now it should work
A: The javax.json api (provided in the JSON Processing API jar) is good only for compiling the application.
If you want to run the application, you have to download the JSON Processing RI jar, as explained here: https://jsonp.java.net/download.html
The JSON Processing RI jar contains the org.glassfish.json.JsonProviderImpl class you are missing.
A: From this answer you could replace javax.json dependency by its org.glassfish implementation.
Maven repo, gives:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
| |
doc_23533454
|
const PIVOT_COLOR = '#FF4949';
const SORTED_COLOR = '#CB6BF9';
async function pivot(blocks, start = 0, end = blocks.length + 1) {
let pivot = Number(blocks[start].childNodes[0].innerHTML);
let swapIdx = start;
let value;
blocks[start].childNodes[1].style.backgroundColor = PIVOT_COLOR;
for (let i = start + 1; i < blocks.length; i++) {
value = Number(blocks[i].childNodes[0].innerHTML);
blocks[i].childNodes[1].style.backgroundColor = 'blue';
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 500)
);
if (pivot > value) {
swapIdx++;
let arr = [];
blocks.forEach(el => arr.push(el.childNodes[0].innerHTML));
console.log(arr);
//swap(arr, swapIdx, i);
await swap(blocks[swapIdx], blocks[i]);
}
blocks[i].childNodes[1].style.backgroundColor = SORTED_COLOR;
}
await swap(blocks[start], blocks[swapIdx]);
console.log(swapIdx)
blocks[start].childNodes[1].style.backgroundColor = SORTED_COLOR;
return swapIdx;
}
export async function QuickSort(blocks, left = 0, right = blocks.length - 1) {
if (left < right) {
let pivotIndex = await pivot(blocks, left, right);
//left
await QuickSort(blocks, left, pivotIndex - 1);
//right
await QuickSort(blocks, pivotIndex + 1, right);
}
}
function swap(el1, el2) {
let wrapper = document.getElementById('wrapper')
let container = wrapper.childNodes[0];
return new Promise((resolve) => {
var temp = el1.style.transform;
el1.style.transform = el2.style.transform;
el2.style.transform = temp;
window.requestAnimationFrame(function () {
// For waiting for .25 sec
setTimeout(() => {
container.insertBefore(el2, el1);
resolve();
}, 250);
});
});
}
var naming reference
When I swap swapIdx and i swap(blocks[swapIdx], blocks[i]) bars are not swapping in the correct swapIdx as shown in the image below but they are being inserted at the correct position in the DOM.
Image showing bars not swapping in the correct position
A: Two issues:
*
*Your code is not really swapping the DOM nodes with a call to insertBefore... Instead it rotates the elements that are in the range between the two given elements: element 2 is inserted before element 1, and that means that all elements that occured between element 1 and 2 are shifted.
*Your blocks array is left unchanged. Nothing is swapped there. Yet you should also swap the nodes in the blocks array, as that is the basis for your algorithm to perform comparisons.
To really swap two DOM elements, proceed as follows:
*
*create temporary dummy element
*call replaceWith to swap that element into the document and at the same time take the first element out.
*call replaceWith to swap that element (which was taken out) with the other element
*call replaceWith to swap the second element with the temporary element.
| |
doc_23533455
|
install(TARGET mytarget DESTINATION bin)
whereas I did recognise that the file() and configure_file() commands don't have an obvious way to be added to a target. But, this didn't work. So, given a simple CMakeLists.txt, such as the one below, how do I make all of the files (including the exmaple directory) appear in the archive?!
cmake_minimum_required(VERSION 2.6 FATAL_ERROR)
enable_language(FORTRAN)
add_executable(mytarget ${PROJECT_SOURCE_DIR}/myprog.for)
install(TARGETS mytarget DESTINATION bin)
add_custom_command(TARGET mytarget PREBUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${PROJECT_SOURCE_DIR}/examplefiles ${PROJECT_BINARY_DIR}/examplefiles)
set(CPACK_GENERATOR "TGZ")
include(CPack)
* I haven't yet found out which one of these 3 methods is actually (most?) correct - so any advice on this too will be hugely appreciated
A: As explained in the documentation of the CPack module, the binary installers created by CPack contain everything installed via CMake's INSTALL command. Thus the executable mytarget in your example will be included in the CPack archive, because you use the install command to copy it to the bin folder.
To also have CPack include the example folder in the generated archive, you can use the DIRECTORY variant of the install command in the following way:
install(DIRECTORY "${PROJECT_SOURCE_DIR}/examplefiles/" DESTINATION "example")
The file(COPY ...) and configure_file(...) do not have an effect on what is installed by CPack. Both command are usually used to copy files from the source tree to the binary tree upon configuring the CMake project.
Using add_custom_command with ${CMAKE_COMMAND} -E copy_directory ... will postpone the actual copying of files to the build time of the project. It will however not trigger the inclusion of the copied files in the CPack archive, either.
| |
doc_23533456
|
I have this php
$ImageLinks['image.png'] = 'http://www.example.com/r/redirect.php';
which redirects to the 'redirect.php' - which is the following
<?php $URL="http://thetargetlinktobeopenedinnewtab.com";
header ("Location: $URL");
exit();
?>
How can I make this $URL open in a new tab? I've tried placing the target="_blank" all over the place.
A: target is an HTML attribute; it has nothing to do with PHP redirects.
What you're attempting to do isn't possible. The header you're returning will redirect the user but it can't open a new tab.
A: You can try this out via javascript.
<script type="text/javascript" language="Javascript">window.open('http://www.example.com');
</script>
Now, you can use a javascript generator from php to convert this to PHP code.
Please note this will fail with a lot of the pop-up blockers around.
| |
doc_23533457
|
import React, { Component } from 'react';
import WelcomePage from './components/welcomePage';
import Register from './components/register';
import { StackNavigator } from 'react-navigation'
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import { Provider,connect } from 'react-redux';
import { store } from './store/store';
const mapStateToProps=state => {
return state;
}
const mapDispatchToProps=dispatch => {
return bindActionCreators(Actions, dispatch);
}
const handleSubmit=values=> {
console.log(values);
}
const Navigationapp=StackNavigator({welcome:{screen:WelcomePage},register:{screen:props=><Register {...props} handleSubmit={handleSubmit}>}});
const Container = connect(mapStateToProps,mapDispatchToProps)(Navigationapp);
export default class App extends Component{
render(){
return (<Provider store={store}>
<Container/>
</Provider>)
}
};
but it shows following error
error: bundling failed: SyntaxError in C:\wamp64\www\rnativeTestProj\App.js: C:/wamp64/www/rnativeTestProj/App.js: Unexpected token, expected } (42:12)
40 | const Container = connect(mapStateToProps,mapDispatchToProps)(Navigationapp);
41 | export default class App extends Component{
> 42 | render(){
| ^
43 | return (<Provider store={store}>
44 | <Container/>
45 | </Provider>)
BUNDLE [android, dev] ./index.js ░░░░░░░░░░░░░░░░ 0.0% (0/1), failed.
what am I missing?is it a correct way to wrap stack navigator inside a redux-provider?
A: screen:props=><Register {...props} handleSubmit={handleSubmit}>
You lost a closing slash, it should be <Register />.
| |
doc_23533458
|
<button onclick="location.href='<%#Eval("ReportLinks")%>'," title='<%#Eval("ReportLinks")%>'> Link</button>
A: Use a small t instead of a capital T for target like this:
<ItemTemplate><a href='LinkDetails.aspx?val1=total'><asp:Label ID="lblUsername" Fore-color="#1A0DAB" ToolTip="all links report" runat="server" Text='<%# Eval ("Total") %>' target="_blank"> </a></asp:Label>
</ItemTemplate>
A: <asp:TemplateField HeaderText="Total Unique Links">
<ItemTemplate><a href='LinkDetails.aspx?val1=total' Target="_blank"><asp:Label ID="lblUsername" ForeColor="#1A0DAB" ToolTip="all links report" runat="server" Text='<%# Eval ("Total") %>' ></asp:Label>
</a>
</ItemTemplate>
| |
doc_23533459
|
Or, visually:
Why does this code:
UIView *tableHeadView = self.tableView.tableHeaderView;
UILabel *tableHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 36, 320, 30)];
[tableHeaderLabel setTextAlignment:NSTextAlignmentCenter];
tableHeaderLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:18];
tableHeaderLabel.text = @"Questions"
UILabel *tableHeaderPrononce = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 320, 30)];
[tableHeaderPrononce setTextAlignment:NSTextAlignmentCenter];
tableHeaderPrononce.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15];
tableHeaderPrononce.text = @"test test test test";
[tableHeadView addSubview:tableHeaderLabel];
[tableHeadView addSubview:tableHeaderPrononce];
added to a UITableViewController viewDidLoad event (which contains a UISearchDisplayerController)
gives this lovely result in iOS6:
and this horrible terrible result in iOS7:
The behavior:
During normal mode the UILabels I added are not shown. while search is active the UILabels suddenly appear ON TOP OF the table cells and does not scroll away
In addition I am getting crashes while searching in iOS 7 which never occurred on iOS6. Probably not related to this piece of code but nevertheless I should mentioned that.
I tried all I could find on SO about fixing this issue but always something else breaks or disappears (mainly the UISearchBar).
Help
A: Look dude, before you modify your code or get frustrated with the behavior of the iOS7, it is advised to go through the UI Transition Guide given by apple.
After reading this you will get to know, why the grouped style tableView is looking annoying is not at all annoying from ios7 point of view. Each group extends the full width of the screen.
Moreover the UISearchBar behavior can be controlled if you read through Search Bar and Scope Bar
I hope that helps. Should you need all the code, please let us know. we can provide sample.
Here is Sample Code as Required Adding UISearchBar to View rather than TableViewHeader
*
*Adding UISearchBar to self.view
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f,0.0f, 320, 44.0f)];
searchBar.delegate = self;
searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
searchBar.searchBarStyle = UISearchBarStyleMinimal;
[self.view addSubview:searchBar];
*Adding UITableView to self.view
tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self.view addSubview:tableView];
*Creating and Adding UITableView.tableHeaderView
UILabel *tableHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 15)];
[tableHeaderLabel setTextAlignment:NSTextAlignmentCenter];
tableHeaderLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:18];
tableHeaderLabel.text = @"Questions";
tableHeaderLabel.alpha = 0.9;
UILabel *tableHeaderPrononce = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 320, 15)];
[tableHeaderPrononce setTextAlignment:NSTextAlignmentCenter];
tableHeaderPrononce.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15];
tableHeaderPrononce.text = @"test test test test";
tableHeaderPrononce.alpha = 0.7;
UIView *aHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[aHeaderView setBackgroundColor:[UIColor clearColor]];
[aHeaderView addSubview:tableHeaderLabel];
[aHeaderView addSubview:tableHeaderPrononce];
tableView.tableHeaderView = aHeaderView;
Here are the results:
SearchDisplayController
// Create search controller
searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchController.searchResultsDataSource = self;
searchController.searchResultsDelegate = self;
searchController.delegate = self;
A: You can do this simply by UITableViewDelegate method shown below:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
sectionHeaderView.backgroundColor = [UIColor grayColor];
UILabel *headerLabel = [[UILabel alloc] init];
[sectionHeaderView addSubview:headerLabel];
return sectionHeaderView;
}
| |
doc_23533460
|
from itertools import product
def multiply(res):
output = []
for i in res:
output.append(bin(int(i[0], 2) * int(i[1], 2))[2:].zfill(n * 2))
return output
arr = 0
val_x = []
val_y = []
if __name__ == "__main__":
while True:
try:
n = int(input('Enter n = '))
for x in range(n ** 2):
for y in range(n ** 2):
if y == 0:
arr += 1
if arr == 1:
val_x.append(bin(x)[2:].zfill(n))
val_y.append(bin(x)[2:].zfill(n))
arr = 0
res_xy = list(product(val_x, val_y))
#print(f'Input = {res_xy}')
res_z = (multiply(res_xy))
for index in range(len(res_z)):
value = res_z[index]
print(value)
#print(f'Output = {res_z}')
except (ValueError, KeyError,NameError) as e:
print(f'Invalid value or action ({e})')
print("Please enter valid integer value")
else:
break
filename = "rom_<a>x<b>.dat"
for r in (('<a>', f'{2**(2*n)}'), ('<b>', f'{2*n}')):
filename = filename.replace(*r)
fileobject = open(filename,'w')
fileobject.write(f'{(value)}')
fileobject.close()
When I run the script in the terminal I get all the values. For example if n=2, I get all the values from 0 to 15. But in the "rom_x.dat" file it reads only the 15th value, not the whole range. If I print "res_z" I can see all the values written, but they are in array and I need them enumerated in the write file.
A: Yes, because you generate a new value of value every time through the loop, and you print it at that time, but you're only writing the very last one -- whatever survives when you exit the loop. You have two choices, (1) open the file before the loop and do the fileobject.write in the loop at the same place you do the print, or (2) gather all the values into a list, and write the list to file after the loop. (1) is probably easier.
** Update **
Here is method 1:
from itertools import product
def multiply(res):
output = []
for i in res:
output.append(bin(int(i[0], 2) * int(i[1], 2))[2:].zfill(n * 2))
return output
val_x = []
val_y = []
if __name__ == "__main__":
filename = "rom_{0}{1}.dat"
while True:
try:
n = int(input('Enter n = '))
name = filename.format(f'{2**(2*n)}', f'{2*n}')
fileobject = open(name,'w')
for x in range(n ** 2):
arr = 0
for y in range(n ** 2):
if y == 0:
arr += 1
if arr == 1:
val_x.append(bin(x)[2:].zfill(n))
val_y.append(bin(x)[2:].zfill(n))
res_xy = list(product(val_x, val_y))
#print(f'Input = {res_xy}')
res_z = (multiply(res_xy))
for index in range(len(res_z)):
value = res_z[index]
print(value)
fileobject.write(f'{value}\n')
#print(f'Output = {res_z}')
except (ValueError, KeyError,NameError) as e:
print(f'Invalid value or action ({e})')
print("Please enter valid integer value")
fileobject.close()
| |
doc_23533461
|
The code is as follows:
const s3 = require('s3'); const client = s3.createClient({
maxAsyncS3: 100,
s3RetryCount: 3,
s3RetryDelay: 30000,
multipartUploadThreshold: 20971520,
multipartUploadSize: 15728640,
s3Options: {
accessKeyId: "xxxx",
secretAccessKey: "yyyy",
region: "us-east-2",
}, });
const params = {
localDir: "file-path",
s3Params: {
Bucket: "bucket-name",
Prefix: "images/image.jpg"
}, };
const uploader = client.uploadDir(params);
uploader.on('error', (err) => {
console.error("unable to upload:", err.stack);
});
uploader.on('progress', () => {
console.log("progress", uploader.progressMd5Amount,
uploader.progressAmount, uploader.progressTotal); });
uploader.on('end', () => {
console.log("done uploading"); });
The error which I get is:
unable to upload: Error: Non-file stream objects are not supported
with SigV4 in AWS.S3
A: You should pass the upload method a file.
Here is an example:
var file = files[0];
var fileName = file.name;
var albumPhotosKey = encodeURIComponent(albumName) + '//';
var photoKey = albumPhotosKey + fileName;
s3.upload({
Key: photoKey,
Body: file,
ACL: 'public-read'
}, function(err, data) {
if (err) {
return alert('There was an error uploading your photo: ', err.message);
}
alert('Successfully uploaded photo.');
viewAlbum(albumName);
});
}
More examples at: http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album-full.html
A: var params = {
ACL: 'public-read', // assign this rule for the readable permissions
Bucket: 'bucket-name-on-amazon-s3', // bucket name created on amazon s3
Key: Date.now() + "_" + path.basename(fullUrl) // assign filename
};
var body = fs.createReadStream(fullUrl);
var s3 = new AWS.S3({
params: params
});
s3.upload({
Body: body
}).
on('httpUploadProgress', function (evt) {
var progress = Math.round(evt.loaded / evt.total) * 100;
console.log('The progress ia '+progress);
}).
send(function (err, data) {
console.log(err, data);
//handle error
if (err) {
console.log("Error", err);
req.flash('error_msg', 'failed to upload the file meta-data');
res.redirect('/upload');
}
//success
if (data) {
console.log("Uploaded in:", data.Location); //url of the file on amazon s3
//build ad object
var person = new Person();
person.country = country;
person.save(function (err) {
if (err) {
req.flash('error_msg', 'failed to upload the file meta-data');
res.redirect('/upload');
} else {
// Do something - give alert to user, e.g. u can use flash messages as well
}
});
}
});
| |
doc_23533462
|
Start:127 stop:139 name:barackObama
Start:144 stop:148 name:born
Start:149 stop:163 name:August 4 1961
Now i got to check these 3 strings are in a same sentence or not by using BreakIterator.
BreakIterator splits the text into sentences with boundaries 0 to n. But here i have start an d end indexes of strings.How do i check these 3 strings located in a same sentence or not by using start and stop indexes.
I tried to print sentences splitted by BreakIterator
BreakIterator i=BreakIterator.getSentenceInstance(Locale.US);
i.setText(text);//HTML page text
for(int s=i.first(), e=i.next(); e>=0; s=e, e=i.next())
{
System.out.println("Sentence: from "+s+" to "+e+" \""+text.substring(s, e)+'"');
}
It prints all HTML lines in the following manner
Sentence: from 0 to 2 "<!"
Sentence: from 2 to 15 "DOCTYPE html>"
Sentence: from 0 to 46 "<html lang="en" dir="ltr" class="client-nojs">"
Sentence: from 0 to 6 "<head>"
**Sentence: from 0 to 95 "<dd><a href="/wiki/Barack_Obama" title="BarackObama">Barack Obama</a> born August 4, 1961</dd>"**
Sentence: from 0 to 5 "</dl>"
Sentence: from 0 to 5 "</dd>"
| |
doc_23533463
|
HTML :
<div class="searchBtn">
<input type="text" id="inputValue" placeholder="Search by name or #tag">
<button onclick="Search()" type="button">Search</button>
</div>
JS:
let filterSearch = $("#inputValue").val().toLowerCase();
function findAllImages(filter, start, itemsCount) {
let photos = [];
let tagSign = "#";
const searchByTag = filterSearch [0] === tagSign;
let searchCondition = searchByTag ? filterSearch.slice(1) : filter;
let newFiltered = imageArrayPhotos.filter(
searchByTag ? image => image.tag.indexOf(searchCondition) >= 0 :
image => image.title.toLowerCase().indexOf(searchCondition) >= 0);
for (let i = start; i < newFiltered.length; i++) {
photos .push(newFiltered [i]);
if (photos.length >= numberOfImages) {
break;
}
}
return photos ;
}
Can i do it with a callback function on let newFiltered = imageArrayPhotos.filter(function() {}) that goes through all the possibilities?
A: Why don't you use the regex. check if this is feasible.
let searchByTag = true;
let imageArrayPhotos = [{
tag: 'tree',
title: 'tree'
},
{
tag: 'forest',
title: 'tree'
},
{
tag: 'sky',
title: 'sky'
},
{
tag: 'bird',
title: 'bird'
},
{
tag: 'watertree',
title: 'sky'
},
];
let filterSearch = '';
let searchCondition = '';
let pattern;
let newFiltered = [];
function Search() {
newFiltered = [];
filterSearch = '';
searchCondition = '';
filterSearch = $("#inputValue").val();
filterSearch = filterSearch.split(',');
//searchCondition = searchByTag ? filterSearch.slice(1) : filter;
//newFiltered = imageArrayPhotos.filter(checkFilter);
filterSearch.forEach(function(item) {
item = $.trim(item);
searchByTag = item[0] == "#";
pattern = new RegExp("^" + $.trim(item).replace(/#/g, '') + "$");
let itemData = imageArrayPhotos.filter(checkFilter);
if (itemData.length > 0) {
newFiltered = newFiltered.concat(itemData);
}
});
console.log(newFiltered);
}
function checkFilter(image) {
return searchByTag ? pattern.test(image.tag) :
pattern.test(image.title)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="searchBtn">
<input type="text" id="inputValue" placeholder="Search by name or #tag">
<button onclick="Search()" type="button">Search</button>
</div>
| |
doc_23533464
|
Firstly, I needed to manipulate the results back from the database to show a more descriptive meaning:
(I am using a basic class for the key/value pair)
class WashBayDesc
{
public string Key { get; set; }
public string Text { get; set; }
}
Now I retrieve the data from a datareader and do the manipulation I need which then adds the results to a list item:
var washbaydata = new List<WashBayDesc>();
// Read through the available cashboxes and populate a list/combobox
while (rdr.Read())
{
string sWashBayDesc = null;
string sWB = rdr["washbay"].ToString();
if (sWB.StartsWith("3"))
{
sWashBayDesc = "Bay " + sWB.Substring(1);
}
else
{
sWashBayDesc = "Auto " + sWB.Substring(1);
}
washbaydata.Add(new WashBayDesc { Key = sWB, Text = sWashBayDesc });
}
// Now bind the hashtable (with our bay selectors) to the dropdown
cmbCashBoxes.DataSource = washbaydata;
cmbCashBoxes.ValueMember = "Key";
cmbCashBoxes.DisplayMember = "Text";
So.. the idea is I can simply bind the ComboBox datasource to the washbaydata list object.. this works fine.
The next part is to retrieve the selected item value (i.e. not the textual description, but the value or key itself). This is the bit I think maybe doesn't quite look right, although again it works...
WashBayDesc myRes = new WashBayDesc();
myRes = (WashBayDesc)cmbCashBoxes.SelectedItem;
string sWashBayCashBox = myRes.Key;
So the result is my string sWashBayCashBox has the selected key...
I guess it works, and that is fine, but is there an easier/more cleaner way?
A: string sWashBayCashBox = (string)cmbCashBoxes.SelectedValue;
| |
doc_23533465
|
A: I dont think the solution you are looking for is to use the different drawable resource folders for different screen densities but instead you should check this link: https://developer.android.com/topic/performance/graphics/load-bitmap.html on how to load the bitmaps more efficiently by downsampling before you load them into the Image View and by making sure you release any bitmap that isn't being used any longer.
A: You have to create different dimen , layout , images and icon files to support all devices.
changes in screen density.
xlarge screens are at least 960dp x 720dp
large screens are at least 640dp x 480dp
normal screens are at least 470dp x 320dp
small screens are at least 426dp x 320dp
Make this layout files, so that it will be same for all devices.
Give padding ,margin ,font and all properties as per devices.
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)
For Layout ,
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra-large in landscape orientation
For Images
res/drawable-mdpi/graphic.png // bitmap for medium-density
res/drawable-hdpi/graphic.png // bitmap for high-density
res/drawable-xhdpi/graphic.png // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png // bitmap for extra-extra-high-density
For Icon
res/mipmap-mdpi/my_icon.png // launcher icon for medium-density
res/mipmap-hdpi/my_icon.png // launcher icon for high-density
res/mipmap-xhdpi/my_icon.png // launcher icon for extra-high-density
res/mipmap-xxhdpi/my_icon.png // launcher icon for extra-extra-high-density
res/mipmap-xxxhdpi/my_icon.png // launcher icon for extra-extra-extra-high-density
For Launcher icon
36x36 (0.75x) for low-density
48x48 (1.0x baseline) for medium-density
72x72 (1.5x) for high-density
96x96 (2.0x) for extra-high-density
180x180 (3.0x) for extra-extra-high-density
192x192 (4.0x) for extra-extra-extra-high-density (launcher icon only; see note above)
Checkout Dimension and
Supporting Multiple Screens Official Documentaion.
| |
doc_23533466
|
# Todo.coffee
mongoose = require "mongoose"
Schema = mongoose.Schema
todoSchema = new Schema
title: String
desc: String
dueOn: Date
completedOn: Date
Todo = new mongoose.model("Todo", todoSchema)
I have a Todos class that is meant for other classes to use. (Not sure if its better to just use the Todo model tho?)
# Todos.coffee
Todo = require "Todo"
class Todos
byId: (id, callback) ->
Todo.findOne { _id: id }, callback
Then in my Mocha/should unit test ...
require "should"
Todos = require "../../../app/todos/Todos.coffee"
Todo = require "../../../app/todos/Todo.coffee"
describe "Todos", ->
describe "byId", ->
it "should return Todo with given ID", (done) ->
Todos.byId 1, (err, todo) ->
todo.should.be.an.instanceOf(Todo)
done()
But I am getting ...
$ mocha --compilers coffee:coffee-script tests/backend/todos/TodosTests.coffee
module.js:340
throw err;
^
Error: Cannot find module 'Todo'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/labs/Projects/Tickle/app/todos/Todos.coffee:4:10)
at Object.<anonymous> (/labs/Projects/Tickle/app/todos/Todos.coffee:20:4)
at Module._compile (module.js:449:26)
at Object.require.extensions..coffee (/usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:22:21)
What did I do wrong?
A: In Todos.coffee, your require of Todo needs to include a relative path so that it is looked for as a local file and not an installed node module.
Todo = require "./Todo"
| |
doc_23533467
|
class Entry(Base):
__tablename__ = 'entry'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255))
author_id = Column(Integer, ForeignKey('user.id'))
date = Column(DateTime)
content = Column(Text)
author = relationship('User', backref='entries')
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(Unicode(255))
...
As you can see this is very classical, users write entries...
I need to render some statistics about them (like show their entries per week/month...)
For counting entries i added a column_property to the user model like so:
class User(Base):
...
entries_count = column_property(select([func.count(Entry.id)]).\
where(Entry.author_id==id))
That let me showing how many entries has been writen by users.
But to make some statistics given a date range, i will need to adapt dynamically the entries_count to add the dates criterias.
So the question is : how would you do to manage the date criterias?? is column_property the best solution for that kind of need??
Thanks by advance.
A: Adding property is a good way to get some database state related to the object. But with external criterion parameter the count won't be just a state, but a function. Representing such data as object property won't be good. So query for additional data directly (counting antries newer than start_date in all examples below):
session.query(User, func.count(Entry.id))\
.outerjoin((Entry, (Entry.author_id==User.id) & (Entry.date>start_date)))\
.group_by(User.id)
Or define a helper method (not property!) in User class to simplify usage:
class User(Base):
# ...
@classmethod
def entries_count(cls, cond):
return select([func.count(Entry.id)])\
.where((Entry.author_id==cls.id) & cond)\
.as_scalar()
session.query(User, User.entries_count(Entry.date>start_date))
| |
doc_23533468
|
I'm using PHP to perform a MySQL search from a form input ($street). I have successfully made it so I can search by all road spelling variations (for example: 'street', 'st', 'st.') as below. I'd like the output array to be grouped by street. The below groups by each individual spelling. Is there a way my return groups can include all variations of the spellings?
My Code
<?php
$results = $db->prepare(
"SELECT * FROM entries
WHERE
street = :street
OR street = REPLACE(:street, 'st', 'street')
OR street = REPLACE(:street, 'st.', 'street')
OR street = REPLACE(:street, 'st.', 'st')
OR street = REPLACE(:street, 'street', 'st')
OR street = REPLACE(:street, 'street', 'st.')
GROUP BY street, house
")
$results->bindParam(':street', $street);
$results->execute();
$output = $results->fetchAll(PDO::FETCH_ASSOC);
return $output;
?>
Current example output
[1] Church Street
[1] 12 Church Street
[2] 25 Church Street
[2] Church St.
[1] 19 Church St.
Desired example output
[1] Church Street
[1] 12 Church Street
[2] 25 Church Street
[3] 19 Church St.
A: I think you have the same problem in your data that you are trying to take care of in your where clause. Rectifying addresses can be a challenge. Here is an attempt for this small example:
SELECT *
FROM entries
WHERE street = :street
OR street = REPLACE(:street, 'st', 'street')
OR street = REPLACE(:street, 'st.', 'street')
OR street = REPLACE(:street, 'st.', 'st')
OR street = REPLACE(:street, 'street', 'st')
OR street = REPLACE(:street, 'street', 'st.')
GROUP BY (case when street like '%st' then concat(street, 'reet')
when street like '% st.' then replace(street, ' st.', ' street')
else street
end), house;
EDIT:
You should be repeating the group by expression in theselect` clause:
SELECT (case when street like '%st' then concat(street, 'reet')
when street like '% st.' then replace(street, ' st.', ' street')
else street
end) as street, house
FROM entries
WHERE street = :street
OR street = REPLACE(:street, 'st', 'street')
OR street = REPLACE(:street, 'st.', 'street')
OR street = REPLACE(:street, 'st.', 'st')
OR street = REPLACE(:street, 'street', 'st')
OR street = REPLACE(:street, 'street', 'st.')
GROUP BY (case when street like '%st' then concat(street, 'reet')
when street like '% st.' then replace(street, ' st.', ' street')
else street
end), house;
| |
doc_23533469
|
I labeled the data as following: 2000 pairs as positive and 2000 pairs as negative but I want to make sure that the batches are balanced as well, ex: 64 batch means 32 positive & 32 negative.
the model take 6 inputs of the following shape: (3024, 1, 192, 192)
y_train shape = (1008, 1)
However when I tried to balance the batches the fit_gen expect an output of the following (x,y)
and I need an output as the following (x[:0]..X[:5],y) to fit it in the model
The following error occurred
Output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: (array([[[[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]],
I used the following formula to balance the batches:
img_1 = x_train[:, 0]
img_2 = x_train[:, 1]
img_3 = x_train[:, 2]
img_4 = x_train[:, 3]
img_5 = x_train[:, 4]
img_6 = x_train[:, 5]
gen = balanced_generator(x_train,img_1, img_2, img_3, img_4, img_5, img_6, y_train, 64)
modelMerged.fit_generator(gen, steps_per_epoch=1, epochs=epochs)
def balanced_generator(x,x1,x2,x3,x4,x5,x6, y, batch_size):
batch_x_shape = (batch_size, x.shape[1], x.shape[2], x.shape[3],x.shape[4])
batch_y_shape = (batch_size, )
batch_size1 = int(batch_size/2)
batch_x = np.ndarray(shape=batch_x_shape, dtype=x.dtype)
batch_y = np.zeros(shape=batch_y_shape, dtype=y.dtype)
for i in range(batch_size1):
ind1 = np.random.randint(0,y.shape[0])
while y[ind1] == 0:
ind1 = np.random.randint(0,y.shape[0])
batch_x[i,0,:,:,:] = x1[ind1,:,:,:]
batch_x[i,1,:,:,:] = x2[ind1,:,:,:]
batch_x[i,2,:,:,:] = x3[ind1,:,:,:]
batch_x[i,3,:,:,:] = x4[ind1,:,:,:]
batch_x[i,4,:,:,:] = x5[ind1,:,:,:]
batch_x[i,5,:,:,:] = x6[ind1,:,:,:]
batch_y[i] = y[ind1]
for i in range(batch_size):
i = int(batch_size/2)
ind2 = np.random.randint(0,y.shape[0])
while y[ind2] == 0:
ind2 = np.random.randint(0,y.shape[0])
batch_x[i,0,:,:,:] = x1[ind2,:,:,:]
batch_x[i,1,:,:,:] = x2[ind2,:,:,:]
batch_x[i,2,:,:,:] = x3[ind2,:,:,:]
batch_x[i,3,:,:,:] = x4[ind2,:,:,:]
batch_x[i,4,:,:,:] = x5[ind2,:,:,:]
batch_x[i,5,:,:,:] = x6[ind2,:,:,:]
batch_y[i] = y[ind2]
print("batch #")
yield(batch_x[:, 0],batch_x[:, 1],batch_x[:, 2],batch_x[:, 3],batch_x[:, 4],batch_x[:, 5], batch_y)
A: The fit_generator in keras only takes input as (X,Y) format, so you should concate your X output in yield part into a list in your customized generator function :
yield( [batch_x[:, 0],batch_x[:, 1],batch_x[:, 2],batch_x[:, 3],batch_x[:, 4],batch_x[:, 5]], batch_y) # <- Add []
| |
doc_23533470
|
A: No, you cannot use GL_RGB8 with image load/store. This is done because implementations are allowed to support GL_RGB8 by substituting it with GL_RGBA8. But they are also allowed to not do that if they can support 3-component formats directly. So OpenGL as a specification does not know if the implementation can actually handle 24-bits-per-pixel or if its pretending to do so with a 32-bit texture.
So OpenGL just forces you to do the substitution explicitly.
| |
doc_23533471
|
directoryListing = os.listdir(inputDirectory)
#other code goes here, it iterates through the list of files in the directory
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?
A: You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.
an example of a with statement:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
lines=file.readlines() #read all the lines in the file
#when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).
A: What you are doing is fine. With is indeed the preferred way for opening files, but listdir is perfectly acceptable for just reading the directory.
| |
doc_23533472
|
Thank you for your help.
A: You can achieve it by using UICollectionView inside your ViewController. Create a custom tab bar on your ViewController and set actions for each bar to navigate the pages on your UICollectionView.
You can manipulate your Custom UICollectionViewCell inside cellForItemAt to differentiate each page.
For UICollectionView tutorial you can check out this page: https://www.raywenderlich.com/9334-uicollectionview-tutorial-getting-started
I have created a view pager with a bottom tab bar, like instagram has, on one of my apps using this UICollectionView.
| |
doc_23533473
|
const spawn = require('child_process').spawn;
const script = require.resolve('./script_1.bat');
const bat = spawn(script);
/* program runs properly (for the most part) */
bat.stderr.on('data', (data) => {
console.log('stdErr: ' + data);
});
bat.on('exit', (code) => {
console.log('Child exited with code' + code);
});
The problem is that script_1.bat has a call command to script_2.bat in the same directory:
`call script_2.bat`
When I execute script_1.bat in the command line, it works fine. However, when I run script_1.bat from node, I see this in the console:
stdErr: 'script_2.bat' is not recognized as an internal or external command, operable program or batch file.
I have done my best to dig through the node child process documentation, but I could not find an explination for why this would happen. Is there a way to pass nested batch files into the spawn() method some how?
Thanks for your time.
A: Change this in the 1st batch:
call ./script_2.bat
| |
doc_23533474
|
I am loading ImageView's image through a URL using Volley library. I want to show the Framelayout i.e. FrameLayout's visibility should be set to visible only when the image is loaded successfully and not before it. I have implemented listener to listen to the image loading which set the FrameLayout's visibility to visible once image is loaded. But the problem is as RecyclerView recycles view, I am getting some FrameLayout's visibility as VISIBLE even if the ImageView isn't loaded.
Here is my onBindViewHolder code:
@Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position)
{
holder.topContainer.setVisibility(View.INVISIBLE);
holder.bottomContainer.setVisibility(View.INVISIBLE);
String poster = "some image url";
holder.mThumbnail.setImageUrl(poster, volleySingleton.getImageLoader());
/* Listener for listening to image loading*/
holder.mThumbnail.addOnLayoutChangeListener(new OnLayoutChangeListener()
{
@Override
public void onLayoutChange(View view, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7,
int arg8)
{
if(holder.mThumbnail.getDrawable()!=null)
{
holder.topContainer.setVisibility(View.VISIBLE);
holder.bottomContainer.setVisibility(View.VISIBLE);
}
else
{
holder.topContainer.setVisibility(View.INVISIBLE);
holder.bottomContainer.setVisibility(View.INVISIBLE);
}
}
});
}
| |
doc_23533475
|
<article>
<p>Some content here</p>
<ol class="footnotes">
<li id="footnote-1">Footnote 1 text</li>
<li id="footnote-2">Footnote 2 text</li>
</ol>
</article>
Is there an HTML5 container element more descriptive/semantic than a ol or div with class = "footnotes" (or is there an appropriate container that should be wrapping the ol element)? And, is there a text element more descriptive/semantic than a p or li for each individual footnote? If not, is there perhaps a microformat out there that at least establishes some common class names to use?
Note this question is not about the markup for footnote links - that's already been discussed and it appears that there is still no element in HTML to semantically identify a footnote link. I left out the footnote links and back-links from the sample markup here for brevity.
A: There isn't any dedicated mechanism yet, but footnotes either with linked, or simple footer notes with list elements as well as side notes can be merged into a common suggested alternative markups. You might have seen this already - "HTML5 Common Idioms without dedicated elements"
Sure it's more viable to wrap each footnotes within a <section> element if more than one occurs within a single <article>. If that's not the case you can wrap 'em within <footer> or <aside>. Then content elements follows as usual. Like <p> for descriptive segments.
Here is another example of "Footnotes with microformats"
| |
doc_23533476
|
I have been using Go to run some machine learning experiments on a large server, 512GB of main memory, which makes the 128GB limit set using a 37 bit address insufficient.
Previously I would edit malloc.h in the runtime package to change to 38 bit addresses but with the conversion from C to Go of the source I'm having difficulty finding if there is still something as simple to modify.
This commit that changed max memory to 128GB from 16GB shows the kind of change I am talking about https://code.google.com/p/go/source/detail?r=a310cb32c278
A: So I realized I did not find the file because I am not use to using the Google Code repo explorer. I located what are now 3 malloc.go files and have found the relevant section of code.
https://code.google.com/p/go/source/browse/src/runtime/malloc2.go#122
Honestly I think the update using 1 and 0 booleans and multiplication rather than simple if statements is overly confusing and doesn't convey what is going on as clearly as the header file used to.
Also thank you bamboon I only realized my mistake after reading the mailing list and getting linked to a different repo viewer.
| |
doc_23533477
|
int main()
{
char buf1[100] = "Hello";
char buf2[100] = "World";
char *ptr1 = buf1+2;
char *ptr2 = buf2+3;
strcpy(ptr1, buf2);
strcpy(ptr2, buf1);
cout << ptr1 << endl << ptr2 << endl;
return 0;
}
Try to solve without lookinkg on the answer:
World
HeWorld
Personally, I could not solve. I realized only the first few steps:
*
*Declares an array of type char dimension of 100 units. Arrays are initialized by text.
char buf1[100] = "Hello";
char buf2[100] = "World";
*Is declared a pointer ptr1, which will indicate the address of buf1 offset in two units. For clarity, we remove the two characters of buf1 and see that ptr1 points to the first letter l in the word Hello.
char *ptr1 = buf1+2;
*Cross out of buf2 first three characters and see that the pointer ptr2 points to the letter l in the word World.
char *ptr2 = buf2+3;
strcpy function is copying. I do not understand what and where copied.
A: The initial memory contents are:
buf1 buf2
v v
Hello World
^ ^
ptr1 ptr2
The strcpy function copies its second argument into the first.strcpy(ptr1, buf2) copies the contents of buf2 ("World") into ptr1. So now we have:
buf1 buf2
v v
HeWorld World
^ ^
ptr1 ptr2
strcpy(ptr2, buf1) copies contents of buf1 ("HeWorld") into ptr2. The result is:
buf1 buf2
v v
HeWorld WorHeWorld
^ ^
ptr1 ptr2
So in the end, ptr1 points to the string "World", and ptr2 points to the string "HeWorld".
A: As you mentioned that you know that ptr1 pointing to llo and ptr2 pointing to ld.
Now see the first strcpy
strcpy(ptr1, buf2);
this will copy World to buf1 frow where ptr1 points to, so it actually points World now. Hence printing ptr1 will print World.
Since buf1 (after decay) and ptr1 are pointing to the different elements (l (first) of Hello and l of world string respectively), any modification made to ptr1 will reflected to buf1. So, buf1[] now becomes HeWorld.
Since the original string has been modified and hence ptr2 is not pointing any longer to l. Now it points to W of the string HeWorld.
Now see the second strcpy.
strcpy(ptr2, buf1);
Now this will starts coyying HeWorld from where ptr2 points to. Hence printing ptr2 prints HeWorld.
| |
doc_23533478
|
I load it from
videoEl.src = "https://dl.dropboxusercontent.com/s/19evjn1svecnanr/big_buck_bunny_ns.mp4";
wait for 'canplaythrough' and then with click event
videoEl.currentTime = 1.0;
console.log(videoEl.currentTime); // gives 1
same scenario but local link:
videoEl.src = "http://localhost:8000/media/videos/video_test1/big_buck_bunny_ns.mp4";
videoEl.currentTime = 1.0;
console.log(videoEl.currentTime); // gives **0**
How? Why? Confused!
| |
doc_23533479
|
thank you in advance
A: RubyMotion only works on OSX.
As of today, the only way to create native applications on iOS is with a mac.
You could maybe take a look at PhoneGap to create some applications in HTML/css/js. But you still need a mac to submit the app to the app store.
Hope it helps.
| |
doc_23533480
|
the default constructor of "bpt::internal_node_t" cannot be referenced -- it is a deleted function
the structure goes like this:
struct internal_node_t {
typedef index_t * child_t;
off_t parent; /* parent node offset */
off_t next;
off_t prev;
size_t n; /* how many children */
index_t children[BP_ORDER];
};
references can be seen everywhere in bpt.cc, like this
internal_node_t parent;
I don't really get what the message means. How to make the code compiled in VS?
some type definition update:
struct key_t {
char k[16];
key_t(const char *str = "")
{
bzero(k, sizeof(k));
strcpy_s(k, str);
}
};
typedef unsigned int size_t;
struct index_t {
key_t key;
off_t child; /* child's offset */
};
I use off_t in <sys\types.h> and a marco #define bzero(ptr, size) memset(ptr, 0, size) for bzero
I also write another program like this:
#include <sys/types.h>
#include <string.h>
#define bzero(ptr, size) memset(ptr, 0, size)
struct key_t {
char k[16];
key_t(const char *str = "")
{
bzero(k, sizeof(k));
strcpy_s(k, str);
}
};
struct index_t {
key_t key;
off_t child; /* child's offset */
};
struct internal_node_t {
typedef index_t * child_t;
off_t parent; /* parent node offset */
off_t next;
off_t prev;
size_t n; /* how many children */
index_t children[20];
};
int main() {
internal_node_t t;
}
That works in VS2015.
A: I find it unlikely that a codebase that relies on POSIX types will compile in a compiler that targets Windows. Maybe you should try something like Cygwin.
For example, both off_t and key_t come from <sys/types.h>. The author didn't even bother including this header, giving a false sense of portability.
NOTE: VS2015 does have off_t. It seems the actual issue is System V IPC (<sys/ipc.h>, the actual header that cares about key_t) which is linux specific.
| |
doc_23533481
|
This is what I have in my code:
S.redirectTo("/manage/project", () => S.notice("Your entry has been saved"))
Instead of being redirected to http://myserver:8080/myapplicationname/manage/project I'm redirected to http://myserver:8080/myapplicationname/myapplicationname/manage/project (myapplicationname doubled). Everything else (Menus, SHtml.links etc) work just fine on the remote server. What could be the problem?
A: This is almost certainly something to do with Lift's interpretation of the context. You dont say what version of Lift or Tomcat you're using, but I would recommend looking at LiftRules.calculateContextPath. That is the rule function that is used throughout Lift's internals to determine how to undertake the redirect & rewriting.
Failing that, you may well have something screwy in your Tomcat setup. Alas, you simply dont provide enough information to debug this.
A: If you have Lift 2.4-M3 version, problem mentioned above might be associated with this Lift's open issue
| |
doc_23533482
|
python example.py runserver
nothing changes even if I clear the browser cache. I wonder if there is another command I can run it to apply the changes.
| |
doc_23533483
|
*
*question
*question
In many answers it does actually use this syntax. Thus my confusion.
Here is my handler:
async private void InstallStyleButton_Clicked(object sender, EventArgs e)
{
var customFileType =
new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
{
{DevicePlatform.macOS, new[] {"xsl"} }
});
var pickResult = await FilePicker.PickAsync(new PickOptions
{
FileTypes = customFileType,
PickerTitle = "Select template to install"
});
if(pickResult != null)
{
// Build target path
string targetFile = Path.Combine("/Users/Shared/VisitsRota.MacOS/Styles", pickResult.FileName);
// OK to install?
if(!File.Exists(targetFile))
{
// Install
File.Copy(pickResult.FullPath, targetFile);
// Add it
StylesPicker.ItemsSource.Add(pickResult.FileName);
// Select it
StylesPicker.SelectedItem = pickResult.FileName;
}
}
}
I realise it is not a good idea to hardcode the folder path and I will eventually get around to that. Other than that, my handler appears to operate fine on my development MacBook Pro when I try it.
Is my use of async void with the button handler ok? And if not, how should my handler be adjusted?
A: I found this link where it states:
To summarize this first guideline, you should prefer async Task to async void. Async Task methods enable easier error-handling, composability and testability. The exception to this guideline is asynchronous event handlers, which must return void.
So my code is OK.
| |
doc_23533484
|
Code:
//Convert temperatures between Fahrenheit and Celsius.
use std::io;
fn main() {
let c: bool = true;
let f: bool = false;
let mut temperatur = String::new();
println!("Gib die Temperatur an:");
io::stdin()
.read_line(&mut temperatur)
.expect("Konnte nicht gelesen werden");
let temperatur_int: i32 = temperatur.parse::<i32>().unwrap();
println!("{}", temperatur_int);
}
Error:
Gib die Temperatur an: 5 thread 'main' panicked at 'called Result::unwrap()on anErrvalue: ParseIntError { kind: InvalidDigit }', src/main.rs:17:57 note: run withRUST_BACKTRACE=1 environment variable to display a backtrace
Tried to parse String to Integer
A: You're doing the right thing, but you forgot that you will get a newline in your string when reading from stdin. So instead of '32' you will have '32\n', which cannot be parsed.
So do trim() additionally before the parsing:
let temperatur_int: i32 = temperatur.trim().parse::<i32>().unwrap();
| |
doc_23533485
|
For example, the session endpoint has a POST (log in, public) and a DELETE (log out, needs auth) method. Maybe I can split this two into a logout and login servlet but in the case I have resource endpoints that need auth to POST (create) and don't need auth to GET, a filter is impossible to apply and creating two separate servlets for each method is a pain to manage in a large scale app.
Is there a solution to this by just using servlets without any framework?
Apart from this, in the case I would apply the filter to "/secure" path, isn't this really user unfriendly? (To access a url that says "secure" or "public").
A: In servlets and filter specification, I am not aware of any way to do a mapping actually depending on the request type (GET/POST/PUT/DELETE...). One direct but intrusive way is to pass a string describing the request types that should be processed. In that case, if the request is not in those types, the filter should immediately call next element in filter chain.
If you do not want to change the authentification filter, you could imagine a wrapping filter that take the class of the actual filter as a parameter along with parameters to pass to the real filter. In that case, the wrapping filter will:
*
*at initialization time, create an instance of the real filter in initialize it
*at filter time test is the request is of an acceptable type and
*
*if not directly call the FilterChain
*if yes call the real filter with the current request, response and chain
A possible code for the wrapping filter could be:
public class WrappingFilter implements Filter {
Filter wrapped;
List<String> methods;
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
// process FilterConfig parameters "actual_filter" and "methods"
String classname = filterConfig.getInitParameter("actual_filter");
String methodsString = filterConfig.getInitParameter("methods");
methods = Arrays.asList(methodsString.split("|"));
try {
// create and initialize actual filter
Class<?> clazz = Class.forName(classname);
wrapped = (Filter) clazz.getConstructor().newInstance();
wrapped.init(filterConfig);
} catch (ClassNotFoundException ex) {
throw new ServletException(ex);
} catch (NoSuchMethodException ex) {
throw new ServletException(ex);
} catch (SecurityException ex) {
throw new ServletException(ex);
} catch (InstantiationException ex) {
throw new ServletException(ex);
} catch (IllegalAccessException ex) {
throw new ServletException(ex);
} catch (IllegalArgumentException ex) {
throw new ServletException(ex);
} catch (InvocationTargetException ex) {
throw new ServletException(ex);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String method = ((HttpServletRequest) request).getMethod();
if (methods.contains(method)) {
// appropriate method: call wrapped filter
wrapped.doFilter(request, response, chain);
}
else {
// directly pass request to next element in chain by-passing wrapped filter
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// destroys wrapped filter
wrapped.destroy();
}
}
The WrappingFilter filter should be normally declared in the web application. It should be passed directly through a FilterConfig in Java initialization, or indirectly through filter_params in Web.xml file :
*
*actual_filter: the class name of the actual filter to be wrapped by the WrappingFilter
*methods: a String giving the methods to process separated with |, for example POST|DELETE
*other parameters will be passed for the initialization of the wrapped filter
BEWARE: untested...
A: If you just need it for authentication perhaps you dont have to write a servlet filter. Specifying a SecurityConstraint either in web.xml or via @ServletSecurity you can restrict the constraint to certain http methods. See e.g. here and there.
But if you really have to write a filter the only way I know is to check the http method using httpRequest.getMethod() in your filter implementation, see eg.this answer.
A: I ended up creating a method addPublicFilter() that applies the filterPublicFilter to the path and methods you pass as arguments.
public class PublicFilter implements Filter {
private FilterConfig filterConfig;
public static final String PUBLIC_METHODS = "com.example.access.PUBLIC_METHODS";
static final String IS_PUBLIC = "com.example.access.IS_PUBLIC";
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final List<String> allowedMethods = Arrays.asList(filterConfig.getInitParameter(PUBLIC_METHODS).split(","));
final String method = ((HttpServletRequest) request).getMethod();
if (allowedMethods.contains(method)) request.setAttribute(IS_PUBLIC, true);
chain.doFilter(request, response);
}
public void destroy() {}
}
Then in Jetty I have the method:
private static void addPublicFilter(ServletContextHandler context, String path, String publicMethods) {
final FilterHolder holder = new FilterHolder(PublicFilter.class);
holder.setInitParameter(PublicFilter.PUBLIC_METHODS, publicMethods);
context.addFilter(holder, path, EnumSet.of(DispatcherType.REQUEST));
}
And I call it:
addPublicFilter(context, "/*", "OPTIONS");
addPublicFilter(context, "/user/*", "POST");
addPublicFilter(context, "/session", "POST,GET");
| |
doc_23533486
|
I preload the tscn files and main.add_child(item). How to delete this RigidBody node and its child nodes (RigidBody node with child nodes: a sprite node and a collider shape node)?
A: There isn't enough info, or just incomprehensible for me, but to delete node with it children, you just need to delete the they parent node.
get_node("your_rigid_body").free()
or
get_node("your_rigid_body").queue_free()
if you want to delete it in next frame. ( I'm not sure about the second one )
| |
doc_23533487
|
Let's say you have a QListWidget with blue icons. When you click on any items inside the QListWidget, the item will be highlighted with blue background color(the exact color identical to the color of the icons). In this way, the icon will be invinsible because all you will see is blue.
So in order to see the icon when the item is clicked and highlighted, I have to invert the color of the icon when clicked. My solution is to make another icon identical to the previous one but with white color. So when the item is clicked, the icon is supposed to turn white so that we could see the icon clearly. However, things go sideways and all we see is that:
I cannot understand why the icon is light blue when it is supposed to be white. Here are the two different color of icons I am talking about. They are in .png format.
Additional information:
In order to highlight the item when clicked, I used QSS. The code is as the following:
QListWidget
{
background-color: #ffffff;
border: none;
border-raduis: 10px;
font: 10.5pt "Microsoft Yahei";
outline: 0px;
padding-top: 55px;
}
QListWidget::item
{
background-color: transparent;
color: #000000;
border: 0px;
padding-left: 5px;
height: 38px;
}
QListWidget::item:selected
{
color: #ffffff;
background-color: rgb(46, 123, 253);
border-radius: 9px;
}
In order to change the icon when the item is clicked, I used the following code: (Actually I don't think the following code matters! If you want to learn more you can continue)
def change_icon(self):
icon_list = ['resources-inverted/all_music.png', 'resources-inverted/favourite_music.png',
'resources-inverted/recommended.png',
'resources-inverted/MV.png', 'resources-inverted/bilibili.png']
index = self.ui.listWidget.currentRow()
img = QImage(icon_list[index])
pixmap = QPixmap(img)
fit_pixmap = pixmap.scaled(23, 23, Qt.IgnoreAspectRatio,
Qt.SmoothTransformation)
self.ui.listWidget.item(index).setIcon(fit_pixmap)
self.ui.listWidget.setIconSize(QSize(23, 23))
self.set_list_icon(exception=index)
self.set_list_icon is a function that sets all the icons for the QListWidget. It takes in an arguement exception which tells the function which row of the QListWidget it should skip. The reason why I called this function at the end of the change_color function is that if you don't call such a function, when you click on another item in the QListWidget, the last item's icon color will remain white. But rather, we want to keep the icon's color blue when not selected.
The full project is at:https://github.com/Zhu-Aemon/music_gallery, including all the .png files, the .ui file and all the code. Thank you for your help!
| |
doc_23533488
|
constructor1()
{
// do something
}
constructor2() : this()
{
//do something else
}
Is there a reason that this is not allowed?
constructor1()
{
// do something
}
constructor2()
{
constructor1();
// do something else.
}
| |
doc_23533489
|
@app.route('/id_cap', methods=["GET", "POST"])
def id_cap():
if request.method == 'POST':
x = request.form["folio"]
print(x)
return redirect(url_for('page_red'))
return render_template("id_cap.html")
@app.route('/video_feed')
def video_feed():
encodes = pd.read_sql_table("Encodes", con=db.engine)
return Response(gen(encodes), mimetype='multipart/x-mixed-replace; boundary=frame')
#edit
@app.route('/enrollment', methods=["GET", "POST"])
def page_red():
with open(target, "rb") as f:
unpickler = pickle.Unpickler(f)
name = unpickler.load()
if name == "noname":
if request.method == 'POST':
params = {"nombre": request.form.get('textbox'), "folio": request.form.get('textbox2')}
encodes = pd.read_sql_table("Encodes", con=db.engine)
id_num = len(encodes)
encode_subj = functionist()#this make the encodes whit face_recognition library
encode_pd = encode_creation(encode_subj, id_num, params)
row_to_write = list(encode_pd.loc[0])
row_value_markers = ','.join(['?']*len(row_to_write))
db.engine.execute("INSERT INTO Encodes VALUES (%s)"%row_value_markers, row_to_write)
return redirect(url_for('index'))
return render_template("enrollment.html")
if name != "noname":
return redirect(url_for('index'))
return render_template("enrollment.html")
and in another file i have this other code
def gen():
doing some stuff with opencv to show camera....
url = 'http://0.0.0.0:5000/id_cap'
myobj = {'folio': folio}
x = requests.post(url, data = myobj)
(flag, encodedImage) = cv2.imencode(".jpg", frame)
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
sadly the page is not redirecting, in the console where the main.app is executed, when i go to the /id_cap page i get:
127.0.0.1 - - [02/Jun/2020 15:31:42] "GET /id_cap HTTP/1.1" 200 -
127.0.0.1 - - [02/Jun/2020 15:31:45] "GET /video_feed HTTP/1.1" 200 -
54254354
127.0.0.1 - - [02/Jun/2020 15:31:48] "POST /id_cap HTTP/1.1" 302 -
127.0.0.1 - - [02/Jun/2020 15:31:48] "GET /enrollment HTTP/1.1" 302 -
127.0.0.1 - - [02/Jun/2020 15:31:48] "GET / HTTP/1.1" 200 -
the integer line here is the x printed on the id_cap()so the post is recived by the app but then it is not redirected, any advice or help here will be welcome
| |
doc_23533490
|
Regards,
Sreenath
A: At this time, there is not a way to export the data feeding Recurly Analytics directly. Many merchants consume webhooks (https://docs.recurly.com/docs/webhooks) and/or Automated Exports (https://docs.recurly.com/docs#section-automated-exports) in order to build their own external analytics.
| |
doc_23533491
|
New thread code looks like this:
Thread newThread = new Thread(){
@Override
public void run() {
//My thread code
};
newThread.start();
This is what the thread code looks like, not going to copy and paste all the code it uses as it would be pointless but I'm wanting something like when
newThread.iscomplete {
//More code
}
Something along those lines
Thanks
A: Maybe you can show a message at the end of the Thread. Which would be helpful to let the user know that the process has finished.
Showing Message
System.out.print("Thread has finished!");
This would be at the last line, so it would only execute if all the above codes have been executed and the code has reached the last line for execution.
Thread newThread = new Thread() {
@Override
public void run() {
//My Thread code
System.out.print("Done!");
}
};
This will print Done! in the Console (I assume application is being run using a Console). Denoting that the code has been executed.
using a variable
boolean done = false;
Thread newThread = new Thread() {
@Override
public void run() {
//My Thread code
done = true;
}
};
Using EventListeners
Or else you can use Event Listener to detect the Thread completion. The above method was kind of simple.
http://docs.oracle.com/javase/tutorial/uiswing/events/
| |
doc_23533492
|
The working code is here: https://github.com/rkwright/ParticleTest. Works with XCode 12.3 and iOS 15.3
Here is the function that sets up the ParticleEngine via code.
func createTrailCode( color: UIColor ) -> SCNParticleSystem {
let particleSystem = SCNParticleSystem()
particleSystem.birthRate = 5000
particleSystem.particleLifeSpan = 1
particleSystem.warmupDuration = 1
particleSystem.emissionDuration = 500.0
particleSystem.loops = false
particleSystem.particleColor = color
particleSystem.particleSize = 0.25
particleSystem.birthDirection = .random
particleSystem.speedFactor = 7
particleSystem.emittingDirection = SCNVector3(0,1,1)
particleSystem.emitterShape = .some(SCNSphere(radius: 2.0))
particleSystem.spreadingAngle = 30
particleSystem.particleImage = "star"
particleSystem.isAffectedByGravity = true
particleSystem.acceleration = SCNVector3(0.0,-1.8,0.0)
return particleSystem
If you run the demo you'll see the ParticleEngine created from the scnp file works fine and the particles slowly drop as they are pulled by gravity. But for the engine created with code (above) the particles immediately zoom off the scene, no matter what the gravity or acceleraton is set to.
Still poking at this, but any suggestions would be appreciated. TIA
| |
doc_23533493
|
jquery.js
$('.menu_top').click(function(){
var href = $(this).attr('href');
$('#content_area').fadeOut().load(href).fadeIn('normal');
$('.menu_top').not(this).removeClass('active');
$(this).addClass('active');
return false;
});
Index.php
<a class="menu_top" href="#content_area">LINK 1</a>
<a id="content_area"style="display:none;">
THIS IS LINK ONE
</a>
<a class="menu_top" href="#content_area">LINK 2</a>
<a id="content_area"style="display:none;">
THIS IS LINK TWO
</a>
A: You need to use $(this).closest('a') for finding closest anchar after class="menu_top".
Documentation of .closest()
$('.menu_top').click(function(){
var href = $(this).attr('href');
$(this).closest('a').fadeOut().next('a').fadeIn('normal');
$('.menu_top').not(this).removeClass('active');
$(this).addClass('active');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="menu_top" href="#content_area">LINK 1</a>
<a id="content_area"style="display:none;">
THIS IS LINK ONE
</a>
<a class="menu_top" href="#content_area">LINK 2</a>
<a id="content_area"style="display:none;">
THIS IS LINK TWO
</a>
A: this solution worked for me
Index.php
<div class="menu_top" data-target="#content_area1">Link 1</div>
<div class="menu_top" data-target="#content_area2" >Link 2</div>
<div class="menu_top" data-target="#content_area3" >Link3</div>
<div id="content_area1" class="content_area" style="display:none;">
This is link 1
</div>
<div id="content_area1" class="content_area" style="display:none;">
This is link 2
</div>
<div id="content_area1" class="content_area" style="display:none;">
This is link 3
</div>
Jquery.js
$('.menu_top').click(function() {
var el=$(this)
$('.menu_top').removeClass('active')
$('.content_area').hide()
$($(this).data('target')).show('slow', function() {
$(el).addClass('active');
});
});
| |
doc_23533494
|
def create
@product = Product.friendly.find(params[:product_id])
@subscription = current_user.subscriptions.build(subscription_params)
if @subscription.save!
redirect_to product_subscriptions_subscription_path(subscription_id: @subscription.id, id: :overview)
else
render :new
end
end
When I use @product.subscriptions.build I get the following Error: Validation failed: User must exist
What did I do wrong ? What should I do ?
| |
doc_23533495
|
I verified error logs of apache and I found following errors
libpng warning: Ignoring attempt to set cHRM RGB triangle with zero area
Corrupt JPEG data: 234 extraneous bytes before marker 0xd9
The application is created on cakephp, the library for rendering pdf is tcpdg and staging and production servers are on ubuntu. I’ve consult some senior guys, they all are saying this is GD problem.
The environment on stage server
PHP 5.3.3-0.dotdeb.1 with Suhosin-Patch (cli) (built: Oct 1 2010 08:49:29)
Copyright (c) 1997-2009 The PHP Group
The environment on production server
PHP 5.3.2-1ubuntu4.18 with Suhosin-Patch (cli) (built: Sep 12 2012 19:12:47)
Copyright (c) 1997-2009 The PHP Group
Please recommend me any risk free solution.
A: There are some garbage bytes after the end of the image for any reason which stop it to work.
You can do a work around to find "\xFF\xD9" in your image bytes which represents EOI (End of Image) and where ever you find it chop the bytes after it. Hopefully this will work.
A: During diagnosis this issue. I noticed that ImageMagick module wasn't loaded on our staging server. That's why it was working on staging server. We disabled it from production server and it works. It was causing some conflicts with GD.
I commented out following extension
extension=imagick.so
Thanks anyways
| |
doc_23533496
|
Let's assume foo.py :
class A:
def a(self):
b()
#c()
@staticmethod
def b():
print("b called!")
def c():
print("c called!")
a=A()
a.a()
print(a.a)
print(type(A.b))
print(type(c))
Then when I access function b in a I will encounter error:NameError: name 'b' is not defined.
Can't function b be accessed inside method a? Both b and c are functions, only c can be accessed inside a.Why?
A: Try calling self.b() instead of b() when referring to the member function b of the class A. Each instance of A is a unique object, members and attributes of an instance can be referred to using self.
class A:
def a(self):
self.b()
c()
@staticmethod
def b():
print("b called!")
def c():
print("c called!")
We can refer to c without using self.c() as it is not a member of A. Member function b does not take self as the first argument, as a staticmethod does not call to or alter any other members of the object. Member function a is not considered a staticmethod of A, because it calls another member function (b) of the instance self.
(Note: self is not a keyword, but a widely used convention).
A: I think it is because of the b is the static method of the class A, not just a function from the outer scope. It has to be accessible with this syntax:
A.b()
| |
doc_23533497
|
I have tried working with the DesignerSerializationVisibility and its three settings. All I seem to be able to do with that is prevent Visual Studio from including the Image property at all, which causes my control to malfunction at run time.
I've looked into designing a custom CodeDomSerializer but I've not had any success with that at this point.
Is there any way to just tell Visual Studio to leave that property as it is and don't change it?
A: For those who have kindly taken the time to consider this item or who may visit this in the future, I have discovered the resolution. Someone prior to me had set this up, so I was unaware of what they had done.
So, the goal was to have a dll that contained images, and when/if those images changed, you could just swap out the dll and the various controls in the other projects would automatically pick up those changes at runtime by simply replacing that single dll.
The method requires setting up a project with nothing but the image resources. Then link (not copy) the resx file from that project to the other ones that are using it. Then, once you put the global:: references in the Designer.cs, they will stay in there unmolested by Visual Studio.
A: [DesignerSerializer(typeof(CustomCodeDomSerializer), typeof(CodeDomSerializer))]
public class BaseUserControl : UserControl
{
}
public class CustomCodeDomSerializer : CodeDomSerializer
{
public override object Serialize(IDesignerSerializationManager manager, object value)
{
var baseClassSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(BaseUserControl).BaseType, typeof(CodeDomSerializer));
var codeObject = baseClassSerializer.Serialize(manager, value);
if (codeObject is CodeStatementCollection collection)
{
for (var i = 0; i < collection.Count; i++)
{
var st = collection[i] as CodeVariableDeclarationStatement;
if (st?.Type.BaseType == typeof(ComponentResourceManager).FullName)
{
var ctr = new CodeTypeReference(typeof(MyCustomComponentResourceManager));
st.Type = ctr;
st.InitExpression = new CodeObjectCreateExpression(ctr, new CodeTypeOfExpression(manager.GetName(value)));
}
}
}
return codeObject;
}
/// <inheritdoc />
public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
{
CodeDomSerializer baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(BaseUserControl).BaseType, typeof(CodeDomSerializer));
return baseSerializer.Deserialize(manager, codeObject);
}
}
public class MyCustomComponentResourceManager : ComponentResourceManager
{
public MyCustomComponentResourceManager() : base()
{
}
public MyCustomComponentResourceManager(Type type) : base(type)
{
}
}
You can swap the ComponentResourceManager with your own one. This way, you can get your images from the database at runtime. The designer will still generate the .resx files with the images and everything else inside it, but it's not a problem since, at design time, you still want to show some default images and whatnot. If you don't like the .resx files, I think you can define your own implementation with the IResourceService and save your stuff to a database instantly, but I didn't test it. So I might be wrong. I had a similar problem, but with localization. If you are interested, you can read my answer Here. Note that the form designer only works with the BASE class. You need to inherit the BaseUserControl to make the custom CodeDomSerializer work. The BaseUserControl still uses the "old" CodeDomSerializer. Last I recommend that you read this answer about how the Designer works Here
| |
doc_23533498
|
Update Firewall rules
A: Based on your update and our comment conversation, I think you need to add a firewall rule. Below shows how to open all ports so any port is accessible on the VM to any outside user. Not great for security but should hopefully show this was the issue. Make sure not to run like this for production etc.
*
*Go to "Firewall" within "VPC Network" in GCP
*Click "Create Firewall Rule"
*Give it a name like "all"
*Change Targets to "All instances in the network"
*Change Source IP Ranges to 0.0.0.0/0
*Click "Allow all" on port ranges
You should be able to access SERVERIP:30177. This should work fine with NodePort in a VM (rather than using GKE) and the server suggests the port is listening with netstat -ntlp showing 0.0.0.0:30177.
| |
doc_23533499
|
Right now I encounter a probolemin the PAgination configuratino that is apparently not described earlier as far as I can ssee.
Probably the issue is not PAgination only related but more general. In my first attempt, I just filled the confiuration in the controller method and passed it to the initialize() method:
$config['base_url'] = $this->config->base_url() . "/categorie/{$catName}/";
$config['total_rows'] = $this->event_model->get_nrofevents_for_categorie($categorieObject->id, TRUE);
$config['per_page'] = 12;
$config['full_tag_open'] = '<div class="paging">';
$config['full_Tag_close'] = '</div>';
$config['prev_link'] = 'Vorige';
$config['next_link'] = 'Volgende';
$this->pagination->initialize($config);
And this works fine. But I have a buch of other pages that use the same pagination with most of its parameteres identical, only the base_url and the total_rows config properties are different for each page.
I have put the common configuration in the config/pagination.php configuration file but see no option to add the page-dependent properties in the code.
More general, is it possible to put generic configuration in a config file and add some customized properties in the controller method?
For me this seems logical but cannot figure out how...
I tried something like:
$this->load->config('pagination');
$this->config->set_item('next_link', 'blablabla');
but it seems that the Pagination is initialized immediately after reading the config file and this code has no effect.
Please any suggestions?
A: Since the initialize() only replaces the keys you provide, you can have your config/pagination.php hold the default values and call initialize() with the changing ones.
config/pagination.php
// put default values here
$config['next_link'] = 'Volgende';
$config['prev_link'] = 'Vorige';
// ...
controller
$this->pagination->initialize(array(
'base_url' => base_url().'categorie/'.$catName.'/',
'total_rows' => $totalRows,
// ...
)));
A: don't use base_url()... I always use site_url();
$config['base_url'] = site_url('');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.