id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23529000
|
I have the following code:
clear all
close all
clc
Data = {'2';'0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00';'3';'2.55059E+02 -1.51068E-01 1.98598E+01 3.05054E-02 -3.33973E+00 5.20304E+00';'4';'2.91592E+02 -1.60734E-01 2.65596E+01 1.18310E-02 -8.48549E-01 3.26528E+01';'5';'2.95371E+02 -8.31506E-03 2.73774E+01 -3.12620E-02 3.45210E-01 4.89854E+01';'6';'2.95163E+02 -3.67915E-02 2.73430E+01 5.67954E-03 3.93966E-01 4.91073E+01';'7';'2.91656E+02 3.63959E-02 2.86178E+01 -5.36138E-02 1.01910E+00 3.36354E+01';'8';'2.39894E+02 -5.92872E-02 2.53735E+01 1.04208E-02 2.55075E+00 7.28200E+00';'9';'1.56770E+02 6.15987E+01 3.07648E+01 -1.27722E+01 -6.82190E+00 4.29358E+00';'10';'3.14601E+01 2.74269E+01 -8.55639E+00 -3.92134E+00 -8.17611E+00 -7.48109E-01';'11';'-1.56914E+01 -2.33817E+00 -4.48457E+01 3.01897E+00 3.16196E-01 -6.26759E+00'};
A = Data(1:2:end,1);
B = Data(2:2:end,1);
A_new = cellfun(@str2num, A);
B_new = cellfun(@str2num, B);
M = [A_new B_new]
,but I get:
Error using cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
Error in ddd (line 11)
B_new = cellfun(@str2num, B);
A: Thanks to Dan:
A_new = cellfun(@str2num, A, 'UniformOutput', false);
B_new = cellfun(@str2num, B, 'UniformOutput', false);
M = [A_new B_new];
Result = cell2mat(M)
| |
doc_23529001
|
data_01_12_2014.
It is clear why this method would be undesirable, but presumably the reason is that the daily tables are enormous and this is a space management mechanism. Whatever the reason, my task is to grab data from these tables, do some transformations, and drop the results into a result table.
My problem is that I want to automate the process, and do not want to manually register the new daily table each day. Is there a way to automate this process in SAS/SAS DI?
Much gratitude.
A: What I do, is to create a macro variable, and give it the value "01_12_2014". You can then register the table in DI Studio with the physical name name "libref.Data_&datevar." Logical name can be anything.
Now the same job will work on the new names, just by changing the value of "datevar" macrovariable.
In the autoexec, a program can be written that sets the macrovariable dynamically. For example, this will set the value to todays date:
data _null_;
call symputx("datevar",translate(put(today(),DDMMYYD10.),"_","-"));
run;
%put &datevar;
Hope this helps!
A: I hope i'm not too late in answering the question. Just saw this question today only.
Anyhow, The most important thing that you need to remember is that the registered table showing up on the metadata folder/inventory are just shortcuts to the physical file. Let's say that the DI Studio job that you have is taking input from this table(registered on the metadata server as let's say MYDATA pointing to physical file data_2015_10_30 on 30th October).
On 31st October i can run the below code to update the shortcut to point to 31st dataset i.e data_2015_10_31. The tableID macro value is the Metadata ID of the table which shows in the Basic Properties panel( if it's not showing check View->Basic Properties . It should start showing on bottom left screen). Also, I'm hard coding 2015_10_31, but you can use macro to pick up today's date instead of hard coding. Leaving that to you.
%let tableID=A5LZW6LX.BD000006;
data _null_;
rc=metadata_setattr("omsobj:PhysicalTable?@Id ='&tableID'",
"SASTableName",
"DATA_2015_10_31");
rc=metadata_setattr("omsobj:PhysicalTable?@Id ='&tableID'",
"TableName",
"DATA_2015_10_31");
run;
PLEASE NOTE THAT DI STUDIO JOB CAN BE OPENED OR CLOSED WHILE YOU MAKE THE CHANGES OR RUN THE ABOVE CODE, BUT IF IT IS OPEN THEN CLOSE IT AND REOPEN IT AND IF THE JOB WAS CLOSED, JUST OPENING IT WOULD WORK. IF YOU DO NOT REOPEN THE JOB THEN TRANSFORMATIONS IN THE JOB WHICH ARE INTERACTING WITH THE DATASET MYDATA WOULD STILL PICK UP OLD TABLE NAME NOT THE UPDATED ONE. Also, The above code CANNOT be added as Precode since opening the job is updating all the linkages of the dataset to the new physical table in the transformations i.e. 31st October in the DI Job. You can created a new job with the above code and add it in the jobflow to run before you main job. If you would like to add it in precode then code to update becomes complicated and lengthy which i would avoid.
Good Reference Link : http://support.sas.com/resources/papers/proceedings09/097-2009.pdf
| |
doc_23529002
|
It seems that pandas.merge_asof allows only to join on one soft key and does not allow to specify hard key names separately for left and right tables (in case they are differently named and renaming isn't easy to process).
Consider the following two datasets
table1:
soft keys: sk1, sk2
hard keys: x, y
sk1,sk2,x,y,val1
10,100,10,15,1
20,200,20,25,2
30,300,10,10,3
table2:
soft keys: sk1,sk2
hard keys: k1,k2
sk1,sk2,k1,k2,val2,x,y
15,110,10,15,3,1,1
23,230,20,25,5,2,2
34,330,10,10,-1,3,3
I would need something equivalent to
soft_merge(t1, t2, left_by=["x","y"], right_by=["k1","k2"], on=[sk1, sk2], tolerance=[5,15])
to get output (showed vals only for clarity):
val1 | val2
1 | 3
I understand that instead of left_by and right_by for hard keys we can just
use by and rename columns, but this might not be easily supportable by a system since other system components might rely on old namings. Is there any clean and nice way of achieving it without multiple naming-renaming?
But the problem of joining on multiple soft keys still remain unclear ...
A: Implement the tolerances after an exact merge:
m = df1.merge(df2, left_on=["x","y"], right_on=["k1","k2"])
mask = (m.sk1_x - m.sk1_y).abs().le(5) & (m.sk2_x - m.sk2_y).abs().le(15)
m.loc[mask, ['val1', 'val2']]
# val1 val2
#0 1 3
This doesn't ensure a 1:1 merge, and will give all combinations that achieve that tolerance. If you need the "nearest" match you will need to specify some distance formula and keep only the closest. Here I use the total absolute distance. Assuming val1 is a unique key:
m['dist'] = (m.sk1_x - m.sk1_y).abs() + (m.sk2_x - m.sk2_y).abs()
m.sort_values('dist').loc[mask].drop_duplicates('val1')
| |
doc_23529003
|
Here is my data
Open High Low Close
2017-09-01 1.29360 1.29951 1.29052 1.29495
2017-09-03 1.29600 1.29660 1.29444 1.29535
2017-09-04 1.29536 1.29643 1.29124 1.29300
2017-09-05 1.29306 1.30440 1.29088 1.30331
2017-09-06 1.30331 1.30820 1.30181 1.30471
2017-09-07 1.30472 1.31381 1.30325 1.31319
2017-09-08 1.31319 1.32239 1.31233 1.31945
2017-09-10 1.31816 1.31978 1.31736 1.31769
2017-09-11 1.31769 1.32223 1.31593 1.31764
2017-09-12 1.31766 1.33145 1.31703 1.33097
2017-09-13 1.33096 1.33286 1.31836 1.32040
2017-09-14 1.32039 1.34055 1.31501 1.33955
2017-09-15 1.33955 1.36159 1.33922 1.35871
2017-09-17 1.35579 1.36029 1.35579 1.35921
2017-09-18 1.35921 1.36181 1.34646 1.35176
2017-09-19 1.35176 1.35515 1.34683 1.35178
2017-09-20 1.35178 1.36573 1.34517 1.34914
2017-09-21 1.34914 1.35861 1.34706 1.35761
2017-09-22 1.35760 1.35955 1.34496 1.34935
2017-09-24 1.34872 1.35339 1.34832 1.35261
2017-09-25 1.35262 1.35706 1.34308 1.34816
2017-09-26 1.34816 1.35139 1.34094 1.34385
2017-09-27 1.34386 1.34389 1.33634 1.33753
2017-09-28 1.33754 1.34551 1.33427 1.34159
2017-09-29 1.34160 1.34258 1.33497 1.33963
A: You can subset data easily within xts using a string date in the "YYYY-MM-DD/YYYY-MM-DD" format. So the max of the high column would be something like:
max(df.xts$High["2017-09-01/2017-09-04"])
If your data is in a dataframe called df.xts. You can also add the na.rm=T argument to the max function if there are NA values in your dataset, which will exclude those in computing the maximum rather than returning NA.
A: Is your Date column stored as row numbers?
Maybe want to load the data in a way that we have a Date column. Then this will work.
#Ensure Date Column is in Date format:
library(lubridate)
df$Date <- ymd(df$date)
# Subset by date
new.df <- subset(df, Date >= as.POSIXct("2017-09-01") & Date <= as.POSIXct("2017-09-04"))
# Find max
max(new.df$High)
| |
doc_23529004
|
Is it possible for any of the existing modal plugins to show the image outside this iframe, and within the window as a whole?
A: You need to reference parent.window so your modal is not confined to the iframe window.
| |
doc_23529005
|
tablename = clients
field = firstname CHAR(30)
And a Model much like this:
public class Clients
{
[StringLength(30)]
public string firstname { get; set; }
}
I know I can declare firstname as a DbString type and set IsAnsi and Length:
con.Execute(@" insert Clients(firstname) values(?firstname?)",
new { firstname = new DbString { Value = "John", IsAnsi = true, Length = 30 }});
But when I pass in the model above to dapper, it results in "Illegal attempt to convert Text Byte blob type" because dapper is assuming the string firstname is a text type rather than a fixed string:
con.Execute(@" insert Clients(firstname) values(?firstname?)", Clients);
I couldn't find any examples showing how to either:
*
*define the string length as a custom attribute in a model and inform dapper to use the customer attribute and define the string as a DbString with a length
*tell dapper to use the StringLength data annotation attribute in a model (It seems to me that this would be ideal since it is likely that validation is already in use and dapper could make a better assumption of the string)
I'm unsure if a shim is the proper usage for this case.
| |
doc_23529006
|
He uses Windows, and I use Mac and Windows, so it's not a big issue for me to port changes from one codebase to the other, or vice versa. But, at the same time, it's also not an issue to test functionality in a single codebase across multiple OSes for me.
Our initial prototype was coded in Python and Tkinter, which worked fairly well for testing. Of course though, they did not look native across platforms, and there was still a lot of conditional statements in the first place. We weren't expecting it to be great for cross-platform support, which is why we started looking for others.
A: You should strive to ensure that only the presentation code and implementation code of the data layer were platform-specific, the domain layer should be completely platform-independent, as well as the interfaces of the data layer. To avoid a large number of ifs, substitute different implementations of the view and data layer for the same interface
| |
doc_23529007
|
function startTimer(duration) {
desap = duration - (new Date).getTime() / 1000;
var timer = desap,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
return display;
}, 1000);
}
document.write(startTimer(999999999999999))
JSFiddle
A: Ideally, I would lean toward using the .textContent javascript property, rather than document.write:
var displayTimer = document.getElementsByClassName('display-timer')[0];
function startTimer(duration) {
setInterval(function() {
var timer = duration - (new Date).getTime() / 1000;
var minutes = parseInt(timer / 60, 10)
var seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
displayTimer.textContent = display;
}, 1000);
}
window.addEventListener('load',function(){startTimer(999999999999999);},false);
<div class="display-timer">
</div>
A: It does not return undefined as string. It just returns undefined and that is because there is no return statement in your code.
The return statement is inside callback of setInterval
Sample code
function startTimer(duration) {
desap = duration - (new Date).getTime() / 1000;
var timer = desap,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
return display;
}, 1000);
}
var a = startTimer(999999999999999);
document.write("Value of a is: ", a, " and type is: ", typeof(a))
If you wish to get timer, you can try something like this:
function startTimer(duration) {
desap = duration - (new Date).getTime() / 1000;
var timer = desap,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
return display;
}, 1000);
}
var a = startTimer(999999999999999);
document.write("Value of a is: ", a, " and type is: ", typeof(a))
And if you wish to show timer on UI, you should use callbacks:
function startTimer(duration, callback) {
desap = duration - (new Date).getTime() / 1000;
var timer = desap,
minutes, seconds;
setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
if(callback) callback(display);
}, 1000);
}
var a = startTimer(999999999999999, notify);
function notify(str){
document.getElementById("timerContent").innerHTML = str;
}
<div id="timerContent"></div>
Reference
*
*setInterval
*How to return value from setInterval/setTimeout
A: Why not just put the document.write inside the interval?
function startTimer(duration) {
var desap = duration - (new Date().getTime()) / 1000;
var timer = desap;
var minutes = 0;
var seconds = 0;
var display = "";
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs <br/>";
if (--timer < 0)
display = "Ended";
document.write(display);
}, 1000);
}
startTimer(999999999999999);
A: Try this code snippet, I disabled document.write because JSFiddle disallow the use of this function, instead I used console.log to display the output. You can change that later.
Edit : You are getting an undefined error because you are using an anonymous function and outside "setInterval" you don't have any return for your main function "startTimer"
function startTimer(duration) {
desap = duration - (new Date).getTime() / 1000;
var timer = desap, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
display = "Ended";
}
//document.write(display);
console.log(display);
return display;
}, 1000);
}
startTimer(999999999999999);
A: In OP code document.write(startTimer(999999999999999)) , you haven't return any variable so it will undefined ,even if you return it will get only one times because startTimer is only one time runs.setInterval has inside function so write document.write inside setInterval function of startTime will be valid .
<div id="timing"></div>
<script type="text/javascript">
var show = document.getElementById("timing");
function startTimer(duration) {
desap = duration - 1000;
var timer = desap;
clock = setInterval(function() {
var minutes, seconds,display;
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display = "Ends in " + minutes + " mins and " + seconds + " secs";
if (--timer < 0) {
clearInterval(clock);
display = "Ended";
}
else{
show.innerHTML = display;
}
},1000);
}
startTimer(999999999999999);
</script>
| |
doc_23529008
|
here is the code reduced to a min
from pylab import *
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import numpy as np
import itertools
a=1
B=4
L= B+a
Vmax= 50
Vpot = False
N = 1000 # number of points to take
psi = np.zeros([N,2]) # Wave function values and its derivative (psi and psi')
psi0 = array([0,1]) # Wave function initial states
Vo = 50
E = 0.0 # global variable Energy needed for Sch.Eq, changed in function "Wave function"
b = L # point outside of well where we need to check if the function diverges
x = linspace(-B-a, L, N) # x-axis
def V(x):
'''
#Potential function in the finite square well.
'''
if -a <=x <=a:
val = Vo
elif x<=-a-B:
val = Vmax
elif x>=L:
val = Vmax
else:
val = 0
return val
def SE(z, p):
state0 = p[1]
state1 = 1.0*(V(z) - E)*p[0]
return array([state0, state1])
def Wave_function(energy):
global E
E = energy
# odeint(func, y0, t)
# solve_ivp(fun, t_span, y0)
psi = solve_ivp(SE, [-B-a, L], psi0, max_step = ((B+a+L)/(N)))
return psi.y
def main():
# main program
f2 = figure(2)
plot(x, Wave_function(9.8)[0][:1000])
grid()
f2.show()
if __name__ == "__main__":
main()
this is what the code gives me in the end. the right side is okay but the left side is wrong. I depend on both sides working, not for visuals.
edit:
for charity this is what the potential function should look like:
the final graph should look similar to this:
A: Not sure if it helps but it may gives you a hint.
It is not that solve_ivp doesn't work for -x to 0, but your function V may be wrong. I noticed that the wave begins to appear after that V decreases from Vmax to 0.
This code :
%matplotlib inline
from pylab import *
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import numpy as np
import itertools
a=1.
B=4.
L= B+a
Vmax= 50.
N = 10000
E = 9.8
def V(x):
if -L <= x <= -B:
return Vmax
else:
return 0
def SE(z, p):
state0 = p[1]
state1 = (V(z) - E)*p[0]
return array([state0, state1])
def Wave_function():
return solve_ivp(SE, [-L, L], [0., 1.], max_step=2*L/N)
result = Wave_function()
plot(result.t, result.y[0], color='tab:blue')
gives you the "expected" output :
A: Your code seems Okay in general. However, given your figure for the potential energy, the value for Vo should be *Vo = 10. In addition, in your main function your are only plotting the wave function as the solution of the Schrodinger Equation. Bellow, is what I am proposing you as a possible solution to your problem assuming that I properly understood your concern:
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
import numpy as np
a=1
B=4
L= B+a
Vmax= 50
N = 1000 # number of points to take
psi = np.zeros([N,2]) # Wave function values and its derivative (psi and psi')
psi0 = np.array([0,1]) # Wave function initial states
Vo = 10 # Not 50, in order to conform your figure of the potential energy
E = 0.0 # global variable Energy needed for Sch.Eq, changed in
# function "Wave function"
b = L # point outside of well where we need to check if the function diverges
x = np.linspace(-L, L, N) # linspace(-B-a, L, N) # x-axis
def V(x):
'''
Potential function in the finite square well.
'''
if -a <=x <=a:
val = Vo
elif x<= -L: # -a-B:
val = Vmax
elif x>=L:
val = Vmax
else:
val = 0
return val
def SE(z, p):
state0 = p[1]
state1 = 1.0*(V(z) - E)*p[0]
return array([state0, state1])
def Wave_function(energy):
global E
E = energy
psi = solve_ivp(SE, [-B-a, L], psi0, max_step = ((B+a+L)/(N)))
return psi.y
def main():
# main program
plt.figure()
plt.subplot(121)
plt.plot(x, Wave_function(9.8)[0][:1000])
plt.grid()
plt.title("Wave function")
plt.xlabel(r"$ x $")
plt.ylabel(r"$\psi(x)$")
plt.subplot(122)
potential = np.vectorize(V) # Make the function 'V(x)' to also work on array
pot = potential(x) # Potential ernergy in the defined domain of 'x'
t = [-L, -a, a, L] # the singular value of x
y = potential(t) # the potential energy at thos singular value of 'x'
# But to conform your figure I'll just do y = 0 * y
plt.plot(x, pot, t, 0*y, 'ko')
plt.title("Potential Energy")
plt.xlabel(r"$ x $")
plt.ylabel(r"$V(x)$")
plt.show()
if __name__ == "__main__":
main()
The output figure is the following:
| |
doc_23529009
|
But in Chrome content script, I use
document.addEventListener("DOMContentLoaded", function(evt){console.log('domcontentloaded!')}, true);
It doesn't work, it can only catch loading event of the top window.
So is there anything different here between Firefox and Chrome?
A: This code should not work as you describe if executed in the top frame, even in Firefox.
The easiest way to achieve this would be to inject your content script in every frame.
Maybe the difference is that Firefox does it by default; in Chrome this is optional. Since the console is shared between frames/contexts, you get the (false!) impression that it comes from code in the top frame.
In the manifest:
"content_scripts" : [
{
"matches" : ["<all_urls>"],
"js" : ["content.js"],
"all_frames" : true,
"run_at" : "document_start"
}
]
Note: I'm putting "document_start" there as well since by default your scripts are injected after that event (so you're not guaranteed to catch it). For more information, see run_at parameter docs.
Using executeScript:
chrome.tabs.executeScript({file: "content.js", all_frames: true});
| |
doc_23529010
|
I am using calabash-ios and SVPullToRefreshView to do my functional tests.
Using swipe or scroll gestures in calabash, the 'Pull to refresh...' text label never changes to 'Release to refresh...'. This then doesn't fire my code after the pull down so unable to functionally test the result.
Tried:
record/playback has apparently been removed from iOS7 support for Calabash.
Any suggestions are welcome
| |
doc_23529011
|
How hard is apex to work with? I looked into it a bit, it does seem fairly straightforward, but is there more to it that I am not aware of? Also, I am a little surprised that there is no built in functionality to let you set up complex permissions?
A: I've been working in Apex since August now, and did 4 years of Oracle Forms before this, so PL/SQL wasn't an issue for me. HTML and Javascript i also knew, just not as in-depth, but i believe i've picked up nicely so far.
What i'm doing at the moment is migrating a bunch of old Oracle Forms to Apex. So far my experience is that it can be very easy and fast to pump out the basics, but making your pages more dynamical or user-friendly can eat away some time. Still, the framework is very solid, save for some niggles. For example, they have a javascript api, which handles a lot like jquery. I can mostly get done what i want to, and i think the most time i've "wasted" so far, has been getting javascript code to work the way i want it.
Recently i've also been implementing some authorisation, and i must say it isn't really that hard! You can provide some authorisation schemes, and simply apply those to pages, regions or items. I of course don't know what you really mean with 'complex' permissions ;) There is always the possibility of using the APIs and do manual calls to verify authorisation.
If you're really totally new, then simply head over to apex.oracle.com, and take the 2-day developer guide to get a quick feel for the environment. You'll have to request a workspace, can do the exercises, and play around a bit.
A: We were looking at apex a year ago. And canceled. It's easy to make standard things, but it's not convenient to develop something specific. May be, we were looking not very properly, indeed.
| |
doc_23529012
|
A: The MavenSession spans the entire build (mvn invocation), which may encompass multiple MavenProjects in a multi-module build. The build then goes through one or more phases, to which your custom plugin’s <execution> can be attached. Hope that explains things.
| |
doc_23529013
|
[✓] Flutter (Channel stable, 3.0.3, on Microsoft Windows [版本 10.0.22000.739], locale zh-TW)
[✗] Visual Studio - develop for Windows
✗ Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[✓] VS Code (version 1.68.1)
[✓] Connected device (1 available)
[✓] HTTP Host Availability
! Doctor found issues in 1 category.
But I already got visual studio 2022 installed with "Desktop development with C++" on my pc.
What I have tried:
*
*Switch the channel to Master
*Install visual studio 2019 with "Desktop development with C++"
*Restarting the PC
*Reinstall visual studio 2022 with "Desktop development with C++"
A: I was in the same situation as you.
I solved the problem by bringing vswhere up to date.
In my environment, the following paths are affected.
C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe
Here is the URL I used for reference
https://github.com/microsoft/vswhere/releases
https://github.com/flutter/flutter/issues/102451
| |
doc_23529014
|
If you're unsure what I mean, here's the drop shadow on a normal window:
And here's the Adobe Air app, which doesn't have a shadow:
Thanks for the help. :)
EDIT: Added images that actually show now.
A: The cookbooks on the adobe site outline a couple of ways of doing this:
Adding a drop shadow to a custom chrome window
| |
doc_23529015
|
I use a network script (social engine) for my little homepage. When i am logged in, it sets the default $_SESSION keys below:
array(
['__default'] =>
array(
['session.counter'] => 7
['session.timer.start'] => 1314860302
['session.timer.now'] => 1314860677
['user_email'] => '740dc176ae3c650327f94ab327916c07'
['user_pass'] => '3486851c47c9e92c72725a1046d87288'
['user_persist'] => FALSE
['user_id'] => 2
)
['user_id'] =>
['user_id2'] => 3
)
I program on my Windows machine (xampp) there i have no problem to do sth. like this $_SESSION['user_id'] = 2;
I know, normally i should not use the same key even though it is not in the same layer, but i used it... (next time i will not)
I would like to understand why on the online vserver (linux) with the same files, $_SESSION['user_id'] => is always empty. I can never set it. Setting sth. like $_SESSION['user_id2'] = 3; is no problem (ok is another key).
I really do not have any clue why. Sadly the admin there also do not have an idea to solve this.
Is there a setting in the php config or sth. i must activate to get the same behavior on both machines?
I would appreciate any help. Thank you
ruvenm
Ok i found the solution. register_globals is on for the vserver. After deactivating it, it works. Thought this setting will be deprecated?
A: Search your sources for user_id and $_SESSION['user_id'], they may be used elsewhere.
| |
doc_23529016
|
Task is get all products (If product is duplicate than sum of it's qty) and deduct wastage stock (If wastage product is duplicate than sum of it's qty).
I have two tables like,
1) manage_stock
2) manage_wastage
manage_stock
=> This table has p_id(Product ID) and many rows with product duplication's.
p_id p_name p_qty
1 Pro-1 10
2 Pro-2 15
3 Pro-3 8
1 Pro-1 15
manage_wastage
=> This table has p_id(Product ID) of manage_stock table. It is also many rows with product duplication's.
p_id w_qty
1 2
1 4
3 5
Desired Output
p_id p_name p_qty w_qty final_qty
1 Pro-1 20 6 14
2 Pro-2 15 0 15
3 Pro-3 8 5 3
Thank you very much.
A: You just have to compute the difference between the stock quantity and the wastage
SELECT s.p_id, s.p_name, SUM(p_qty), SUM(w_qty), SUM(p_qty) - SUM(w_qty) as final_qty
FROM manage_stock s
LEFT OUTER JOIN manage_wastage w
ON s.p_id = w.p_id
GROUP BY s.p_id, s.p_name
A: SELECT ms.p_id ,GROUP_CONCAT(ms.p_name)p_name ,SUM(ms.p_qty) p_qty ,SUM(mw.w_qty) w_qty,SUM(ms.p_qty)-SUM(mw.w_qty) final_qty FROM manage_stock ms
INNER JOIN manage_wastage mw on ms.p_id =mw.p_id
GROUP BY ms.p_id
Try above code.
As p_name always unique with p_id GROUP_CONCAT() only returns single name.
A: try this one
SELECT s.p_id, s.p_name, SUM(p_qty),SUM(ifnull(w_qty, 0)),SUM(p_qty - ifnull(w_qty, 0)) as total
FROM manage_stock s
left outer JOIN manage_wastage w
ON s.p_id = w.p_id
GROUP BY s.p_name
its work
| |
doc_23529017
|
Articles:
art_id | name
-------|--------------
1 | article1
2 | article2
3 | article3
Tags:
tag_id | description
-------|--------------
1 | Scientific
2 | Long
3 | Short
article_tags:
art_id | tag_id
-------|---------
1 | 1
1 | 2
2 | 1
2 | 3
3 | 1
3 | 2
3 | 3
The question is How to select all articles that are BOTH Scientific and Short?
Please note, it should be general for [2.N) tag combinations...
A: You can use the following query to get the result:
select a.art_id, a.name
from articles a
inner join article_tags at
on a.art_id = at.art_id
inner join tags t
on at.tag_id = t.tag_id
where t.description in ('Short', 'Scientific') -- tags here
group by a.art_id, a.name
having count(distinct t.tag_id) = 2 -- total count of tags here
See SQL Fiddle with Demo
Or this could be written:
select a.art_id, a.name
from articles a
inner join article_tags at
on a.art_id = at.art_id
inner join tags t
on at.tag_id = t.tag_id
group by a.art_id, a.name
having
sum(case when t.description = 'Short' then 1 else 0 end) >= 1 and
sum(case when t.description = 'Scientific' then 1 else 0 end) >= ;
See SQL Fiddle with Demo.
If you just want to return the article id, then you could just query the article_tag table:
select art_id
from article_tags
where tag_id in (1, 3)
group by art_id
having count(distinct tag_id) = 2
See SQL Fiddle with Demo
A: SELECT *
FROM articles
WHERE art_id IN
(
SELECT art_id
FROM article_tags
GROUP BY art_id
HAVING COUNT(art_id) > 1
)
| |
doc_23529018
|
To skip this I do that
devise_for :advertisers, :skip => :registrations
But issue is that edit_registration_path also skip with it. How I fix it?
A: You can do like this:
devise_for :advertisers, :skip => [:registrations]
as :advertiser do
get "/advertisers/edit" => "devise/registrations#edit", :as => :edit_advertisers_registration
put "/advertisers" => "devise/registrations#update", :as => :advertisers_registration
end
Hope this will help you .
| |
doc_23529019
|
So in the morning they need to click through hundreds of these. It doesn't appear that IE asks for each poll and some mornings there are only a dozen. We do not see this on Chrome or Firefox.
Is there anything I can do in my JavaScript to affect the number of recursive, modal security dialogs that need to be clicked through each morning?
| |
doc_23529020
|
Geometry has a synthesized property:
interface:
@interface Geometry : NSObject <drawProtocol, intersectionProtocol>
@property int geoLineWidth;
implementation:
@synthesize geoLineWidth;
Circle is a subclass of Geometry. The interface:
@interface Circle : Geometry
This code compiles, inside a method of Geometry, in Geometry.m
NSLog(@"%d", geoLineWidth);
This code does not compile, inside a method of Circle
NSBezierPath * thePath= [NSBezierPath bezierPath];
[thePath setLineWidth: geoLineWidth];
Use of undeclared identifier 'geoLineWidth'
However, this code compiles:
[thePath setLineWidth: [self geoLineWidth]];
Is this behavior intentional, or am I missing something ?
A: This is intentional. Your subclass only knows about the contents of the interface file (that's all you import, isn't it?), and in there all you have is the property declaration. That gives the compiler no reason to believe that there is an instance variable called GeoLineWidth.
A: In the subclass, instead of accessing the instance variable directly, you must actually use the accessor.
Change this:
[thePath setLineWidth: GeoLineWidth];
To this:
[thePath setLineWidth: self.GeoLineWidth];
[thePath setLineWidth: [self GeoLineWidth]];
To get the compiler to recognize the instance variable, you'd need explicitly to declare it in the superclass header file.
A: A) don't use caps for variables, looks like a class...
B) if an Ivar is public or protected a subclass can access with self->Ivar.
C) since you have properties, use them and everything will work out.
| |
doc_23529021
|
How do i check if the connection is already in a transaction? I am using Microsoft SQL Server Database File.
A: After some searching, I found this other Stack Overflow question. It turns out that you cannot nest transactions in ADO.NET. When you try, you probably end up starting two unrelated transactions, which gives the parallel transactions error.
To see if a connection is currently in a transaction, you could:
var com = yourConnection.CreateCommand();
com.CommandText = "select @@TRANCOUNT";
var trancount = com.ExecuteScalar();
This returns the number of nested transactions.
Note that you can nest transactions manually, without using the SqlTransaction object. For example:
var com = yourConnection.CreateCommand();
com.CommandText = "BEGIN TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "BEGIN TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "INSERT INTO TestTable (name) values ('Joe');";
com.ExecuteNonQuery();
com.CommandText = "COMMIT TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "ROlLBACK TRANSACTION";
com.ExecuteNonQuery();
com.CommandText = "SELECT COUNT(*) FROM TestTable";
Console.WriteLine("Found {0} rows.", com.ExecuteScalar());
This prints 0, because the nested transaction was aborted entirely.
A: Are you doing this from multiple threads? If so, then asking won't help because between the time you ask and the time you begin a new transaction, some other thread could have begun its own transaction. You will want to use a connection pool to avoid this sort of race condition.
A: You can check whether a transaction is already open by checking if cmd.Transaction is null.
Then wrap your code accordingly so if a transaction is already open, then the calling function owns that transaction and will commit it / roll it back appropriately.
//begin transaction unless one was already started
bool newTransaction = cmd.Transaction == null;
if (newTransaction) cmd.Transaction = cmd.Connection.BeginTransaction();
try {
// do Stuff Here
cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
// commit if it's our to commit
if (newTransaction) cmd.Transaction.Commit();
} catch (SqlException ex) {
if (newTransaction && cmd.Transaction != null) cmd.Transaction.Rollback();
throw;
}
Then the parent function can pass in a command and optionally choose to begin it's own transactional block, or if not, one will be created and commited by the called function.
| |
doc_23529022
|
Here's an example a test for a route:
describe 'post /sections with empty data' do
before do
params = {
:site_id => site.id,
:page_id => page.id,
}
post '/sections', params, @session
end
specify { last_response.status.should == 200 }
specify { json_response['id'].should_not be_nil }
specify { json_response['type'].should == default_section_type }
end
Each test will be using the same base URL, with the same session data, the only difference is the parameters, and what the responses should be. There's at least 4 tests (GET, POST, PUT, DELETE) per route, and usually more.
Is there a way of making these tests more manageable?
A: Without resorting to metaprogramimng, you can use nested describe blocks to override only the parameters you want:
describe "/sessions" do
before do
send(http_method, "/sessions", params, @session)
end
describe "with POST" do
let(:http_method) { :post }
describe "and empty data" do
let(:params) do
{ :site_id => site.id, :page_id => page.id }
end
specify { last_response.status.should == 200 }
specify { json_response['id'].should_not be_nil }
specify { json_response['type'].should == default_section_type }
end
describe "with non-empty data" do
let(:params) do
# relevant params
end
end
end
describe "with GET" do
let(:http_method) { :get }
# ...
end
end
A: Have no idea if this works but it can give you an idea of what you can do
describe ' /sections with empty data' do
before(:all) do
@params = {
:site_id => site.id,
:page_id => page.id,
}
end
after(:each) do
specify { last_response.status.should == 200 }
specify { json_response['id'].should_not be_nil }
specify { json_response['type'].should == default_section_type }
end
[:get, :post, :put, :delete].each do |http_method|
it "works with #{http_method}" do
send(http_method) '/sections', @params, @session
end
end
end
Update
Reading your question again made me realize that this is not what you actually asked for. If it doesn't help at all tell me so I delete it.
| |
doc_23529023
|
If I don't want to run the program on my own server, what type of company can offer me such a service where I can run my own apps?
I want to expand the current setup to a larger scale, so I want to make sure I am using good practices and keep hackers out.
Thanks
| |
doc_23529024
|
tr {
position: relative;
}
.ImgProd {
border: solid 3px dimgrey;
width: 180px;
height: 180px;
transition: .2s;
}
.filteredtable tbody tr,
.tablefilter {
display: none;
}
#class1.tablefilter:checked~table tbody tr.class1,
#class2.tablefilter:checked~table tbody tr.class2,
#class3.tablefilter:checked~table tbody tr.class3 {
display: table-row;
}
.tablefilter+label {
cursor: pointer;
background-color: #666;
color: #fff;
padding: 3px;
}
.tablefilter:checked+label {
background-color: #111;
}
/*hiermee zorgen we ervoor dat de image zoomt wanneer de gebruiker erover hovert*/
.ImgProd:hover {
transform: scale(2);
}
.tableProducten {
position: relative;
left: 6%
}
<h1>Onze producten</h1>
<!-- we gebruiken buttons als fitler element tussen de verschillende merken van auto's -->
<input type="checkbox" class="tablefilter" name="class1" id="class1" checked />
<label for="class1">Mercedes</label>
<input type="checkbox" class="tablefilter" name="class2" id="class2" checked />
<label for="class2">BMW</label>
<input type="checkbox" class="tablefilter" name="class3" id="class3" checked />
<label for="class3">Opel</label>
<table class="tableProducten">
<tr class="class1">
<td>
<img src="../resources/Mercedes/AMG_GT4.jpg" alt="AMG GT4" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/BenzSla.jpg" alt="BenzSla" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/Cla.jpg" alt="Cla" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/DEX.jpg" alt="DEX" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/Eklas.jpg" alt="Eklas" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/EQC.jpg" alt="EQC" class="ImgProd">
</td>
<td>
<img src="../resources/Mercedes/SUV.jpg" alt="SUV" class="ImgProd">
</td>
</tr>
<tr class="class2">
<td>
<img src="../resources/BMW/AC.jpg" alt="bmw AC" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/IX3.jpg" alt="IX3" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/M2.jpg" alt="M2" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/M5.jpg" alt="M5" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/M6.jpg" alt="M6" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/X1.jpg" alt="X1" class="ImgProd">
</td>
<td>
<img src="../resources/BMW/Z4.jpg" alt="Z4" class="ImgProd">
</td>
</tr>
<tr class="class3">
<td>
<img src="../resources/OPEL/Adam.jpg" alt="ADAM" class="ImgProd">
</td>
<td>
<img src="../resources/OPEL/Astra.jpg" alt="Astra" class="ImgProd">
</td>
<td>
<img src="../resources/OPEL/ComboL1.jpg" alt="ComboL1" class="ImgProd">
</td>
<td>
<img src="../resources/OPEL/Corsa.jpg" alt="Corsa" class="ImgProd">
</td>
<td>
<img src="../resources/OPEL/CorsaX.jpg" alt="CorsaX" class="ImgProd">
</td>
<td>
<img src="../resources/OPEL/MokkaX.jpg" alt="MokkaX" class="ImgProd">
</td>
</tr>
</table>
A: Use this in your CSS (you don't use the same class name in your selector that you have given your table in HTML)
.tableProducten tbody tr,
.tablefilter{
display:none;
}
| |
doc_23529025
|
I am getting below error,
chmod: changing permissions of '/root/.ssh/id_rsa': Read-only file system
I have already apply defaultmode & mode for the same but still it is not working.
volumes:
- name: gitsecret
secret:
secretName: git-keys
VolumeMounts:
- mountPath: "/root/.ssh"
name: gitsecret
readOnly: false
thank you
A: As you stated, your version of Kubernetes is 1.10 and documentation for it is available here
You can have a look at the github link @RyanDawson provided, there you will be able to find that this RO flag for configMap and secrets was intentional. It can be disabled using feature gate ReadOnlyAPIDataVolumes.
You can follow this guide on how to Disabling Features Using Feature Gates.
As a workaround, you can try this approach:
containers:
- name: apache
image: apache:2.4
lifecycle:
postStart:
exec:
command: ["chown", "www-data:www-data", "/var/www/html/app/etc/env.php"]
You can find explanation inside Kubernetes docs Attach Handlers to Container Lifecycle Events
A: There has been some back and forth over this but presumably you are on a k8s version where configmap and secret are read-only no matter how you set the flag - the issue is https://github.com/kubernetes/kubernetes/issues/62099 I think you'll need to follow the advice on there and create an emptyDir volume to copy the relevant files into.
| |
doc_23529026
|
{
"compilerOptions": {
"checkJs": true
}
}
And I can't find a way to cast something, like here:
The example above should work in Closure Compiler (unverified), as documented here. But I can't find the equivalent syntax for JavaScript Language Service.
I also tried with the following simpler statement, which does not work either:
let castedWindow = (/** @type {any} */(window)); // castedWindow: Window (I want `any`)
I'm asking how to do casts, and if someone happens to know where the syntax is documented (or, if undocumented, just how it works).
Is what I'm asking even possible?
Thanks for your time!
A: As of TypeScript 2.5, support for type assertion/cast syntax in checkJs/@ts-check mode has been introduced.
Type assertion/cast syntax in checkJs/@ts-check mode
TypeScript 2.5 introduces the ability to assert the type of
expressions when using plain JavaScript in your
projects. The
syntax is an /** @type {...} */ annotation comment followed by a
parenthesized expression whose type needs to be re-evaluated. For
example:
var x = /** @type {SomeType} */ (AnyParenthesizedExpression);
| |
doc_23529027
|
Invalid object name 'dbo.Employee'.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name
'dbo.Employee'.
Source Error:
An unhandled exception was generated during the execution of the current web
request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Here are my connection strings:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-HolidayTracker-20190122013056.mdf;Initial Catalog=aspnet-HolidayTracker-20190122013056;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="LotusWorksEntities" connectionString="metadata=res://*/Models.HolidayTrackerModel.csdl|res://*/Models.HolidayTrackerModel.ssdl|res://*/Models.HolidayTrackerModel.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-LAKNQGQ\CONORSQL;initial catalog=LotusWorks;user id=sa;password={"mypassword"};MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I'm not sure if I used these correctly when publishing as this is my first web app. It does get published but anytime I use a page which uses the database I get an error.
A:
Exception Details: System.Data.SqlClient.SqlException: Invalid object name
'dbo.Employee'.
This error means that EF uses an object (most likely a table) named dbo.Employee, which does not exist in the database.
Check your database and verify whether that table exists, or that you should be using a different table name.
Also, according to your description, the connection strings you provided are all local Sql database. As you want to publish to azure and view the page which uses the database, you need to use the Azure Sql Database to provide data. Here is a tutorial you could refer to.
After setting up Azure sql database, select Use this connection string at runtime(update destination web.config) option, so it will use the azure sql db connectionstring.
| |
doc_23529028
|
Then, is it also true that we also have always optimal solution if we accept the requests in the order of latest starting time?
I think it is false, because we would get a different schedule set, but I am wondering how I can come up with a more mathematical proof.
A: Scheduling by latest starting time is the same as:
*
*Reverse time (negate all the times and swap interval ends)
*Schedule by earliest finish time
*Reverse time again to restore the original intervals.
By symmetry, the maximum number of schedulable intervals is the same whether you reverse time or not, so if "earliest finish time" is optimal, then "latest start time" is optimal, too.
A: As a hint, imagine mirroring all the intervals, or pretending that time runs backwards. You know that the greedy “take the earliest finish time” will select the maximum number of intervals. If you sweep backwards in time, what’s the equivalent condition?
| |
doc_23529029
|
After click once on submit there will be 2 3 or 4 submissions.
For every submission I get this error message, but for the last submit I don't get it and the code is doing what is suppose to.
Redirected to [...]/projects/2/keywords/new
Completed 302 Found in 13ms (ActiveRecord: 3.1ms)
[2014-04-25 12:17:34] ERROR Errno::ECONNRESET: Connection reset by peer
I had to add data-no-turbolink='true' into my <a> tag to prevent the form doing what it does.
The problem is that I want to use turbolinks in those pages, because it makes everything super fast.
If necessary I will post my forms code.
A: The form was submitting multiple times because I was tracking with google tag manager forms submissions.
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-PQZJ2T"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-PQZJ2T');</script>
| |
doc_23529030
|
So when I scroll or go to page /kontakt I want to change class from "hamburger" to "hamburger active".
I also tried regex. Any ideas?
Here is code:
const HamMenu = ()=> {
const [sidebar, setSidebar] = useState(false)
const [burger, setBurger] = useState(false)
const url = window.location.href;
const showSidebar = () => setSidebar(!sidebar)
const changeColor = () => {
if((window.scrollY >= 60) || (url.indexOf("kontakt") > -1)){
setBurger(true);
} else {
setBurger(false);
}
}
window.addEventListener('scroll', changeColor);
return (
<StyledMenu>
<div>
<Link to="#" className={sidebar ? 'menu-bars open' : 'menu-bars'} >
<FontAwesomeIcon
icon={faBars}
size="2x"
className={burger ? 'hamburger active' : 'hamburger'}
onClick={showSidebar}
/>
</Link>
</div>
A: Dealing with window in Gatsby could be a little bit tricky because two fundamental reasons:
*
*window object is only defined in the browser, so it will work perfectly under gatsby develop but you will need to add a "hack" to avoid a code-breaking in the gatsby build (because there's no window in the Node server).
*Treating the window outside React ecosystem, may break the rehydration of the components. This means that React won't potentially know what components need to re-render on-demand, causing unmounted components, especially when navigating forward and backward using the browser's history.
There are a few workarounds to achieve what you're trying to do.
Gatsby, by default, provides a location prop in all top-level components (pages). So you can pass it to any child components at any time to change the class name based on its value:
const IndexPage = ({ location }) =>{
return <Layout>
<HamMenu location={location} />
<h1> some content</h1>
</Layout>
}
Then, in your <HamMenu> component:
const HamMenu = ({ location })=> {
const [sidebar, setSidebar] = useState(false)
const [burger, setBurger] = useState(false)
const url = window.location.href;
const showSidebar = () => setSidebar(!sidebar)
const changeColor = () => {
if((window.scrollY >= 60) || (url.indexOf("kontakt") > -1)){
setBurger(true);
} else {
setBurger(false);
}
}
useEffect(() => {
if(typeof window !== "undefined"){
const url = window.location.href
const changeColor = () => {
setBurger(window.scrollY >= 60 || url.contains("kontakt"))
}
window.addEventListener('scroll', changeColor)
return () => {
window.removeEventListener('scroll', changeColor)
}
}
}, [])
return (
<StyledMenu>
<div>
<Link to="#" className={sidebar ? 'menu-bars open' : 'menu-bars' location.pathname.includes("your-page")? ''some-class' : 'some-other-class' } >
<FontAwesomeIcon
icon={faBars}
size="2x"
className={burger ? 'hamburger active' : 'hamburger'}
onClick={showSidebar}
/>
</Link>
</div>
I would suggest another approach to get the scroll position rather than using directly the window, using React-based approach to avoid what I was pointing before (How to add a scroll event to a header in Gatsby).
However, I've fixed your initial approach, wrapping it inside a useEffect with empty deps ([]). This function will be triggered once the DOM tree is loaded, to avoid the code-breaking window use that I was talking about. Alternatively to url.indexOf("kontakt") > -1 you may want to use url.includes("kontakt") which is way more readable.
Regarding the rest, it's quite self-explanatory. Destructuring the location props you get access to a bunch of data, the pathname property holds the page name so based on that, you can add a ternary condition wherever you want, such as location.pathname.includes("your-page") ? ''some-class' : 'some-other-class' (includes is more semantic in my opinion).
As you see, I've fixed your approach but I've also added a React/Gatsby-based one, choose what makes you feel comfortable.
A: React components rendering server-side (such as during gatsby build) do not have access to window, and in order to avoid breaking hydration, the first render needs to match what is rendered server-side. For these reasons, you'll want to use useEffect to make client-side changes that rely on window after the component mounts.
Note that this solution is going to perform rather poorly since changeColor is calling setBurger on each scroll event, which prompts the component to be re-rendered (even if the value is the same). You'll want to add a debounce or throttle routine to mitigate this.
const HamMenu = ()=> {
const [burger, setBurger] = useState(false)
useEffect(() => {
const url = window.location.href
const changeColor = () => {
setBurger(window.scrollY >= 60 || url.contains("kontakt"))
}
window.addEventListener('scroll', changeColor)
return () => {
window.removeEventListener('scroll', changeColor)
}
}, [])
return (
<StyledMenu>
<div>
<Link to="#" className={sidebar ? 'menu-bars open' : 'menu-bars'} >
<FontAwesomeIcon
icon={faBars}
size="2x"
className={burger ? 'hamburger active' : 'hamburger'}
/>
</Link>
</div>
</StyledMenu>
)
}
| |
doc_23529031
|
CODE, ORG, TYPE, DATE are table columns.
SELECT COUNT(CODE) AS OK, ORG AS ORG
FROM EVENTS
WHERE (TYPE = 'A') and (DATE BETWEEN '2015-07-06' AND '2015-07-12')
GROUP BY ORG
The results are:
OK ORG
---------
93 1
292 2
51 3
The main problem is, there are a total of 6 Orgs, but they do not get listed because the COUNT have no rows to count because this week they couldn't work.
I need to always get the ORG listed, and if theres a valid COUNT value, show it, otherwise show 0. Something like this:
OK ORG
---------
93 1
292 2
51 3
0 4
0 5
0 6
Thanks for your help!
A: Can you please try this:
SELECT O.ORG AS ORG, SUM(ISNULL(E.CODE,0,1)) AS OK
FROM ORGANIZATIONS O
LEFT JOIN EVENTS E ON O.ORG = E.ORG
AND E.TYPE = 'A'
AND E.DATE BETWEEN '2015-07-06' AND '2015-07-12'
GROUP BY O.ORG
A: You need to fetch first all ORG from EVENTS and the do a LEFT JOIN:
SELECT
ISNULL(COUNT(e.CODE), 0) AS OK,
t.ORG AS ORG
FROM(
SELECT DISTINCT ORG FROM EVENTS
)t
LEFT JOIN EVENTS e
ON e.ORG = t.ORG
AND e.TYPE = 'A'
AND e.DATE BETWEEN '2015-07-06' AND '2015-07-12'
GROUP BY t.ORG
| |
doc_23529032
|
A: Models should not be aware they're operating in a web environment.
What you might want to consider instead is just storing the FB UID on the model the same way as any other property, by setting it on the model during creation.
| |
doc_23529033
|
While I am building a library, I am getting an error like 'tree.h not found'.
I suppose this is a standard header file in C and C++. This raised in me the curiosity to know all the header files and their contribution.
Is there a place I can search for?
I am working on Solaris Unix.
A: http://www.cplusplus.com/reference/ lists all the standard C++ headers and the C++ wrappers of C header files.
tree.h is not part of the standard library.
A: I found this Wikipedia entry on the C standard library which contains, lists of C header files and detailed information on which standard they're part of. That gives you a nice historical perspective and some other, similar details.
Of course that's just C. There's a similar article to be found under "C++ standard library". That also has references to some other libraries which may not be "standard" per se but without which C++ would feel "crippled" to some people used to working with the extensions.
A: Try here : http://en.cppreference.com/w/
However, you may also be refering to the header files of your OS. These can be found either on MSDN (Windows) or by man command (POSIX systems). Or another source if you're on another OS.
A: The header 'tree.h' is not standard anywhere.
C Standards
ISO/IEC 9899:1990 (C89, C90)
The 15 standard headers in C89 are:
<assert.h> <limits.h> <signal.h> <stdlib.h>
<ctype.h> <locale.h> <stdarg.h> <string.h>
<errno.h> <math.h> <stddef.h> <time.h>
<float.h> <setjmp.h> <stdio.h>
ISO/IEC 9899:1990/Amd.1:1995
The 3 extra headers introduced in C94* (Amendment 1) are:
<iso646.h> <wchar.h> <wctype.h>
ISO/IEC 9899:1999 (C99)
The 6 extra headers in C99 are:
<complex.h> <inttypes.h> <stdint.h> <tgmath.h>
<fenv.h> <stdbool.h>
ISO/IEC 9899:2011 (C11)
The 5 extra headers in C2011 (for a total of 29) are:
<stdalign.h> <stdatomic.h> <stdnoreturn.h> <threads.h> <uchar.h>
ISO/IEC 9045:2008 (POSIX 2008, Single Unix Specification)
Note that POSIX requires many more headers (82, including all the C99 headers). The list below repeats the standard C (C99) headers. Windows requires a different set of headers, of course.
<aio.h> <libgen.h> <spawn.h> <sys/time.h>
<arpa/inet.h> <limits.h> <stdarg.h> <sys/times.h>
<assert.h> <locale.h> <stdbool.h> <sys/types.h>
<complex.h> <math.h> <stddef.h> <sys/uio.h>
<cpio.h> <monetary.h> <stdint.h> <sys/un.h>
<ctype.h> <mqueue.h> <stdio.h> <sys/utsname.h>
<dirent.h> <ndbm.h> <stdlib.h> <sys/wait.h>
<dlfcn.h> <net/if.h> <string.h> <syslog.h>
<errno.h> <netdb.h> <strings.h> <tar.h>
<fcntl.h> <netinet/in.h> <stropts.h> <termios.h>
<fenv.h> <netinet/tcp.h> <sys/ipc.h> <tgmath.h>
<float.h> <nl_types.h> <sys/mman.h> <time.h>
<fmtmsg.h> <poll.h> <sys/msg.h> <trace.h>
<fnmatch.h> <pthread.h> <sys/resource.h> <ulimit.h>
<ftw.h> <pwd.h> <sys/select.h> <unistd.h>
<glob.h> <regex.h> <sys/sem.h> <utime.h>
<grp.h> <sched.h> <sys/shm.h> <utmpx.h>
<iconv.h> <search.h> <sys/socket.h> <wchar.h>
<inttypes.h> <semaphore.h> <sys/stat.h> <wctype.h>
<iso646.h> <setjmp.h> <sys/statvfs.h> <wordexp.h>
<langinfo.h> <signal.h>
Note, too, that X/Open Curses requires another set of headers. There was a new version (Release 7) of that specification released in November 2009 (the first update since 1996 — the primary differences are the loss of official support for termcap and pre-standard C <varargs.h> header).
<curses.h> <term.h> <uncntrl.h>
Linux Standards Base
There are other headers that you might need to use. For example, there is no mention of <getopt.h> in these lists, but if you are using GNU Getopt (for long options, for example), you will need and use that header. It is standard on Linux according to the LSB, Linux Standards Base. An older version of the LSB was defined as ISO/IEC 23360:2006 in multiple parts; as of 2014-09-21, the current version of the LSB is 4.1 but version 5.0 is in beta. There is a section of the document that defines which headers are included, but there is no convenient table of the headers in the version I looked at. It is closely aligned with POSIX, but has extra facilities beyond what POSIX defines.
C++ Standards
ISO/IEC 14882:1998 (C++98)
The standard lists 32 headers specific to C++:
<algorithm> <iomanip> <list> <ostream> <streambuf>
<bitset> <ios> <locale> <queue> <string>
<complex> <iosfwd> <map> <set> <typeinfo>
<deque> <iostream> <memory> <sstream> <utility>
<exception> <istream> <new> <stack> <valarray>
<fstream> <iterator> <numeric> <stdexcept> <vector>
<functional> <limits>
There are also 18 headers corresponding to headers from C (corresponding to C94):
<cassert> <ciso646> <csetjmp> <cstdio> <ctime>
<cctype> <climits> <csignal> <cstdlib> <cwchar>
<cerrno> <clocale> <cstdarg> <cstring> <cwctype>
<cfloat> <cmath> <cstddef>
Intriguingly, Annex D (§D.7) lists a deprecated header, <strstream>, that is not mentioned earlier in the standard. Including that header with GCC (g++) 7.2.0 generates a warning:
/opt/gcc/v7.2.0/include/c++/7.2.0/backward/backward_warning.h:32:2:
warning: #warning This file includes at least one deprecated or antiquated
header which may be removed without further notice at a future date.
Please use a non-deprecated interface with equivalent functionality
instead. For a listing of replacement headers and interfaces, consult
the file backward_warning.h. To disable this warning use -Wno-deprecated. [-Wcpp]
The header <strstream> is explicitly listed in the other versions of the standard.
ISO/IEC 14882:2011 (C++11)
The 53 C++ headers in C++11 are:
<algorithm> <initializer_list> <numeric> <system_error>
<array> <iomanip> <ostream> <thread>
<atomic> <ios> <queue> <tuple>
<bitset> <iosfwd> <random> <type_traits>
<chrono> <iostream> <ratio> <typeindex>
<codecvt> <istream> <regex> <typeinfo>
<complex> <iterator> <scoped_allocator> <unordered_map>
<condition_variable> <limits> <set> <unordered_set>
<deque> <list> <sstream> <utility>
<exception> <locale> <stack> <valarray>
<forward_list> <map> <stdexcept> <vector>
<fstream> <memory> <streambuf>
<functional> <mutex> <string>
<future> <new> <strstream>
The 26 headers related to C (C11) are:
<cassert> <cinttypes> <csignal> <cstdio> <cwchar>
<ccomplex> <ciso646> <cstdalign> <cstdlib> <cwctype>
<cctype> <climits> <cstdarg> <cstring>
<cerrno> <clocale> <cstdbool> <ctgmath>
<cfenv> <cmath> <cstddef> <ctime>
<cfloat> <csetjmp> <cstdint> <cuchar>
ISO/IEC 14882:2014 (C++14)
Provisional list of headers based on draft standard N3797 found at ISO/IEC JTC1/SC22/WG21 site. The data is from tables 14 and 15 in section 17.6.1.2 Headers, amended as noted below. Since the standard has not been published (as of 2014-09-21), this list is not yet definitive.
The 54 C++ headers in C++14 are:
<algorithm> <initializer_list> <numeric> <strstream>
<array> <iomanip> <ostream> <system_error>
<atomic> <ios> <queue> <thread>
<bitset> <iosfwd> <random> <tuple>
<chrono> <iostream> <ratio> <type_traits>
<codecvt> <istream> <regex> <typeindex>
<complex> <iterator> <scoped_allocator> <typeinfo>
<condition_variable> <limits> <set> <unordered_map>
<deque> <list> <shared_mutex> <unordered_set>
<exception> <locale> <sstream> <utility>
<forward_list> <map> <stack> <valarray>
<fstream> <memory> <stdexcept> <vector>
<functional> <mutex> <streambuf>
<future> <new> <string>
The 26 headers related to C (C11) are unchanged compared with C++11:
<cassert> <cinttypes> <csignal> <cstdio> <cwchar>
<ccomplex> <ciso646> <cstdalign> <cstdlib> <cwctype>
<cctype> <climits> <cstdarg> <cstring>
<cerrno> <clocale> <cstdbool> <ctgmath>
<cfenv> <cmath> <cstddef> <ctime>
<cfloat> <csetjmp> <cstdint> <cuchar>
There is one new header listed for C++14 compared to C++11, namely <shared_mutex>.
NB: The draft lists a number of the headers (<deque>, <istream>, <stdexcept>, <unordered_set>) twice. Also, 5 headers from C++11 are not listed in the tables in the draft, namely <exception>, <iterator>, <ratio>, <scoped_allocator>, and <thread>. Since §18.8 defines <exception>, §24 defines <iterator>, §20.11 defines <ratio>, §30 defines <thread>, and §30.4 defines <shared_mutex>, this is an example of why you should not trust the draft standards as being the final word — they contain errors.
ISO/IEC 14882:2017 (C++17)
Provisional list of headers in C++17 based on the draft N4659 dated 2017-03-21. This is a transcription of tables 16 and 17 from section 20.5.1.2 Headers. This is not the final standard; in theory, something could change.
There are 61 C++ headers:
<algorithm> <future> <numeric> <strstream>
<any> <initializer_list> <optional> <system_error>
<array> <iomanip> <ostream> <thread>
<atomic> <ios> <queue> <tuple>
<bitset> <iosfwd> <random> <type_traits>
<chrono> <iostream> <ratio> <typeindex>
<codecvt> <istream> <regex> <typeinfo>
<complex> <iterator> <scoped_allocator> <unordered_map>
<condition_variable> <limits> <set> <unordered_set>
<deque> <list> <shared_mutex> <utility>
<exception> <locale> <sstream> <valarray>
<execution> <map> <stack> <variant>
<filesystem> <memory> <stdexcept> <vector>
<forward_list> <memory_resource> <streambuf>
<fstream> <mutex> <string>
<functional> <new> <string_view>
The new headers compared to C++14 seem to be: <any>, <execution>, <filesystem>, <memory_resource>, <optional>, <string_view>, <variant>.
Again, the 26 headers related to C (C11) are unchanged compared with C++11 and C++14:
<cassert> <cinttypes> <csignal> <cstdio> <cwchar>
<ccomplex> <ciso646> <cstdalign> <cstdlib> <cwctype>
<cctype> <climits> <cstdarg> <cstring>
<cerrno> <clocale> <cstdbool> <ctgmath>
<cfenv> <cmath> <cstddef> <ctime>
<cfloat> <csetjmp> <cstdint> <cuchar>
See also What are the new features in C++17?
Note that some of the 'C library' headers are deprecated in C++17, specifically <ccomplex>, <cstdalign>, <cstdbool>, <ctgmath> (and not <ciso646>). The C++ header <codecvt> (added in C++11) is also deprecated in C++17.
* The 'off by one year' issues in the dates are due to the time it takes to process the standard after it is approved. ANSI approved the original C standard in 1989; ISO approved it in 1990. Amendment 1 was approved in 1994; it was released in 1995.
| |
doc_23529034
|
I can see the log message from my foreground javascript directly in
chrome by right-clicking on any page and selecting "inspect"...
and I can view the logs of my background javascript by selecting "service worker"
from the manage extensions page... but viewing logs from oauth.js ? - I have no idea how or where to view them.
I know some console.log() calls must have been made just by inspecting the error report below:
A: To halt the execution of the Oauth.js code and examine the values of the variables, you can try adding a breakpoint to oauth.js or putting a debugger statement.
By selecting the "Sources" tab, finding oauth.js in the list of files, and clicking on the line number where you wish to halt code execution, you can accomplish this.
A: Given that such a long time has passed without any answers I have thrashed around and come up with the following thoughts about viewing logs in chrome extensions.
There appear to be three different scenarios for executing JavaScript in a chrome extension and viewing the logs of each of them is achieved very differently...
*
*We have the "content script". To view the logs of these just right click on the main body of your browser and select "developer tools" then "inspect" and navigate to the "console" display.
*We have the "service worker" which is JavaScript that runs all the time. To view those logs we need to go to the "manage extensions" page then click the extension's "Inspect views service worker" link (only visible when developer mode is selected)
*We have any JavaScript that is called from the "default_popup". To view this you must first make the popup appear by clicking on the extensions's icon in the top toolbar of chrome. Then right click within the popup display itself and select "developer tools" then "inspect".
One extra quirk people should know is that the service worker will never be shut down while logs are being viewed. So if you are viewing the service worker's logs and you want to reload a new version of the extension then you must close the viewing window first.
| |
doc_23529035
|
CSS:
table.grid tbody tr td {
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
white-space: nowrap;
vertical-align: top;
}
Question: Why isn't white-space: nowrap; not working? Is there a fix to this or a way around it?
A: As noted above, this may be due to either/both your input and/or select elements being set to display at block level using display:block which will force them onto a 'new line' instead of displaying inline and following through with the anticipate nowrap behaviour
Demo Fiddle
A: I had a div inside my td. Inside the div had 2 button. Even with white-space:nowrap, display:inline-block and position:relative applied to all these elements it did still wrapped.
For me what did the trick was removing a float:left that was being applied to the buttons, from another class, since it "kind of force" the browser to act as those elements were display:block.
| |
doc_23529036
|
Do I use any online tool? Do I write a code in python? Any help would be really good.
I want to know what kind of an encoding format is the above string. That's all.
A: In my experience enca commandline tool is pretty good at guessing encoding correctly:
http://linux.die.net/man/1/enca
In Python, there's chardet:
https://github.com/chardet/chardet
A: I just think of a way, you can decode the string in every possible encodings.
The following encodings are borrowed from Python's Standard Encodings
code_list = ["ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500",
"cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858",
"cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874",
"cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251",
"cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "euc_jp",
"euc_jis_2004", "euc_jisx0213", "euc_kr", "gb2312", "gbk", "gb18030", "hz", "iso2022_jp",
"iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3", "iso2022_jp_ext",
"iso2022_kr", "latin_1", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6",
"iso8859_7", "iso8859_8", "iso8859_9", "iso8859_10", "iso8859_13", "iso8859_14",
"iso8859_15", "iso8859_16", "johab", "koi8_r", "koi8_u", "mac_cyrillic", "mac_greek",
"mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "ptcp154", "shift_jis",
"shift_jis_2004", "shift_jisx0213", "utf_32", "utf_32_be", "utf_32_le", "utf_16",
"utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", "idna", "mbcs", "palmos",
"punycode", "raw_unicode_escape", "rot_13", "undefined", "unicode_escape",
"unicode_internal", "base64_codec", "bz2_codec", "hex_codec", "quopri_codec",
"string_escape", "uu_codec", "zlib_codec"]
s = '\x86\x9cG<!\xd9F@\xb4\n\xd6\xd4(\x9cb\xfe'
for i in code_list:
try:
print 'Using {0} to decode......{1:<30}'.format(i,s.decode(i).encode('utf-8'))
except Exception as e:
# pass
print e
| |
doc_23529037
|
Determine the last 100 clicks in past hour for every user.
I have tried using window functions to build a sliding window in time and generate required output while Spark clears old state using watermarking, however the job returns results for each window which is unuseable since I need only the latest window and any sorting seems to be missing on the streaming set.
Is there a way to achieve that using Spark Streaming?
| |
doc_23529038
|
but I want to do this same using lambda function. Please help me to code this in lambda function and guide me step by step ,I am totally new to this aws lambda
userController.js :
const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
const User = require("../models/userModel");
const s3 = new aws.S3({
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
region: process.env.S3_BUCKET_REGION,
});
const upload = (bucketName) =>
multer({
storage: multerS3({
s3,
bucket: bucketName,
metadata: function (req, file, cb) {
cb(null, { fieldName: file.fieldname });
},
key: function (req, file, cb) {
cb(null, `image-${Date.now()}.jpeg`);
},
}),
});
exports.setProfilePic = (req, res, next) => {
const uploadSingle = upload("profile-picture-upload-youtube").single(
"croppedImage"
);
uploadSingle(req, res, async (err) => {
if (err)
return res.status(400).json({ success: false, message: err.message });
await User.create({ photoUrl: req.file.location });
res.status(200).json({ data: req.file.location });
});
};
`
| |
doc_23529039
|
How to properly add this kind of button to every cell of standard TableView?
A: I do something similar in an app I am working on right now. I have a cell that has a button on it, and I need to know which button was pushed in which cell. I do that like this..
I add my button to each cell..
// add buy button to each cell
UIImage *image;
buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
image = [UIImage imageNamed:@"buy.png"];
[buyButton setBackgroundImage:image forState:UIControlStateNormal];
buyButton.frame = CGRectMake(220, 35, 96, 34);
[buyButton setTag:cellIndex];
[buyButton addTarget:self action:@selector(buyTickets:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:buyButton];
The method used to determine which "button" in which cell was selected, I then push another view controller with the information of the selected button...
// buy tickets button pressed from main table view
- (void) buyTickets:(id)sender{
ResultViewController *vc = [[ResultViewController alloc] init];
vc.buyMovieID = [sender tag]; // "sender tag" is the cell id the button is located in
[[super navigationController] pushViewController:vc animated:YES];
[vc release];
}
This is what the button looks like on each cell.
Hope this helps!
P.S. Tapping on the CELL, would push another view controller, but tapping on "Buy Tickets" button pushes a different one.
alt text http://luistovar.com/ultratableview.jpg
A: I think the detail disclosure accessory type is what you need. The doc can be found on UITableViewCell class reference.
It says :
The accessory view appears in the the right side of the cell in the table view’s normal (default) state. The standard accessory views include the disclosure chevron; for a description of valid accessoryType constants, see “Cell Accessory Type.” The default is UITableViewCellAccessoryNone. If a custom accessory view is set through the accessoryView property, the value of this property is ignored. If the cell is enabled and the accessory type is UITableViewCellAccessoryDetailDisclosureButton, the accessory view tracks touches and, when tapped, sends the data-source object a tableView:accessoryButtonTappedForRowWithIndexPath: message.
Setting your cell's accessoryType property to UITableViewCellAccessoryDetailDisclosureButton, you can easily do whatever you wan when the detail disclosure button is pressed. What's great about using this accessory type is that it's a standard button, so it is user-friendly and it does all the job of tracking which cell has been touched for you.
If you want to use a custom button, you should set the accessoryView property to that custom button and listen to events on it.
A: The way i added a button to a tableview cell was by subclassing UITableViewCell and then building its view in interface builder.
| |
doc_23529040
|
I want to tell @babel/preset-typescript which config file to use.
| |
doc_23529041
|
Allowances table looks like,
Id Title value
1 Transport 2000
2 Housing 1000
3 Housing 1000
The Salaries table,
id Salary
1 2000
2 1000
3 3000
For id's with no Housing allowance the value should be considered as 0 for housing and just the salary should be shown. If housing allowance is available, add up salary and housing.
My query is not exactly giving the right output,
SELECT
s.id,
CASE
WHEN t.`Housing` = 0 THEN s.salary
END AS Salary,
CASE
WHEN t.`Housing` <> 0 THEN t.Housing + s.salary
WHEN t.`Housing` = 0 THEN s.salary
END AS SalaryAndHousing
FROM
(SELECT
id,
CASE
WHEN Title = 'Housing' THEN value
WHEN Title <> 'Housing' THEN 0
END AS 'Housing'
FROM
Allowance) t
JOIN
Salaries s ON (t.id = s.id);
The output of my query is,
id Salary SalaryAndHousing
1 2000 2000
2 null 2000
3 null 4000
It should look like,
id Salary SalaryAndHousing
1 2000 2000 -- 2000 + 0
2 1000 2000 -- 1000 + 1000
3 3000 4000 -- 1000 + 3000
dbfiddle
A: This is can be pretty simple query:
select
s.id,
s.Salary,
s.Salary + coalesce(a.value, 0) SalaryAndHousing
from Salaries s
left join Allowance a on a.id = s.id and a.Title = 'Housing'
order by s.id;
Try it on SQLize.online
| |
doc_23529042
|
Managed(char * const a)
{
}
and the disassembled IL looks like this:
.method public hidebysig specialname rtspecialname
instance void .ctor(int8 modopt([mscorlib]System.Runtime.CompilerServices.IsSignUnspecifiedByte)* modopt([mscorlib]System.Runtime.CompilerServices.IsConst) modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a) cil managed
Removing some insignificant parts:
.method public hidebysig specialname rtspecialname
instance void .ctor(int8* modopt(IsConst) modopt(IsConst) a) cil managed
So while there is only one const in the original code, it is emitted twice in the IL. Why is that so?
| |
doc_23529043
|
public class DocumentProcessor extends DocumentProcessorInterface {
private WordprocessingMLPackage load;
private HTMLSettings htmlSettings;
private Http.MultipartFormData.FilePart filePart;
public DocumentProcessor(Http.MultipartFormData.FilePart filePart) {
super(filePart);
this.filePart = filePart;
}
private void prepare() {
try {
load = Docx4J.load(filePart.getFile());
htmlSettings = Docx4J.createHTMLSettings();
htmlSettings.setImageHandler(new DataUrlImageHandler());
htmlSettings.setWmlPackage(load);
} catch (Docx4JException e) {
e.printStackTrace();
}
}
@Override
public String getHTML() {
prepare();
OutputStream outputStream = new ByteArrayOutputStream();
Logger.info("Converting");
try {
Docx4J.toHTML(htmlSettings, outputStream, Docx4J.FLAG_EXPORT_PREFER_XSL);
} catch (Docx4JException e) {
e.printStackTrace();
}
Logger.info("Converted");
return outputStream.toString();
}
}
Output looks like this: http://imgur.com/0sTTIe6 I've already checked database encoding itself.
What have I missed?
A: As a @JasonPlutext suggested, I should create new string and set encoding to UTF-8.
return new String(outputStream.toByteArray(), "UTF-8");
and that is the answer for my problem.
| |
doc_23529044
|
@media screen and (max-aspect-ratio: 2/3) {
.content_main {
position: relative;
text-shadow: none;
overflow: hidden;
margin: 10% 5%;
margin-top:2%;
padding: 0;
height: 75%;
/*background-color: white; */
}
| |
doc_23529045
|
board = ["X", "X", "X", " ", " ", " ", " ", " ", " "]
WIN_COMBINATIONS = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[3, 4, 5],
[6, 7, 8],
[6, 4, 2],
[1, 4, 7],
[2, 5, 8]
]
How do I choose the array combinations from board that are all "X" or all "O" using the combinations found in WIN_COMBINATIONS?
For example
a different board than the one above in which X wins in the right diagonal.
board = ["X", "O", "X", "O", "X", "O", "X", "X", "O"]
# X | O | X
# ---+---+---
# O | X | O
# ---+---+---
# X | X | O
won?(board) #=> [2,4,6]
A: A slight variation of ndn's answer:
board = %w(X O X
O X O
X X O)
WIN_COMBINATIONS.select { |c| board.values_at(*c).join =~ /XXX|OOO/ }
#=> [[6, 4, 2]]
Explanation:
*
*select returns all elements for which the block returns true.
*values_at returns the values at the specified indices:
board.values_at(*[0, 1, 2])
#=> ["X", "O", "X"]
* converts the array to an argument list, so the above becomes values_at(0, 1, 2)
*join returns a string with the concatenated elements:
["X", "O", "X"].join
#=> "XOX"
*=~ checks if the string matches the regular expression /XXX|OOO/, i.e. either XXX or OOO
You can replace select with find if you just want to retrieve the first winning combination.
A: Edit Code incorporates Stefan's suggestion.
Do this once:
WIN_COMBINATIONS.each(&:sort!)
Then,
h = board.each_index.group_by{|i| board[i]}
# => {"X"=>[0, 1, 2], " "=>[3, 4, 5, 6, 7, 8]}
WIN_COMBINATIONS.find{|a| (h["X"] & a) == a or (h["O"] & a) == a}
# => [0, 1, 2]
A: WIN_COMBINATIONS.find do |combination|
values_at_positions = board.values_at(*combination).uniq
values_at_positions.size == 1 and ['X', 'O'].include?(*values_at_positions)
end # => [0, 1, 2]
A: Just out of curiosity (a slightly updated @Stefan’s answer):
WIN_COMBINATIONS.index do |wc|
board.values_at(*wc).join =~ /(?<l>\w)\k<l>\k<l>/
# or, as suggested by @Stefan: board.values_at(*wc).join =~ /(\w)\1\1/
end
#⇒ 5
Here we match the combinations to three same symbols, which is likely the most semantically correct interpretation of tic-tac-toe game.
A: You can try this.
def won?(board)
xpos = []
opos = []
who_won = nil;
board.each_with_index{|x,i| xpos << i if x == "X" }
board.each_with_index{|x,i| xpos << i if x == "O" }
WIN_COMBINATIONS.each do |com|
temp = com & xpos
who_won = "X" if temp == com
temp = com & opos
who_won = "O" if temp == com
break if !who_won.nil?
end
return who_won
end
won?(board) #=> X if x wins, O if O wins. nil if no body wins.
Its untested but should work.
| |
doc_23529046
|
var params = $urlMatcherFactory.compile('#/:type/docs/articles/:id')
.exec(location.hash, null);
It's pretty simple, it just parses things in the url.
I'm looking at upgrading to angular 2, though, and as such I'll have to abandon angular-ui-router. They're making a version 2 of it, but right now it doesn't work and the upgrade adapter for it doesn't work...
So is there any good alternative to angular-ui-router's $urlMatcherFactory for this kind of behavior? I'm not really even sure what it is called to know what to search for.
| |
doc_23529047
|
var inp = document .createElement ('input');
inp .pattern = '^\d+\.?\d*$';
document .getElementById ("foo") .appendChild (inp);
The regex /^\d+\.?\d*$/ matches "1" when I test it elsewhere. Looks like it should too.
Why does the form element fail to match? (Firefox.)
A: String representations, son.
Your usage of the pattern attribute is correct in that you are using string literals. From MDN:
The regular expression language is the same as JavaScript's. The
pattern is not surrounded by forward slashes.
However, in string literals you have to escape the \ before the slash gets its own li'l interpretation in a string literal sense. If you escape it, it will be seen as an actual slash and then the whole pattern will be recognised by the RegExp engine as a special character.
var inp = document.createElement('input');
inp.pattern = '^\\d+\\.?\\d*$';
document.getElementById("foo").appendChild(inp);
https://jsfiddle.net/qatt3rwt/4/
| |
doc_23529048
|
or any type of <!doctype> s added to the top of the page ! what is this error?
I search on google and i found <!doctype html> is the correct format even stackoverflow source code has it but when i used it javascripts not working but when it removed script working fine & html object is moving but my styles are gone away because of removing <!doctype html>
<!doctype html> when this line removed it works(html element is moving)
<html>
<head>
<script type="text/javascript">
function scrollDiv(){
var obj = document.getElementById("movingDiv");
obj.style.left = 100;
obj.style.top = 10;
}
document.onclick = scrollDiv;
</script>
</head>
<body class="body">
<div class="maindiv" id="mainDiv">
<div class="html_js_code" style="text-align:center;">
<div id="movingDiv" style="position:absolute;left:100pt;top:10pt;border:1px blue
outset;width:160px;background-color:lightyellow;font-weight:bold;">Moving Div</div>
</div>
</div>
</body>
</html>
A: Without a doctype, the browser assumes that unlabelled lengths are in pixels. With a doctype, they require an explicit unit.
obj.style.left = "100px";
obj.style.top = "10px";
A: you also forgot to put the parenthesis at the end of the function you called. I'm also pretty sure you passed it incorrectly. I believe it should look like this:
document.onclick = scrollDiv();
or
document.onclick(scrollDiv());
| |
doc_23529049
|
// Copy object to master for use as a backup
$scope.master = angular.copy($scope.user);
return $http( {method: 'PUT',
url: config.serviceBaseUri_v3 + $rootScope.permissions.PutUsers.uri.replace("{userId}", data.id),
data: $.param(filterPutRequest(angular.copy(data))),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
// Remove unwanted properties from the server request
var filterPutRequest = function(user){
if($rootScope.permissions.PutUsers.fields){
var propNames = Object.getOwnPropertyNames(user);
for(var i=0;i<propNames.length;i++){
if($rootScope.permissions.PutUsers.fields.indexOf(propNames[i]) === -1){
delete user[propNames[i]];
}
}
}
return user;
};
| |
doc_23529050
|
The localhost:9200:
{
"name" : "elasticsearch-dev-client-6858c5f9dc-zbz8p",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "lJJbPJpJRaC1j7k5IGhj7g",
"version" : {
"number" : "6.7.0",
"build_flavor" : "oss",
"build_type" : "docker",
"build_hash" : "8453f77",
"build_date" : "2019-03-21T15:32:29.844721Z",
"build_snapshot" : false,
"lucene_version" : "7.7.0",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
My python code to connect to elasticsearch host:
def get_data_es(question):
es = Elasticsearch(hosts=[{"host": "elastic", "port": 9200}], connection_class=RequestsHttpConnection, max_retries=30,
retry_on_timeout=True, request_timeout=30)
#es = Elasticsearch(hosts='http://host.docker.internal:5000', connection_class=RequestsHttpConnection, max_retries=30, timeout=30)
doc = {'author': 'gunner','text': 'event', "timestamp": datetime.now()}
es.indices.refresh(index="radius_ml_posts")
res = es.index(index="radius_ml_posts", id = 1, body = doc)
res = es.search(index="radius_ml_posts", size = 30, body={ "query": {
"query_string": {
"default_field": "search_text",
"query": question
}
}
}
)
return res
My docker-compose.yml file:
version: '2.2'
services:
elastic:
image: docker.elastic.co/elasticsearch/elasticsearch-oss:7.7.0
container_name: elastic
environment:
- discovery.type=single-node
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
memlock:
soft: -1
hard: -1
volumes:
- data01:/usr/share/elasticsearch/data
ports:
- 9300:9300
- 9200:9200
networks:
- elastic
myimage:
image: myimage:myversion
ports:
- 5000:5000
expose:
- 5000
networks:
- elastic
volumes:
data01:
driver: local
networks:
elastic:
driver: bridge
My Dockerfile:
FROM python:3.7.4
COPY . /app
WORKDIR /app
RUN pip install --upgrade pip
RUN pip3 install -U nltk
RUN python3 -m nltk.downloader all
RUN pip --default-timeout=100 install -r requirements.txt
EXPOSE 5000
ENTRYPOINT ["python"]
CMD ["main.py"]
The docker commands I am running stepwise:
*
*docker build -t myimage:myversion .
*docker-compose up
The error I am getting:
myimage_1 | Traceback (most recent call last):
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
myimage_1 | response = self.full_dispatch_request()
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
myimage_1 | rv = self.handle_user_exception(e)
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
myimage_1 | reraise(exc_type, exc_value, tb)
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
myimage_1 | raise value
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
myimage_1 | rv = self.dispatch_request()
myimage_1 | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
myimage_1 | return self.view_functions[rule.endpoint](**req.view_args)
myimage_1 | File "main.py", line 41, in launch_app
myimage_1 | ques = get_data_es(ques1)
myimage_1 | File "/app/Text_Cleaning.py", line 32, in get_data_es
myimage_1 | es.indices.refresh(index="radius_ml_posts")
myimage_1 | File "/usr/local/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 92, in _wrapped
myimage_1 | return func(*args, params=params, headers=headers, **kwargs)
myimage_1 | File "/usr/local/lib/python3.7/site-packages/elasticsearch/client/indices.py", line 42, in refresh
myimage_1 | "POST", _make_path(index, "_refresh"), params=params, headers=headers
myimage_1 | File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 362, in perform_request
myimage_1 | timeout=timeout,
myimage_1 | File "/usr/local/lib/python3.7/site-packages/elasticsearch/connection/http_requests.py", line 157, in perform_request
myimage_1 | raise ConnectionError("N/A", str(e), e)
myimage_1 | elasticsearch.exceptions.ConnectionError: ConnectionError(HTTPConnectionPool(host='elastic', port=9200): Max retries exceeded with url: /radius_ml_posts/_refresh (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f967a9b1710>: Failed to establish a new connection: [Errno -2] Name or service not known'))) caused by: ConnectionError(HTTPConnectionPool(host='elastic', port=9200): Max retries exceeded with url: /radius_ml_posts/_refresh (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f967a9b1710>: Failed to establish a new connection: [Errno -2] Name or service not known')))
Please help in fixing the issue.
Thanks in advance.
A: I fixed it by using the host as:
host:"host.docker.internal"
Code change,
es = Elasticsearch(hosts=[{"host": "host.docker.internal", "port": 9200}], connection_class=RequestsHttpConnection, max_retries=30,
retry_on_timeout=True, request_timeout=30)
A: You can try to set the ELASTICSEARCH_NODES variable in your application environment section as and then consume the variable in your python code as http://ELASTICSEARCH_NODES:
version: '2.2'
services:
elastic:
image: docker.elastic.co/elasticsearch/elasticsearch-oss:7.7.0
container_name: elastic
environment:
- discovery.type=single-node
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ulimits:
memlock:
soft: -1
hard: -1
volumes:
- data01:/usr/share/elasticsearch/data
ports:
- 9300:9300
- 9200:9200
networks:
- elastic
myimage:
image: myimage:myversion
depends_on:
- elastic
environment:
- ELASTICSEARCH_NODES=http://elastic:9200
ports:
- 5000:5000
expose:
- 5000
networks:
- elastic
volumes:
data01:
driver: local
networks:
elastic:
driver: bridge
| |
doc_23529051
|
Customer panel is derived from QTabWidget and has some tabs with some widget's
in which operator (person) can edit data. When data is changed in any widget
I check it, and i set bold font in QLabel that is "buddy" for this widget. I'm doing this by setting:
QFont fontBold; fontBold.setBold(true);
widget->setFont(fontBold)
So far so good.
Next I wanted to have tabs in which there is modified and unsaved data to be also marked with bold font. Even when user switches to other tab, and he leaves unsaved data this tab should remain marked with bold font until he comes back and save the data.
That's the problem.
If I set setFont for widget, or QTabBar - all text, or all tabs are marked
bold.
In my class that is derived from QTabWidget I have:
QTabBar *tabBar() const { return QTabWidget::tabBar(); }
So I can access the tabBar and for example use setTabTextColor - to mark this tab with different color - that's some kind of solution, but other "buddy"labels are marked with bold font, so tabText should be bold to.
If I use setStyleSheet I can make bold font, but there is also a problem:
this->tabBar()->setStyleSheet("QTabBar::tab { font:bold }");
This sets all tabs with bold text, if I use Pseudo-States like active,
selected, etc. - it changes when user switch to other tab, and I need to keep this tab bold until data is saved.
I could use setProperty and then make styleSheet for widget with particular property, but the real problem is, that I can't, or don't know how to access one tab in QTabBar (for example by knowing it's index number)
I have seen, that in QT3 there was QTab* QTabBar::tab(int) which gives access to particular tab, but this is no longer available. I read http://qt.nokia.com/doc/4.5/stylesheet-examples.html and http://qt.nokia.com/doc/4.5/stylesheet-reference.html and I didn't find solution.
How to access particular tab in QTabBar (by its index number) or how to set font:bold with styleSheet for particular tab which preserve bold font when user switches to other tabs?
Thanks in advance.
A: To perform this task, we must overwrite the paintEvent() method to create a class that inherits QTabBar.
class TabBar: public QTabBar{
QVector<int> mUnSaved;
public:
void setUnsaved(int index){
if(index >= count() || index < 0)
return;
mUnSaved << index;
update();
}
void setSaved(int index){
if(!mUnSaved.contains(index))
return;
mUnSaved.remove(mUnSaved.indexOf(index));
update();
}
protected:
void paintEvent(QPaintEvent */*event*/){
QStylePainter painter(this);
QStyleOptionTab opt;
for(int i = 0;i < count();i++)
{
initStyleOption(&opt,i);
painter.save();
if(mUnSaved.contains(i)){
painter.setFont(QFont("Times", 10, QFont::Bold));
}
painter.drawControl(QStyle::CE_TabBarTabShape, opt);
painter.drawControl(QStyle::CE_TabBarTabLabel,opt);
painter.restore();
}
}
};
Then we use it in the following example
class TabWidget : public QTabWidget
{
TabBar *mTabBar;
public:
TabWidget(QWidget *parent=0):QTabWidget(parent){
mTabBar = new TabBar;
setTabBar(mTabBar);
for(int i=0; i < 5; i++){
QString text = QString("Tab %1").arg(i);
addTab(new QLabel(text, this), text);
}
mTabBar->setUnsaved(1);
mTabBar->setUnsaved(3);
mTabBar->setUnsaved(4);
mTabBar->setSaved(3);
mTabBar->setSaved(10);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle("fusion");
TabWidget w;
w.show();
return a.exec();
}
Output:
The complete example can be found in the following link
| |
doc_23529052
|
A: I am not sure i completely understand the question but I hope this example help you start.
you can try this code:
<!DOCTYPE html>
<html>
<body>
<h3>A demonstration of how to access a BODY element</h3>
<p>Click the button to set the background color of the document to red.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("html")[0];
x.style.backgroundColor = "red";
console.log(x);
}
</script>
</body>
</html>
| |
doc_23529053
|
The same function returns me Asia/Calcutta when I use in my test.php file.
What is the problem?
A: Check the documentation:
http://www.yiiframework.com/doc-2.0/yii-base-application.html#getTimeZone%28%29-detail
It explains that "If time zone is not configured in php.ini or application config, it will be set to UTC by default."
A: For Yii 2, If time zone is not configured in php.ini or application config, it will be set to UTC by default, as yii\base\Application:
if (isset($config['timeZone'])) {
$this->setTimeZone($config['timeZone']);
unset($config['timeZone']);
} elseif (!ini_get('date.timezone')) {
$this->setTimeZone('UTC');
}
How to set timezone for Yii 2
You could set default timezone for Yii2 application in config:
$config = [
'timeZone' => 'Asia/Calcutta',
'components' => [
// ...
Yii2 Applications > timeZone
A: date_default_timezone_get()
is a php built-in function.
yii2 sets the the timezone to the timezone setted in the config. Raw php does NOT so the default timezone of the server is being fetched
| |
doc_23529054
|
ERROR: This call to PrestaShop Web Services failed and returned an
HTTP status of 500.
try {
$webService = $this->connPS();
$opt = array('resource' => 'specific_prices');
$xml = $webService->get(array(
'url' => PS_SHOP_PATH.'/api/specific_prices?schema=blank'));
$product = $xml->children()->children();
unset($product->id);
$product->id_shop = 1;
$product->id_cart = 0;
$product->id_product = 553;
$product->id_currency = 0;
$product->id_country = 0;
$product->id_group = 0;
$product->id_customer = 0;
$product->id_shop_group = 0;
$product->id_product_attribute = 0;
$product->id_specific_price_rule = 0;
$product->reduction = 1;
$product->reduction_tax = 1;
$product->reduction_type = 'amount';
$product->price = -1;
$product->from_quantity = 1;
$product->from = "0000-00-00 00:00:00";
$product->to = "0000-00-00 00:00:00";
$opt = array('resource' => 'specific_prices');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$product_price = $xml->specific_prices;
} catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) {
return 'Bad ID';
} else {
if ($trace[0]['args'][0] == 401) {
return 'Bad auth key';
} else {
return '<b>ERROR:</b> '.$e->getMessage();
}
}
}
This is the XML result:
[resource] => specific_prices
[postXml] => <?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<specific_price>
<id_shop_group>0</id_shop_group>
<id_shop>1</id_shop>
<id_cart>0</id_cart>
<id_product>594</id_product>
<id_product_attribute>0</id_product_attribute>
<id_currency>0</id_currency>
<id_country>0</id_country>
<id_group>0</id_group>
<id_customer>0</id_customer>
<id_specific_price_rule>0</id_specific_price_rule>
<price>-1</price>
<from_quantity>1</from_quantity>
<reduction>0.2</reduction>
<reduction_tax>1</reduction_tax>
<reduction_type>percentage</reduction_type>
<from>0000-00-00</from>
<to>0000-00-00</to>
</specific_price>
</prestashop>
The XML result seems ok, but the web service does not give me any information about the error. Could someone help me?
| |
doc_23529055
|
For reference, I am using MySQL Connector/NET 6.3.6 and .NET 4
This is where i started to extract all the exisiting types out of the XML (DbType and ProviderType attributes). These are the values and how often they exist:
Database-Types:
---------------
StringFixedLength 4
Int64 12
Date 20
SByte 32
Single 44
AnsiString 54
DateTime 96
String 300
Int32 432
Provider-Types:
---------------
String 4
Int64 12
Date 20
NewDecimal 24
Text 30
Byte 32
Float 44
Timestamp 96
VarChar 300
Int32 432
The DbTypes all seem perfectly valid according to the DbTypeEnumeration docs http://msdn.microsoft.com/en-us/library/system.data.dbtype.aspx.
I am not sure about the ProviderTypes, but they look ok also.
Does someone have a clue either how to debug this problem or even how to fix it?
| |
doc_23529056
|
I want to thread the report because it takes more than 10 seconds to generate.
Can somebody explain what is going on?
procedure TReportThread1.Execute;
begin
if ReportBUFFER = 1 then begin
dm.rmvFarm.Filename := reportpath + 'aoc.rep';
dm.rmvFarm.Report.Params.Items[0].Value := Thread_StartOfTheDayR1;
dm.rmvFarm.Report.Params.Items[1].Value := Thread_EndOfTheDayR1;
dm.rmvFarm.Report.Params.Items[2].Value := currentusr;
dm.rmvFarm.Preview := true;
dm.rmvFarm.Execute;
ReportThread1.free;
end;
end.
A: If you look at the source code for TVCLReport, its Execute() method displays a VCL-based UI when Preview=True:
type
TVCLReport=class(TCBaseReport)
private
prcontrol:TRpPreviewControl;
...
end;
function TVCLReport.Execute:boolean;
var
...
begin
inherited Execute;
...
try
if Preview then
begin
prcontrol:=TRpPreviewControl.Create(nil);
try
prcontrol.Report:=Report;
Result:=ShowPreview(prcontrol,Title);
finally
prcontrol.free;
end;
end
else
begin
...
end;
TRpPreviewControl is derived from TScrollBox. ShowPreview() is a helper function that places the TRpPreviewControl object onto a custom TForm object (TFRpPreview) that is displayed with ShowModal(). VCL-based UIs are not thread-safe and cannot be use outside of the context of the main UI thread. As you can see, TVCLReport.Execute() does not provide you any opportunity to synchronize with the main UI thread, so Preview=True is NOT safe to use in a worker thread.
If you want to call TVCLReport.Execute() in a worker thread, but display its preview in a thread-safe manner, one possible solution would be to be alter the source code for TVCLReport to expose the preview functionality in a way that allows you to call it using TThread.Synchronize(), eg:
type
TVCLReportPreviewEvent = procedure(Sender: TObject; var VResult: Boolean) of object;
TVCLReport=class(TCBaseReport)
private
prcontrol:TRpPreviewControl;
...
public
OnPreview: TVCLReportPreviewEvent;
function DisplayPreview: Boolean;
end;
function TVCLReport.Execute:boolean;
var
...
begin
inherited Execute;
...
try
if Preview then
begin
if Assigned(OnPreview) then
OnPreview(Self, Result)
else
Result := DisplayPreview;
end
else
begin
...
end;
function TVCLReport.DisplayPreview: Boolean;
begin
prcontrol:=TRpPreviewControl.Create(nil);
try
prcontrol.Report:=Report;
Result := ShowPreview(prcontrol, Title);
finally
prcontrol.free;
end;
end;
procedure TReportThread1.Execute;
begin
if ReportBUFFER = 1 then begin
dm.rmvFarm.Filename := reportpath + 'aoc.rep';
dm.rmvFarm.Report.Params.Items[0].Value := Thread_StartOfTheDayR1;
dm.rmvFarm.Report.Params.Items[1].Value := Thread_EndOfTheDayR1;
dm.rmvFarm.Report.Params.Items[2].Value := currentusr;
dm.rmvFarm.Preview := true;
dm.rmvFarm.OnPreview := DisplayPreviewInMainThread;
dm.rmvFarm.Execute;
ReportThread1.free;
end;
end;
procedure TReportThread1.DisplayPreviewInMainThread(Sender: TObject; var VResult: Boolean);
begin
TThread.Synchronize(nil,
procedure
begin
VResult := dm.rmvFarm.DisplayPreview;
end
);
end;
Although, if your report really does take a long time to generate, then chances are that the preview will also take a long time to generate. If so, this solution will not gain you anything useful. It might be easier to simply leave the TVCLReport in the main UI thread, and display a message to the user while it is busy generating the report.
You will just have to try it and see what happens.
| |
doc_23529057
|
When I start debugging in Classic Dev Mode, I get a white blank screen on Chrome. When I open debug screen in Chrome, I see the error message : " Failed to load resource: net::ERR_CONNECTION_REFUSED".
How can I debug in old fashioned way?
Thx in advance.
HDayi
A: The Dev Mode plugin has been deprecated a long time ago for both chrome and firefox.
If you really want to keep using the old dev mode, the only browser that will allow you to use it right now is Internet Explorer.
If you can, you should consider switching to the all new GWT 2.7 which contains significant improvement to the super dev mode that replaces the old hosted mode, with greatly improved recompilation times.
| |
doc_23529058
|
By doing this, don't I gain the power to slow down the user's device? Is there something Android OS can do to prevent/stop it?
| |
doc_23529059
|
To illustrate the difference between :nth-child() and :nth-of-type() and to illustrate the problem, consider the following HTML document:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>:nth-of-type() in Sizzle/jQuery?</title>
<style>
body p:nth-of-type(2n) { background: red; }
</style>
</head>
<body>
<p>The following CSS is applied to this document:</p>
<pre>body p:nth-of-type(2n) { background: red; }</pre>
<p>This is paragraph #1.</p>
<p>This is paragraph #2. (Should be matched.)</p>
<p>This is paragraph #3.</p>
<p>This is paragraph #4. (Should be matched.)</p>
<div>This is not a paragraph, but a <code>div</code>.</div>
<p>This is paragraph #5.</p>
<p>This is paragraph #6. (Should be matched.)</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
// The following should give every second paragraph (those that had red backgrounds already after the CSS was applied) an orange background.
// $('body p:nth-of-type(2n)').css('background', 'orange');
});
</script>
</body>
</html>
Since Sizzle uses the browser-native querySelector() and querySelectorAll() methods if those are present (i.e. in browsers that already implement the Selectors API), stuff like $('body p:nth-child'); will of course work. It won’t work in older browsers though, because Sizzle has no fallback method for this selector.
Is it possible to easily add the :nth-of-type() selector to Sizzle, or to implement it in jQuery (by using the built-in :nth-child() selector, perhaps)? A custom selector with parameters would be nice.
A: the jQuery plugin moreSelectors has support for nth-of-type (and many other selectors). I suggest either using that, or simply implement a simple plugin that only implements the exact selectors you need. You should be able to copy-paste code from there.
Happy hacking!
A: /**
* Return true to include current element
* Return false to exclude current element
*/
$.expr[':']['nth-of-type'] = function(elem, i, match) {
if (match[3].indexOf("n") === -1) return i + 1 == match[3];
var parts = match[3].split("+");
return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
};
Test case - (check in IE or rename the selector)
You can of course add even & odd too:
match[3] = match[3] == "even" ? "2n" : match[3] == "odd" ? "2n+1" : match[3];
A: I can't pretend to know how nth-of-type is implemented, but jQuery does provide a mechanism by which you can create your own custom selector.
The following question deals with custom selectors, and may provide a useful insight to you
What useful custom jQuery selectors have you written?
| |
doc_23529060
|
Does anyone know how I can modify this code to allow for past date selecting.
$('#start-date').bind('dpClosed', function(e, selectedDates) {
var d = selectedDates[0];
if (d) {
d = new Date(d);
$('#end-date').dpSetStartDate(d.addDays(1).asString()).dpSetSelected(d.asString()).val($(this).val());
}
});
Adding a
$('.date-picker').dpSetStartDate('01/01/2000');
doesn't work. :(
I would greatly appreciate all help.
Thanks,
Tim
A: If you simply want dates in the past to be selectable it is as simple as:
$('.date-picker').datePicker({startDate:'01/01/2000'});
(see http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerPastDate.html )
Note that the startDate you pass in must me in the same format as you have set Date.format to (or dd/mm/yyyy by default).
You can also dynamically allow e.g. dates in the last year like so:
$('.date-picker'.datePicker({startDate: (new Date()).addYears(-1).asString()});
A: you can use min date option also if you don't want to show the date before any specify date as :-
$('#start-date').datepicker('option', 'minDate', new Date());
// new Date will show today's date you can put any specific date a
| |
doc_23529061
|
cause i would like to store only one or two string ...and avoid string table as if i use FindResource() function it will load a whole block of strings
A: Store each string separately as a Binary resource. In this case you can load each string separately by its ID.
Code below will extract resource with "ResId" from "RES_SECTION", where
RES_SECTION is custom section defined by user when resource is added, and
ResId is id of the resource.
HMODULE hModule = NULL;
HGLOBAL hResource = NULL;
HRSRC hResInfo = NULL;
LPVOID tmpData = NULL;
DWORD tmpDataSize = 0;
/* find and get resource handle */
hResInfo = FindResource(hModule, MAKEINTRESOURCE(ResId), RES_SECTION);
/* loads resource into global memory. */
hResource = LoadResource(hModule, hResInfo);
/* get a pointer to the loaded resource */
tmpData = LockResource(hResource);
/* determine the size of the resource */
tmpDataSize = SizeofResource(hModule, hResInfo);
unsigned char * str = new unsigned char[tmpDataSize];
memcpy_s(str, tmpDataSize, tmpData, tmpDataSize);
Do not forget to add correct error handling for above function calls.
| |
doc_23529062
|
My Implementation works fine with the primitive data types, but fails when user wants to pass Non-POD [Plain Old Datatypes] types.
On people's suggestion here on SO I read about Boost Serialization and how it allows to serialize even the Non-PODs.
Question :
Q1. Is serialization/De-serialization considered an IPC mechanism in itself or it is used along with other implementation ? [ In other words, should I enhance my message queue implementation using serialization, or I should move on to Serialization as the IPC mechanism itself ? ]
If yes, wouldn't it be slow as it involves writing the data onto hard disk and reading it from there ?
or it is just my misunderstanding and all IPC like d-bus might actually save the data onto disk and just pass on the file identifier to the other process to read ?
A: Serialisation/Deserialisation isn't an IPC mechanism in and of itself - You need to use something like pipes to communicate between different processes. Having said that, you could definitely serialise/deseralise data to and from these pipes.
Using such a strategy could be slow, but if so, any slowness would come from serialisation and buffering. If you're using pipes, you're just passing the serialised bytes through memory, not by writing to the disk and then reading from the disk.
I wrote an implementation of a pattern like this in C# a while ago, there's a blog post on it here if you're interested in some implementation ideas.
| |
doc_23529063
|
I created a texbox that works as a command line. You enter data and depending on what is written, it will perform several functions: for example: change the color of a panel, button, letter, etc.
Now I try that when I enter "color.Red" the program detects the word "color" and then knows that all that appears after that word is the color that the user wants to change so far it is like this:
if (e.KeyCode == Keys.Enter) // if user presses enter
{
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml (command_txt.Text); // reads the content of the textbox and passes it to html language that gives us the color
this.BackColor = myColor; // at the end, set this color to the bottom of the form
}
As you can see, I only made the program able to read the color.
Is there a way to run this code only when the user enters "color" + "(whatever color you want)".?
| |
doc_23529064
|
Intent registration= new Intent("com.google.android.c2dm.intent.REGISTER");
registration.putExtra("app", PendingIntent.getBroadcast(getBaseContext(),0,new Intent(),0));
registration.putExtra("sender",project_number);
startService(registration);
i need put extra similar
registration.putExtra("id_user",id_user);
and recieved in broadclass
public class resquest extends BroadcastReceiver {
NEED CATCH HERE..... a USER_ID
@Override
public void onReceive(Context context, Intent intent) {
.....Code here
}
}
Regards!
A: First of all you need to send in the user id to be able to fetch it:
Integer id_user = 1;
Intent registration= new Intent("com.google.android.c2dm.intent.REGISTER");
registration.putExtra("app", PendingIntent.getBroadcast(getBaseContext(),0,new Intent(),0));
registration.putExtra("sender",project_number);
registration.putExtra("id_user", id_user.intValue());
startService(registration);
Then you can fetch it like this
public class resquest extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int id_user = i.getExtras().getInt("id_user");
}
}
| |
doc_23529065
|
var currentDate = dateFormat(now, "yyyy-mm-dd"); //dateFormat is a npm package
console.log(currentDate) //returns 2015-12-29
My currentDate value is saved to a PostgreSQL database. HOWEVER, when I view it, it is 2015-12-29T05:00:00.000Z. Does anyone know why that additional string is there and how I can get rid of it?
A: This is because the column in Postgres table is of type timestamp (with or without time zone).
If you can change it to date you will see expected format.
However, you can always cast the value to type date:
select '2015-12-29T05:00:00.000Z'::timestamp;
timestamp
---------------------
2015-12-29 05:00:00
(1 row)
select '2015-12-29T05:00:00.000Z'::date;
date
------------
2015-12-29
(1 row)
A: From Wikipedia,
If the time is in UTC, add a Z directly after the time without a
space. Z is the zone designator for the zero UTC offset. "09:30 UTC"
is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would
be "14:45:15Z" or "144515Z".
Link: ISO 8601
| |
doc_23529066
|
Compiling the packages is tedious work and can take a lot of time. Uninstalling is even more error prone as you have to keep the source directory around to do a make uninstall. Handling different versions (multiple compilers for example) is also a pain as it usually means compiling into different paths and setting some environment variables to select which one you want.
Are there any good tools out there to make this job easier and less time consuming? Something like RPM where you can pick a path and build/install packages by writing a spec file. Or maybe some system like busybox which handles most of the work for you. Being able to select versions of things (compiler, jvm, etc..) would be even better. It has to be some solution that does not require root.
I know a lot of people must be doing some variant of this. How do you handle this problem?
| |
doc_23529067
|
plotOptions: {
series: {
slicedOffset: 0,
cursor: 'pointer',
stacking: 'normal',
point: {
events: {
click: function (e) {
$(e).showBalloon({
contents: 'Hello'
});
}
}
}
It doesn't work says SCRIPT16386: No such interface supported. I thought it would be better to add normal HTML element ( add div to the series on click) and perform bubble on it, but I am unable add div to it. Here is the code for that,
$(e).append("<div>hello world</div>");
But it says SCRIPT5007: Unable to get value of the property 'createDocumentFragment': object is null or undefined. Can any body help me finding the mistake please ?
I was able to show balloon pop up using this,
$($(e.target)).showBalloon({
contents: '<div ng-controllrt="chartController"<a href="javascript::void(0)" ng-click="test()"> Click </a></div>'
});
But the problem is the tool tip is never been under angular scope, it's outside the scope. I will try to post a fiddle soon. But, to understand the code structure here is how is done, here is the chart config is seperate js file,
var chartService = function($rootScope){
var setConfig = function(chartData,$scope){
$roorScope.chartConfig = {
chart: { // options}
};
plotOptions: {
series: {
slicedOffset: 0,
cursor: 'pointer',
stacking: 'normal',
point: {
events: {
click: function (e) {
$(e).showBalloon({
contents: 'Hello'
});
}
}
}
};
return {
setConfig: function(chartData,$scope){
return setConfig(chartData,$scope);
}
};
};
In my controller I inject this as service and call the setConfig
var myController = function ($rootScope,){
chartService.setConfig(data,$scope);
//this is the scope function I wanted to execute whenever user clicks on the anchor link in the jquery Balloon Pop Up
$scope.test = function () {
alert("test");
};
};
But the click never happens , can anybody suggest me what might be the issue ?
A: I got it working. Although it is not an efficient way to do it. It is working.
You need to iterate though all the points and toggle off balloon. So, The iteration and toggling off the balloon can be achieved by using sibling and hideBalloon,
$(e.target).siblings().each(function () {
$(this).hideBalloon();
});
And for the initialization part it is same as you have mentioned in your question. So, the code looks as follows,
click: function (e) {
$(e.target).siblings().each(function () {
$(this).hideBalloon();
});
$(e.target).showBalloon({
classname: "balloonTip",
contents: 'Hello'
});
},
And here is a working fiddle.
| |
doc_23529068
|
I want to map custom icons, which are defined in a json data object by the property name. I have multiple Icons.
I wrote this code, but it's not working and my console says the error is in line 266,
"Uncaught TypeError: Cannot read property 'createIcon' of undefined"
but I can't figure out the error.
var map = L.map('map').setView([50.922082,6.944733], 13);
var markerIcons = {
"REWE": L.icon({
iconUrl: 'rewe.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Kaufland": L.icon({
iconUrl: 'kaufland.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Netto Filiale": L.icon({
iconUrl: 'netto.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"REWE Rahmati": L.icon({
iconUrl: 'rewe.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Lidl": L.icon({
iconUrl: 'lidl.jpg',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"ALDI SÜD": L.icon({
iconUrl: 'aldi.jpg',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"PENNY": L.icon({
iconUrl: 'penny.jpg',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"dm-drogerie markt": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Hit": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"HIT Handelsgruppe GmbH & Co. KG": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Hit getränkemarkt": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Hit Markt": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Kaufland Köln-Niehl": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Kaufland Köln-Ehrenfeld": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Kaufland Köln-Kalk": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Kaufland Köln-Mühlheim": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"NORMA Filiale": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"NORMA": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"real": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Wodarz Getränkemarkt": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Center Engels Marsdorf GmbH": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Engels": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Peters": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Gans": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Daub KG": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Center Engels Widdersdorf": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Romano": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Wodarz": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Kausemann": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Weiden": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Hein": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Feldmann-Höner": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA - Die Kippings": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Blomeier": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Aktiv Markt Hetzenegger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA STEFFENS": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Jung": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Markt Hein": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Frischmarkt Zickuhr": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Stahl": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Klein": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Hetzenegger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA-Markt Frischecenter J. Engels GbR": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Geurtz": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Wünsch": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Hetzenegger Getränkemarkt": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Klein Hessling": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Breuer": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Höner": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Schröder": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA FrischeCenter Gusek": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Zickuhr": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Köln-Merheim": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Klein-Heßling": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Mülln": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Bonus": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"EDEKA Breidohr-Frischecenter": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Edeka Jünger": L.icon({
iconUrl: 'dm.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
};
for (var i = 0; i < jsonDataObject.length; i++) {
var lat = parseFloat(jsonDataObject[i].geometry.location.lat);
var lng = parseFloat(jsonDataObject[i].geometry.location.lng);
var marker = L.marker(L.latLng(lat, lng), {
icon: markerIcons[jsonDataObject[i].name]
});
marker.bindPopup(jsonDataObject[i].name, {
autoClose: false
});
map.addLayer(marker);
marker.myJsonData = jsonDataObject[i];
};
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
A: You get this error because in your jsonDataObject you only have as name Lidl and not REWE and Netto Filiale. Moreover there is not an object for Lidl in your markerIcons dictionary. If you include in your markerIcons an object for Lidl you should be good and not get the error.
<!DOCTYPE html>
<html>
<head>
<title>Angelkarte</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
</head>
<body>
<div id="map" style="width: 700px; height: 640px"></div>
<script>
var jsonDataObject = [
{
"geometry": {
"location": {
"lat": 50.93756,
"lng": 6.947799799999999
},
"viewport": {
"northeast": {
"lat": 50.93890322989272,
"lng": 6.949169529892721
},
"southwest": {
"lat": 50.93620357010728,
"lng": 6.946469870107277
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id": "62cb1e6d0806ad07128377d901ee32310253a30b",
"name": "REWE",
"opening_hours": {
"open_now": true
},
"photos": [{
"height": 3096,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/101585085101168022315\"\u003eMomen Mawad\u003c/a\u003e"
],
"photo_reference": "CmRaAAAAXm4APOhsx_uZaCqKYJaPIV3j4N8LacOOyJRbo4Ngic4a8d_wfvN2hpGdEq99Bb4a-GJ1zNYytXZJb31oZtb76UcCXlCqJz-_T8OUJIGU0QPrwtoxouUUNbpogqSCnCddEhDqABsG5Mqmf0PSSo-b_T2uGhTU6tkDpTmygG7CRvzKLaSm2W1K_Q",
"width": 4128
}],
"place_id": "ChIJfT5IYqklv0cRa8hjie38gBs",
"plus_code": {
"compound_code": "WWQX+24 Köln",
"global_code": "9F28WWQX+24"
},
"rating": 4,
"reference": "ChIJfT5IYqklv0cRa8hjie38gBs",
"scope": "GOOGLE",
"types": [
"supermarket",
"grocery_or_supermarket",
"food",
"point_of_interest",
"store",
"establishment"
],
"user_ratings_total": 718,
"vicinity": "Neumarkt 8-10, Köln"
},
{
"geometry": {
"location": {
"lat": 50.9896636,
"lng": 6.9450721
},
"viewport": {
"northeast": {
"lat": 50.99083827989272,
"lng": 6.945784879892721
},
"southwest": {
"lat": 50.98813862010728,
"lng": 6.943085220107277
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id": "15bde73489d3e661f76c6c8b057b857d15c33f5d",
"name": "Lidl",
"opening_hours": {
"open_now": true
},
"photos": [{
"height": 4160,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/109844980228758601627\"\u003eJakub Zeman\u003c/a\u003e"
],
"photo_reference": "CmRaAAAAxWykfcdTATYDgX-RKiu2bJMZ_i1TDEKYRRZtLY7d7ra2LoPSq-lHbqYgj2Hm8rT2MtniHkb5LbjPsynSg_03hYxVvrU7y5HC0shGbjO-AkmChpTk4G0u0fm7Ryso_BUcEhC4p08zvEuFmcU5fOZvbCoKGhS1zKXZF6SF27Ly4u6ZWlmsd2VJ3Q",
"width": 3120
}],
"place_id": "ChIJI0M7-Jkvv0cRZafVWxoOywc",
"plus_code": {
"compound_code": "XWQW+V2 Köln",
"global_code": "9F28XWQW+V2"
},
"rating": 4.1,
"reference": "ChIJI0M7-Jkvv0cRZafVWxoOywc",
"scope": "GOOGLE",
"types": [
"supermarket",
"grocery_or_supermarket",
"food",
"point_of_interest",
"store",
"establishment"
],
"user_ratings_total": 450,
"vicinity": "Neusser Str. 774/776, Köln"
},
{
"geometry": {
"location": {
"lat": 50.9626901,
"lng": 7.0051027
},
"viewport": {
"northeast": {
"lat": 50.96417282989272,
"lng": 7.006365279892721
},
"southwest": {
"lat": 50.96147317010728,
"lng": 7.003665620107277
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id": "abb022726ecd83f2f41a4921b9969fdb92f78a48",
"name": "Lidl",
"opening_hours": {
"open_now": true
},
"photos": [{
"height": 1920,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/101798318233683502049\"\u003eSergei Baikin\u003c/a\u003e"
],
"photo_reference": "CmRaAAAAJ4SqucpuL7ecaLXlipj7twdqC_KwTTYAF48n-2aMGzLTJGT1nphb_OM9h_A05nRob5R34sHNKNqtKBSoHeVTI5UlDf6cbHRswDv1UFldESl814keTyTXfWTlzlryyGxQEhApWglsPwfp3thXkYgHzAp2GhT9cZSOrbfKytiDWdGjM8y-hNhE1Q",
"width": 1080
}],
"place_id": "ChIJA5HPDgcmv0cR-QJ3JHPmld4",
"plus_code": {
"compound_code": "X274+32 Köln",
"global_code": "9F29X274+32"
},
"rating": 3.6,
"reference": "ChIJA5HPDgcmv0cR-QJ3JHPmld4",
"scope": "GOOGLE",
"types": [
"supermarket",
"grocery_or_supermarket",
"food",
"point_of_interest",
"store",
"establishment"
],
"user_ratings_total": 318,
"vicinity": "Wr. Pl. 1, Köln"
},
{
"geometry": {
"location": {
"lat": 50.97775619999999,
"lng": 7.0010123
},
"viewport": {
"northeast": {
"lat": 50.97912242989272,
"lng": 7.002976729892721
},
"southwest": {
"lat": 50.97642277010728,
"lng": 7.000277070107277
}
}
},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
"id": "078117a10aefd0116715a6079cdb036f5ba41c57",
"name": "Netto Filiale",
"opening_hours": {
"open_now": true
},
"photos": [{
"height": 1280,
"html_attributions": [
"\u003ca href=\"https://maps.google.com/maps/contrib/111351800509443750507\"\u003eA Google User\u003c/a\u003e"
],
"photo_reference": "CmRaAAAAoij8qIZHDfyMMua-UT_Xr4qIbNaEaeJg6ocxZMmLnbtvMBgSHwlnX_z0XXeugXfZRAlGer39I1chZiL10-iR_BIw86ciuNseeI7dzgubxljtcWHE8c-_4Nwk4hctxZFSEhAe5EKQCBGRRJbzGikqunuXGhT0Qox0e2htUVa_VhVgGvOrJWwr2w",
"width": 960
}],
"place_id": "ChIJXQ6kzFMvv0cRHnkGLzukbvw",
"plus_code": {
"compound_code": "X2H2+4C Köln",
"global_code": "9F29X2H2+4C"
},
"rating": 3.9,
"reference": "ChIJXQ6kzFMvv0cRHnkGLzukbvw",
"scope": "GOOGLE",
"types": [
"supermarket",
"grocery_or_supermarket",
"food",
"point_of_interest",
"store",
"establishment"
],
"user_ratings_total": 360,
"vicinity": "Düsseldorfer Str. 177, Köln"
}
];
var map = L.map('map').setView([50.922082, 6.944733], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var markerIcons = {
"REWE": L.icon({
iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon-2x.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Netto Filiale": L.icon({
iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon-2x.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
"Lidl": L.icon({
iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon-2x.png',
iconSize: [38, 95],
iconAnchor: [22, 94],
popupAnchor: [-3, -76],
}),
};
for (let i = 0; i < jsonDataObject.length; i++) {
var lat = parseFloat(jsonDataObject[i].geometry.location.lat);
var lng = parseFloat(jsonDataObject[i].geometry.location.lng);
console.log(jsonDataObject[i].name)
var marker = L.marker([lat, lng], {
icon: markerIcons[jsonDataObject[i].name]
});
marker.bindPopup(jsonDataObject[i].name, {
autoClose: false
});
map.addLayer(marker);
marker.myJsonData = jsonDataObject[i];
};
</script>
</body>
</html>
| |
doc_23529069
|
Thanks
A: Because Java byte-code is closer (more similar) to the source than assembly.
In particular, .class files include metadata for classnames, method names, field & parameter types, etc...
All a Java (or .Net) decompiler needs to do is look at the instructions in each method body, and turn them into the appropriate syntactic constructs.
By contrast, native languages like C++ do not include any metadata at all, so the decompiler needs to reconstruct everything.
A: Java is compiled into an intermediate form, JVM bytecode, that retains a large amount of the information contained in the original Java code. A language like C++ compiles into assembly code, with looks a lot different from the original code, and is, therefore, harder to reverse.
| |
doc_23529070
|
The problem is that CImg creates uchar array, where data stored in the following way (in the case of 3-channel image):
*
*first there are pixels of Red Channel,
*then all pixels of Green channel follows,
*then - Blue channel.
It looks like this: R R R R R R .... G G G G G G ... B B B B B B...
OpenCV stores data in a differnt way: B G R B G R B G R B G R...
Here is my code where I convert from CImg to IplImage:
CImg<uint8_t> src;
src.load_jpeg_buffer(srcData, size);
size_t width = src._width;
size_t height = src._height;
size_t nChannels = src._spectrum;
size_t depth = 8;
IplImage* m_image = cvCreateImage(cvSize(width, height), depth, nChannels);
for(size_t i = 0; i < height; i++)
{
for(size_t j = 0; j < width;j++)
{
for(size_t k = 0; k < nChannels; k++)
{
((m_image->imageData + i * m_image->widthStep))[j * nChannels + nChannels - 1 - k] =
src._data[k * src.size() / 3 + k + (i * m_image->widthStep + j * nChannels) / 3];
}
}
}
This code worked fine. Converted image of OpenCV format was the full copy of the original image.
I tested this code with valgrind. It said that it causes a lot of memory problems. I can't find the cause of this memory problems.
I will be grateful, if you have any ideas on this matter!
Or may be you know another method, which can load image from buffer in OpenCV (not cvDecodeImage).
A: The problems weren't in my code. As I found out OpenCV library functions cause memory problems. Examples of messages of valgrind are:
Use of uninitialised value of size 8
==16460== at 0x6500539: void cv::CvtColorLoop<cv::RGB2Gray<unsigned char> >(cv::Mat const&, cv::Mat&, cv::RGB2Gray<unsigned char> const&) (in /usr/local/lib/libopencv_imgproc.so.2.4.2)
==16488== 151,812 bytes in 1 blocks are possibly lost in loss record 3,419 of 3,425
==16488== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16488== by 0x56A2470: cv::fastMalloc(unsigned long) (in /usr/local/lib/libopencv_core.so.2.4.2)
==16488== LEAK SUMMARY:
==16488== definitely lost: 19,988 bytes in 171 blocks
==16488== indirectly lost: 15,201,012 bytes in 311 blocks
==16488== possibly lost: 1,202,769 bytes in 3,618 blocks
==16488== still reachable: 693,651 bytes in 3,733 blocks
==16488== suppressed: 0 bytes in 0 blocks
| |
doc_23529071
|
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
A: You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
A: Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}
| |
doc_23529072
|
#include "stdio.h"
void reverse (char * str);
int main (int argc , char* argv[]){
char *str = "hello";
reverse(str);
return 0;
}
void reverse (char *str)
{
char *end = str;
char tmp;
if(str){
while(*end){
++end;
}
--end;
while(str < end){
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
}
I can't figure out why I get a "bus error" when I try to run the above program. I am using i686-apple-darwin10-gcc-4.2.1. Thanks
A: String literals in C are stored in the .data section of the binary which is read only memory. When saving it as const char * or char * they are non modifiable (in some cases if you modify the access fails silently or in your case you get a bus error because it's ROM).
Try using char str[] = "hello"; instead (I believe this should work, but I may be wrong).
A: If you change char *str = "hello"; to char str[] = "hello"; your error will go away, since string literals are stored in a read-only part of memory and trying to modify "hello" may cause your program to crash (as it does in this case).
Declaring str as a char[] will copy the literal "hello" into a non-const buffer that you can modify the contents of.
| |
doc_23529073
|
A: Each star you add is another pointer, which means that char *** val is a pointer to another pointer that points to a char pointer
A: The three stars/asterisks mean nothing special. Each of the stars indicate a level of indirection.
Let me exemplify:
char *val is a char pointer called val.
char **val is a pointer to a char pointer called val.
char ***val is a pointer to a pointer to a char pointer called val.
So an asterisk for each pointer level.
| |
doc_23529074
|
After days of research I managed to talk to the server in a way it accepts using purely WCF. Of course, it would have been easy to just put some characters onto the network, ignoring all the SOAP stuff. But in the end I managed to guess every configuration parameter right, so the STS service answers my request like this
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<RequestSecurityTokenResponse xmlns="http://schemas.xmlsoap.org/ws/2005/02/trust">
<TokenType>http://schemas.xmlsoap.org/ws/2005/02/sc/sct</TokenType>
<RequestedSecurityToken>
<SecurityContextToken xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<Identifier>bipro:D5J9M0...</Identifier>
</SecurityContextToken>
</RequestedSecurityToken>
</RequestSecurityTokenResponse>
</Body>
</Envelope>
But now I have trouble to extract the identifier value. For my proxy class (SecurityTokenServicePortTypeClient : ClientBase<SecurityTokenServicePortType>, SecurityTokenServicePortType) I tried every imaginable combination of ServiceContract, DataContract and XmlSerialization on all the types. But all I get is null.
The (heavily modified) interface for the service contract looks like this
[ServiceContract(Namespace = "http://schemas.xmlsoap.org/ws/2005/02/trust")]
public interface SecurityTokenServicePortType {
[OperationContract(Action = "urn:RequestSecurityToken", ReplyAction = "*")]
object RequestSecurityToken();
}
The (heavily modified) implementing class has a method like this
object SecurityTokenServicePortType.RequestSecurityToken() {
var x = base.Channel.RequestSecurityToken();
return x;
}
x is always null.
Instead of a return type of object it was originally RequestSecurityTokenResponse and so on.
I had the same problem with WSE years ago and I was able to solve that by just using the right combination of for example XmlElementAttribute to control the deserialization process. But this time it doesn't seem to help.
Thanks for any advice!
Björn
| |
doc_23529075
|
Examples:
*
*I never want to break on this TimeoutException in a very specific case where I expect it to happen often (often in a deeper layer).
*I do want to break on all other TimeoutExceptions.
*For a very high level try/catch I actually never want to swallow the Exception before it breaks. Say a try/catch on the highest lever of some worker process.
In VS there is an ignore based on ExceptionType and an 'except from this dll' property.
For me this is often not really sufficient, but more a workaround. You have to be lucky that they actually wrote a specific Exception that you can catch and ignore. Adding a seperate assembly for just this functionality seems overkill.
Question
Is it possible to say 'never break on this and this try/catch' - but do break on all others?
A: See Don't stop debugger at THAT exception when it's thrown and caught and the answers there. Especially the attribute System.Diagnostics.DebuggerHidden might help in this case.
| |
doc_23529076
|
for player in players:
player = str(player)
print(type(players[1]))
the output is:
<class 'lxml.etree._ElementUnicodeResult'>
<class 'lxml.etree._ElementUnicodeResult'>
I need to convert this ElementUnicode object into a string so that I can call substring on it, but this for loop isn't doing it. And when I cast it to a string and call substring at the same time, the console reads: str object has no object substring, which makes no sense.
str(players[i]).substring()
Any thoughts on why that may be the case and how I could get around to calling substring on this object?
A: Casting _ElementUnicodeResult to str is not a problem. Complete demonstration:
from lxml import etree
doc = """
<root>
<player>ABC</player>
<player>DEF</player>
</root>"""
root = etree.fromstring(doc)
players = root.xpath("player/text()")
print(type(players[1]))
# Cast each player to a plain string
players = [str(p) for p in players]
print(type(players[1]))
Output:
<class 'lxml.etree._ElementUnicodeResult'>
<class 'str'>
In the question, you have the following code:
for player in players:
player = str(player)
print(type(players[1]))
This does not change anything outside the for loop. type(players[1]) will be the same as before.
In addition, it is true that str has no substring attribute. XPath has a substring() function. Maybe that is what you were thinking of?
A: If you're running python2, try: unicode(players[i])
| |
doc_23529077
|
If there is a HQL like this:
from B b
where b.x =: x
and b.y =: y
And query code like this:
Query query = session.createQuery(hql.toString());
What is the default transformer to set all of the fields into B? I found this even doesn't need setter or getter to set values.
Or say, what is the differece between it and this one:
Query query = session.createQuery(hql.toString()).setResultTransformer(Transformers.aliasToBean(B.class));
Thank you for reading this and any ideas are welcome.
A: When default Transformer used it expects the class to be hibernate entity meaning that it must be mapped with some table and in second case that is
Query query=session.createQuery(hql.toString()).setResultTransformer(Transformers.aliasToBean(B.class));
B is not hibernate entity( not mapped to any table its simple POJO without any hibernate specific annotations )
e.g
There are times we have a class, we would like to fill with data according the data returned from a query. The class is a simple POJO and not an Hibernate entity, so Hibernate won’t recognize this class.
This can be done in Hibernate by using Transformers. Let’s have a look on a simple example, showing how Transformers can be used. First, let’s have a look at a simple POJO class named: “UserActivityStat”.
This class contains some statistical information. We would like to fill the statistical information of an instance, directly from running an Hibernate HQL.
public static class UserActivityStat{
private int totalPhotos;
private int totalViews;
public UserActivityStat() { }
public int getTotalPhotos() {
return totalPhotos;
}
public void setTotalPhotos(int totalPhotos) {
this.totalPhotos = totalPhotos;
}
public int getTotalViews() {
return totalViews;
}
public void setTotalViews(int totalViews) {
this.totalViews = totalViews;
}
}
Now, let’s have a look at a simple method, that uses hibernate HQL and the Transformers class to fill “UserActivityStat” instance with data
public UserActivityStat getUserActivityStat(User user) {
return (UserActivityStat) hibernateSession.createQuery(
"select count(*) as totalPhotos, sum(p.views) as totalViews " +
"from Photo p " +
"where p.user = :user " +
"p.dateCreated <= :now")
.setParameter("user", user)
.setTimestamp("now", new Date())
.setResultTransformer(Transformers.aliasToBean(UserActivityStat.class))
.uniqueResult();
}
Note, that each of the 2 columns has an alias. This alias must be the name of the property on the “UserActivityStat” class. Also note for the use of the “setResultTransformer” along the “Transformers” class.
| |
doc_23529078
|
import java.util.ArrayList;
public class EncryptAlpha
{
private static int key;
public static ArrayList<Integer> num = new ArrayList<Integer>();
/**
* Constructs a EncryptAlpha object and sets
* it encryption key to k
* @param k
*/
public static int EncryptAlpha(int k)
{
ArrayList<Integer> num = new ArrayList<Integer>();
for(int i=0; i<10;i++)
{
k= 1+(int)(Math.random()*(100-1)+1);
num.add(k);
System.out.println(num);
}
for(int n=0; n<num.size();n++)
{
key=num.get(n);
if(n==num.size())
n=0;
}
return key;
}
/**
* This method takes a String object and converts it into an
* ArrayList of integers, where each integer is the sum of
* consecutive pairs of characters from str where the sum is
* one character's integer number value plus 1000 times the
* integer value of the next character. If there are an odd
* number of characters a ' ' is added as the last character
* @param str theString to be converted
* @return the ArrayList of integer values
*/
private ArrayList<Integer> convert(String str)
{
ArrayList<Integer> converted = new ArrayList<Integer>();
ArrayList<Integer> num = new ArrayList<Integer>();
for(int i=0; i<10;i++)
{
int k= 1+(int)(Math.random()*(100-1)+1);
num.add(k);
}
for(int i=0; i<str.length(); i+=2)
{
char t1, t2 = ' ';
t1 = str.charAt(i);
if(i<str.length()-1)
t2 = str.charAt(i+1);
int x = (int)t1 + 1000*(int)t2;
converted.add(x);
}
return converted;
}
/**
* This method takes an ArrayList of integers where each integer
* is the sum of consecutive pairs of characters from the original
* String where the sum is one character's integer number value
* plus 1000 times the integer value of the next character.
* @param converted the ArrayList to convert back into a String
* @return the 'original' String
*/
private String deconvert(ArrayList<Integer> converted)
{
String str = new String();
for(int temp : converted)
{
char t1, t2;
t1 = (char)(temp%1000);
t2 = (char)(temp/1000);
str = str + t1 + t2;
}
return str;
}
/**
* Converts the String str into an ArrayList of integers
* @param str a message to be encrypted
* @return the converted ArrayList<Integer>
*/
public ArrayList<Integer> encrypt(String str)
{
ArrayList<Integer> converted = convert(str);
for(int i=0; i<converted.size(); i++)
{
int temp = converted.get(i)*EncryptAlpha(key);
converted.set(i,temp);
}
return converted;
}
/**
* Converts the ArrayList of integers converted back into
* the original message from which it was created.
* @param converted the ArrayList to be decrypted
* @return the original message
*/
public String decrypt(ArrayList<Integer> converted)
{
String str = new String();
for(int i=0; i<converted.size(); i++)
{
for(int n=0; n<num.size();n++)
{
key=num.get(n);
}
int temp = converted.get(i)/key;
converted.set(i, temp);
}
return deconvert(converted);
}
public static void main(String[] args)
{
// Brownie points for anyone who knows why the name of
// EncryptAlpha object is enigma.
EncryptAlpha enigma = new EncryptAlpha();
String message = "I really like robots.";
// Test the private methods
ArrayList<Integer> converted = enigma.convert(message);
System.out.println(converted);
String original = enigma.deconvert(converted);
System.out.println(original);
System.out.println();
// Test the public methods
ArrayList<Integer> encrypted = enigma.encrypt(message);
System.out.println(encrypted);
original = enigma.decrypt(encrypted);
System.out.println(original);
}
The issue is, that I am using an array to store the values for the letter shifts but for some reason the encryption and decryption are using two different arrays. How can I fix this?
A: If I did understand well your "issue", you have a misconception about field/local variable, here's a commented version of your code:
public class EncryptAlpha
{
private static int key;
// let's call this one "num1"
public static ArrayList<Integer> num = new ArrayList<Integer>();
// ...
public static int EncryptAlpha(int k)
{
ArrayList<Integer> num = new ArrayList<Integer>(); // this is *not* num1
This is called variable shadowing, see this question for example. You probably want to remove the local variable declarations (i.e. ArrayList<Integer> num = new ArrayList<Integer>();)
Some reading:
*
*Understanding Class Members
*Variables
| |
doc_23529079
|
(not yet in the code: after three wrongs, it's game over, and then i will ask user if he wants to play again or go back to home)
This is my jquery code:
var error = 0;
var check = 0;
$("table img").bind('click',function(){
var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
var clickedValue = $(this).attr('name');
if(clickedValue ==letterArray[check]){
$(this).parent().empty();
check+=1;
} else {
error+=1;
$("error").add('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>');
if(error==3){
alert("Game Over. Homer will now eat you!");
$("table img").unbind("click");
$("table img").css("opacity", "0.4");
}
}
});
my table in html: just posted the first 6 letters for brevity.
<table>
<tr class="rows">
<td><img src="images/Z.png" alt="Z" name="Z"/></td>
<td><img src="images/R.png" alt="R" name="R"/></td>
<td><img src="images/S.png" alt="S" name="S"/></td>
<td><img src="images/U.png" alt="U" name="U"/></td>
<td><img src="images/B.png" alt="B" name="B"/></td>
<td><img src="images/A.png" alt="A" name="A"/></td>
</tr>
</table>
<table><tr id="error"></tr></table>
A: Use .appendTo() instead of .add()
Try this:
var error = 0;
var check = 0;
$("table img").bind('click',function(){
var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
var clickedValue = $(this).attr('name');
if(clickedValue ==letterArray[check]){
$(this).parent().empty();
check+=1;
} else {
error+=1;
$('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>').appendTo("tr#error");
if(error==3){
alert("Game Over. Homer will now eat you!");
$("table img").unbind("click");
$("table img").css("opacity", "0.4");
}
}
});
DEMO
| |
doc_23529080
|
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate *dateFormatFromString = [dateFormat dateFromString:[item objectForKey:@"Date"]];
NSLog(@"%@", [item objectForKey:@"Date"]);
NSDateFormatter *dateFormatNew = [[NSDateFormatter alloc]init];
[dateFormatNew setDateFormat:@"h:mm a, MMM d, YYYY"];
NSString *stringTime = [dateFormatNew stringFromDate:dateFormatFromString];
NSLog(@"%@", stringTime);
[item objectForKey:@"Date"] does not have a problem, it's the same thing as in the RSS. Foor example:
Wed, 25 Jan 2012 16:41:00 +0400
However, the second RSS with same date format gives me NULL. Both stringTime and dateFormatFromString produces NULL values as well. I changed the address RSS with the same format date and still have this problem.
A: If you are trying to make an RSS reader for any feed (not just a specific feed that you own), you need to deal with all kinds of malformed date formats. Even though there are specifications, many RSS feeds don't follow them.
One approach is to have an array of date formats, and enumerate through it until a non-nil string is returned:
static NSString *sGetDateForString(NSString *inString)
{
static NSArray *sPossibleDateFormats = nil;
if (!sPossibleDateFormats) sPossibleDateFormats = [[NSArray alloc] initWithObjects:
@"EEE, d MMM yyyy HH:mm:ss Z",
@"h:mm a, MMM d, YYYY",
// Add more formats here as you encounter them in the wild
nil];
NSDate *result = nil;
for (NSString *format in sPossibleDateFormats) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:format];
result = [dateFormat dateFromString:dateString];
[dateFormat release];
if (result) break;
}
return result;
}
This is going to be slow, but it may be fast enough for your app. If you need additional performance, you can try caching the index of the matched date format and pass it back into sGetDateForString() (most RSS feeds will only use one date format).
A: It's hard to say exactly what is going on without knowing precisely what string you are passing into [dateFormat dateFromString:] in both cases. You should post more specific details to help narrow it down.
Without knowing more, the only obvious difference I see between the two links is that they appear to use different text encodings. If you are parsing the same way without accounting for encoding differences it is possible that the contents of [item objectForKey:] is not actually the same between these two RSS feeds.
| |
doc_23529081
|
try {
throw std::exception();
} catch(...) {
QMessageBox::critical(this, tr("Exception"),
tr("Exception occured"));
}
}
in catch() messagebox is shown and execution goes into initializeGL() again, and shows a second message box
I'm trying to avoid this via a bool variable:
void MyGlWidget::initializeGL() {
if(in_initializeGL_)
return;
in_initializeGL_ = true;
try {
throw std::exception();
} catch(...) {
QMessageBox::critical(this, tr("Exception"),
tr("Exception occured"));
}
in_initializeGL_ = false;
}
But this leads to crash. So I decided to show error in paintGL()(it also shows 2 messageboxes):
void MyGlWidget::paintGL() {
if(in_paintGL_)
return;
in_paintGL_ = true;
if (!exception_msg_.isEmpty()) {
QMessageBox::critical(this, tr("Exception"),
exception_msg_);
exception_msg_.clear();
}
// rendering stuff
in_paintGL_ = false;
}
void MyGlWidget::initializeGL() {
try {
throw std::exception();
} catch(...) {
exception_msg_ = "Exception in initializeGL()";
}
}
This solves the problem but the code ugly. Is there a more nice solution of this problem?
Qt4.7 VS2008
A: Here is the solution:
http://labs.qt.nokia.com/2010/02/23/unpredictable-exec/
void MyGlWidget::initializeGL() {
try {
throw std::exception();
} catch(...) {
getExceptionMessage(&exception_msg_);
QMessageBox *msgbox = new QMessageBox(QMessageBox::Warning,
"Exception",
exception_msg_,
QMessageBox::Ok,
this);
msgbox->open(0, 0);
}
}
| |
doc_23529082
|
I am using Azure AD v2 endpoints for getting access token:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
https://login.microsoftonline.com/common/oauth2/v2.0/token
And using that access token to make POST request to following endpoint:
https://graph.microsoft.com/v1.0/planner/tasks
I have registered my App on: https://apps.dev.microsoft.com
And given necessary delegated and application permissions EDIT: ie Group.ReadWrite.All
(along with many others)
I am(having admin rights) able to create planner tasks using the API calls but no one else in the organization can. User gets this error message:
Need admin approval
Planner Task App
Planner Task App needs permission to access resources in your organization that
only an admin can grant. Please ask an admin to grant permission to this
app before you can use it.
I know that this user account has required permissions (because when using graph explorer api calls with same account, it works) so the problem lies in App permissions.
Any help is highly appreciated.
EDIT:
Bearer token for Admin (where app successfully creates a planner task):
eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFCSGg0a21TX2FLVDVYcmp6eFJBdEh6MmtUREpfbzduN3lETXJvVzhkUjR1YWZVZ050OEctbmhuNm5HalpvN1p5SDNqNEl0a3E5N3lFX091cEI2eEdITVVpcWpfeFVkdkFWdmx2SVgtV3FlSmlBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiRlNpbXVGckZOb0Mwc0pYR212MTNuTlpjZURjIiwia2lkIjoiRlNpbXVGckZOb0Mwc0pYR212MTNuTlpjZURjIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9jZDc3NzI5NS0xN2IwLTQ0YjMtYjUxNC02YzJlMzE2ZjI5YzcvIiwiaWF0IjoxNTIzMzg5MjcwLCJuYmYiOjE1MjMzODkyNzAsImV4cCI6MTUyMzM5MzE3MCwiYWNyIjoiMSIsImFpbyI6IlkyTmdZTEQ2WUp2WDlEZlR4dTNLMUNVdTd4YWEzVkZNRnphd3NpN2NGTGplL01ianVjSUEiLCJhbXIiOlsicHdkIl0sImFwcF9kaXNwbGF5bmFtZSI6IlBsYW5uZXIgVGFzayBBcHAiLCJhcHBpZCI6IjQ4NzQ3NmM5LWM2OTctNDhhMC1hODViLWUzYjdkMTEyMTU0MyIsImFwcGlkYWNyIjoiMSIsImZhbWlseV9uYW1lIjoiUmFnaGF2IiwiZ2l2ZW5fbmFtZSI6Ik5pdGluIiwiaXBhZGRyIjoiNjcuNzEuMjI3LjE2MiIsIm5hbWUiOiJOaXRpbiBSYWdoYXYiLCJvaWQiOiJlN2JhOTVkNi1jMGIzLTQwYTEtOTU5MS0zOWYwN2YzZWZlMDUiLCJvbnByZW1fc2lkIjoiUy0xLTUtMjEtMTA2Mjg4Nzk2MS0zOTczMjgyMzc2LTE4NTU2ODk4MjEtMTQ3MSIsInBsYXRmIjoiMyIsInB1aWQiOiIxMDAzM0ZGRkE4MUEyMzBBIiwic2NwIjoiR3JvdXAuUmVhZC5BbGwgR3JvdXAuUmVhZFdyaXRlLkFsbCBNYWlsLlNlbmQgVGFza3MuUmVhZCBUYXNrcy5SZWFkLlNoYXJlZCBUYXNrcy5SZWFkV3JpdGUgVGFza3MuUmVhZFdyaXRlLlNoYXJlZCBVc2VyLlJlYWQgVXNlci5SZWFkLkFsbCIsInNpZ25pbl9zdGF0ZSI6WyJrbXNpIl0sInN1YiI6IjB6RkdKeVA5Ym8yeDdYdlNqRVNIbnkwUXZ1Ym03YTJsVXRLcHpoVEtzclEiLCJ0aWQiOiJjZDc3NzI5NS0xN2IwLTQ0YjMtYjUxNC02YzJlMzE2ZjI5YzciLCJ1bmlxdWVfbmFtZSI6Im5pdGluLnJhZ2hhdkBhbWZyZWRlcmlja3MuY29tIiwidXBuIjoibml0aW4ucmFnaGF2QGFtZnJlZGVyaWNrcy5jb20iLCJ1dGkiOiJOZlR1U2RyeFYwYVQzdlk0ckZwSkFBIiwidmVyIjoiMS4wIiwid2lkcyI6WyI2MmU5MDM5NC02OWY1LTQyMzctOTE5MC0wMTIxNzcxNDVlMTAiXX0.T50Ae8vFtdobi4GFHL4o-rqU9sbNYqhhV0KRcA7HYzUI-4M4Latma8kJ7ssqx4djdQigPnjJTCVOg9oFBXE_iSWRPbZbRGbfuvwj9iPePCtzCERZwWn0bHOltk0o0LFWW1UoplUsMJJgxoZyeMlruWBxOIQXOQxRnHlnmMLzU-Nwr2Ex87hAMnFPBN7uD9x7WIJtc3vO-sIecKLmwKgchfbI8vIXMOgs1DsVByWBljHSN-DJ9FwxklS_r-Hco9x6g5SPJ_gXfANL8KXXK51D1Xnc7TKd3IebnjermycCKw5t-ViNPlX0r-og4iKsT2oo_k1UTi5-TO2mMIKPXMjirQ
Even after Admin has given consent to the app using (https://login.microsoftonline.com/common/adminconsent?client_id=my-app-id&state=12345&redirect_uri=https://localhost/myapp), non-admin user gets this:
A: As you have mentioned that you are adding planner task not just reading data, you have to grant permission Group.ReadWrite.All accordingly. Please check the permission and confirm about this.
ref: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/planner_post_tasks
A: In order to use Group.ReadWrite.All you need the consent of a tenant Admin. To obtain this you need to have an Admin on the tenant execute the Admin Consent process.
I have a walkthrough that might help you here:
*
*v2 Endpoint & Consent (explains the various consent workflows involved)
*v2 Endpoint & Admin Consent (explains how to obtain Admin Consent)
| |
doc_23529083
|
Thus for my original file:
chr1 | ENSEMBL gene| 17369| 17436| . - . |gene_id "ENSG00000278267.1"; gene_type "miRNA"; gene_status "KNOWN"; gene_name "MIR6859-1"; level 3;
chr1 | ENSEMBL gene| 30366| 30503| . + . |gene_id "ENSG00000274890.1"; gene_type "miRNA"; gene_status "KNOWN"; gene_name "MIR1302-2"; level 3;
chr1 | ENSEMBL gene| 157784| 157887| . - . |gene_id "ENSG00000222623.1"; gene_type "snRNA"; gene_status "KNOWN"; gene_name "RNU6-1100P"; level 3;
chr1 | ENSEMBL gene| 187891| 187958| . - . |gene_id "ENSG00000273874.1"; gene_type "miRNA"; gene_status "KNOWN"; gene_name "MIR6859-2"; level 3;
I would like it appear like this, with 'gene_id,' 'gene_type,' 'gene_status,' 'gene_name,' and level all being in SEPARATE columns:
chr1 |ENSEMBL |gene| 17369| |17436 |. - . |gene_id "ENSG00000278267.1" |gene_type "miRNA" |gene_status "KNOWN" |gene_name "MIR6859-1" |level 3
chr1 |ENSEMBL |gene| 30366| 30503 |. + . |gene_id "ENSG00000274890.1" |gene_type "miRNA" |gene_status "KNOWN" |gene_name "MIR1302-2" |level 3
chr1 |ENSEMBL |gene| 157784| 157887 |. - . |gene_id "ENSG00000222623.1" |gene_type "snRNA" |gene_status "KNOWN" |gene_name "RNU6-1100P" |level 3
chr1 |ENSEMBL |gene| 187891| 187958 |. - . |gene_id "ENSG00000273874.1" |gene_type "miRNA" |gene_status "KNOWN" |gene_name "MIR6859-2" |level 3
I have tried to parse it using gffutils, using the basic code they provide:
import gffutils
db = gffutils.create_db("sRNA.gene.gtf", dbfn='sRNA.gene.gtf.db')
print(list(db.featuretypes()))
# Here's how to write genes out to file
with open('sRNA.gene.gtf', 'w') as fout:
for gene in db.features_of_type('gene'):
fout.write(str(gene) + '\n')
However, I recieve an 'ImportError: cannot import name 'feature:'
ImportError Traceback (most recent call last)
<ipython-input-26-4dd7cd5c7e24> in <module>()
2
3
----> 4 db = gffutils.create_db("sRNA.gene.gtf", dbfn='sRNA.gene.gtf.db')
5
6 #db = gffutils.FeatureDB('sRNA.gene.gtf.db')
I am not sure what is going wrong here, and now am considering trying to just parse it using the command line. Could anyone please offer some suggestions on the best way to parse GTF files?
Thank you in advance.
A: You want to change multiple delimiters in a GTF file to a single tab delimiter. Once you've done that the file is no longer a GTF file.
The following code will get the content of the GTF file into a text file
import gffutils
try:
db = gffutils.create_db("sample.gtf", dbfn='sample.db')
except:
pass
db = gffutils.FeatureDB('sample.db', keep_order=True)
with open('sample.txt', 'w') as fout:
for line in db.all_features():
line = str(line)
line = line.split(";") #make your parsing changes here
fout.write(str(line) + '\n')
Note that you can only use the create_db() method once. That's why I've commented it out.
EDIT
Added try statement
A: You can use the pyranges library to parse gtf/gff, you will then get each entry in the attribute column as a single column.
Install instructions:
# pip install pyranges
# or
# conda install -c bioconda pyranges
Example file:
# !head ensembl.gtf
# #!genome-build GRCh38.p10
# #!genome-version GRCh38
# #!genome-date 2013-12
# #!genome-build-accession NCBI:GCA_000001405.25
# #!genebuild-last-updated 2017-06
# 1 havana gene 11869 14409 . + . gene_id "ENSG00000223972"; gene_version "5"; gene_name "DDX11L1"; gene_source "havana"; gene_biotype "transcribed_unprocessed_pseudogene";
# 1 havana transcript 11869 14409 . + . gene_id "ENSG00000223972"; gene_version "5"; transcript_id "ENST00000456328"; transcript_version "2"; gene_name "DDX11L1"; gene_source "havana"; gene_biotype "transcribed_unprocessed_pseudogene"; transcript_name "DDX11L1-202"; transcript_source "havana"; transcript_biotype "processed_transcript"; tag "basic"; transcript_support_level "1";
# 1 havana exon 11869 12227 . + . gene_id "ENSG00000223972"; gene_version "5"; transcript_id "ENST00000456328"; transcript_version "2"; exon_number "1"; gene_name "DDX11L1"; gene_source "havana"; gene_biotype "transcribed_unprocessed_pseudogene"; transcript_name "DDX11L1-202"; transcript_source "havana"; transcript_biotype "processed_transcript"; exon_id "ENSE00002234944"; exon_version "1"; tag "basic"; transcript_support_level "1";
# 1 havana exon 12613 12721 . + . gene_id "ENSG00000223972"; gene_version "5"; transcript_id "ENST00000456328"; transcript_version "2"; exon_number "2"; gene_name "DDX11L1"; gene_source "havana"; gene_biotype "transcribed_unprocessed_pseudogene"; transcript_name "DDX11L1-202"; transcript_source "havana"; transcript_biotype "processed_transcript"; exon_id "ENSE00003582793"; exon_version "1"; tag "basic"; transcript_support_level "1";
# 1 havana exon 13221 14409 . + . gene_id "ENSG00000223972"; gene_version "5"; transcript_id "ENST00000456328"; transcript_version "2"; exon_number "3"; gene_name "DDX11L1"; gene_source "havana"; gene_biotype "transcribed_unprocessed_pseudogene"; transcript_name "DDX11L1-202"; transcript_source "havana"; transcript_biotype "processed_transcript"; exon_id "ENSE00002312635"; exon_version "1"; tag "basic"; transcript_support_level "1";
Using pyranges:
import pyranges as pr
# as PyRanges-object
gr = pr.read_gtf("ensembl.gtf")
# +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------------+----------------+------------------------------------+-----------------+----------------------+-------+
# | Chromosome | Source | Feature | Start | End | Score | Strand | Frame | gene_id | gene_version | gene_name | gene_source | gene_biotype | transcript_id | transcript_version | +13 |
# | (category) | (object) | (category) | (int32) | (int32) | (object) | (category) | (object) | (object) | (object) | (object) | (object) | (object) | (object) | (object) | ... |
# |--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------------+----------------+------------------------------------+-----------------+----------------------+-------|
# | 1 | havana | gene | 11869 | 14409 | . | + | . | ENSG00000223972 | 5 | DDX11L1 | havana | transcribed_unprocessed_pseudogene | nan | nan | ... |
# | 1 | havana | transcript | 11869 | 14409 | . | + | . | ENSG00000223972 | 5 | DDX11L1 | havana | transcribed_unprocessed_pseudogene | ENST00000456328 | 2 | ... |
# | 1 | havana | exon | 11869 | 12227 | . | + | . | ENSG00000223972 | 5 | DDX11L1 | havana | transcribed_unprocessed_pseudogene | ENST00000456328 | 2 | ... |
# | 1 | havana | exon | 12613 | 12721 | . | + | . | ENSG00000223972 | 5 | DDX11L1 | havana | transcribed_unprocessed_pseudogene | ENST00000456328 | 2 | ... |
# | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
# | 1 | ensembl | transcript | 120725 | 133723 | . | - | . | ENSG00000238009 | 6 | AL627309.1 | ensembl_havana | lincRNA | ENST00000610542 | 1 | ... |
# | 1 | ensembl | exon | 133374 | 133723 | . | - | . | ENSG00000238009 | 6 | AL627309.1 | ensembl_havana | lincRNA | ENST00000610542 | 1 | ... |
# | 1 | ensembl | exon | 129055 | 129223 | . | - | . | ENSG00000238009 | 6 | AL627309.1 | ensembl_havana | lincRNA | ENST00000610542 | 1 | ... |
# | 1 | ensembl | exon | 120874 | 120932 | . | - | . | ENSG00000238009 | 6 | AL627309.1 | ensembl_havana | lincRNA | ENST00000610542 | 1 | ... |
# +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------------+----------------+------------------------------------+-----------------+----------------------+-------+
# Stranded PyRanges object has 95 rows and 28 columns from 1 chromosomes.
# For printing, the PyRanges was sorted on Chromosome and Strand.
# 13 hidden columns: transcript_name, transcript_source, transcript_biotype, tag, transcript_support_level, exon_number, exon_id, exon_version, (assigned, previous, ccds_id, protein_id, protein_version
# as DataFrame
df = gr.df
# Chromosome Source Feature Start End Score Strand Frame gene_id gene_version gene_name ... transcript_biotype tag transcript_support_level exon_number exon_id exon_version (assigned previous ccds_id protein_id protein_version
# 0 1 havana gene 11869 14409 . + . ENSG00000223972 5 DDX11L1 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 1 1 havana transcript 11869 14409 . + . ENSG00000223972 5 DDX11L1 ... processed_transcript basic 1 NaN NaN NaN NaN NaN NaN NaN NaN
# 2 1 havana exon 11869 12227 . + . ENSG00000223972 5 DDX11L1 ... processed_transcript basic 1 1 ENSE00002234944 1 NaN NaN NaN NaN NaN
# 3 1 havana exon 12613 12721 . + . ENSG00000223972 5 DDX11L1 ... processed_transcript basic 1 2 ENSE00003582793 1 NaN NaN NaN NaN NaN
# 4 1 havana exon 13221 14409 . + . ENSG00000223972 5 DDX11L1 ... processed_transcript basic 1 3 ENSE00002312635 1 NaN NaN NaN NaN NaN
# .. ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
# 90 1 havana exon 110953 111357 . - . ENSG00000238009 6 AL627309.1 ... lincRNA NaN 5 3 ENSE00001879696 1 NaN NaN NaN NaN NaN
# 91 1 ensembl transcript 120725 133723 . - . ENSG00000238009 6 AL627309.1 ... lincRNA basic 5 NaN NaN NaN NaN NaN NaN NaN NaN
# 92 1 ensembl exon 133374 133723 . - . ENSG00000238009 6 AL627309.1 ... lincRNA basic 5 1 ENSE00003748456 1 NaN NaN NaN NaN NaN
# 93 1 ensembl exon 129055 129223 . - . ENSG00000238009 6 AL627309.1 ... lincRNA basic 5 2 ENSE00003734824 1 NaN NaN NaN NaN NaN
# 94 1 ensembl exon 120874 120932 . - . ENSG00000238009 6 AL627309.1 ... lincRNA basic 5 3 ENSE00003740919 1 NaN NaN NaN NaN NaN
#
# [95 rows x 28 columns]
| |
doc_23529084
|
http://help.adobe.com/en_US/flex/using/images/chd_SimpleDataTip.png
I've found the method positionDataTips() in ChartBase which appears to do the drawing of the circle. I was going to subclass LineChart and override the method with my modified version of it. However, this method needs access to a lot of private instance variables which are only accessible to ChartBase.
Thoughts?
A: I spent a very long week dealing with this and other issues relating to chart datatips.
I have an answer to a similar question at similar question that you can look at. I will post here a modified version of that answer, since it was never marked as the answer to the question :-(
There isn't any good documentation on how exactly to work with overriding the two massive functions, ChartBase.positionDataTips and ChartBase.positionAllDataTips. I spent many days digging through mx charting code to determine the best way to override these functions in order to bend the flex charts to my will :-P
Here is some (hard-earned) code to customize the data tip targets, the default bulls-eye circles that show upon mouse hover over a series.
*
*Create a new chart class that extends ChartBase or a child of that.
*Set the ChartBase style, showDataTipTargets, to false.
*Create a new Style, showCustomDataTipTargets, on your custom chart class.
*
*you might even want to create a Style for a dataTipTargetRenderer to do the custom rendering. This would be a much more elegant solution.
*Override positionDataTips and positionAllDatatips
*
*I have written code to draw a square, but to make a larger circle, simply use your own values in place of TOOLTIP_TARGET_RADIUS and TOOLTIP_TARGET_INNER_RADIUS.
The new overridden functions would look something like this:
override protected function positionDataTips():void
{
// Setting the showDataTipTargets to false will prevent
// super.positionDataTips() from drawing the default bulls-eyes.
// By setting this style, we allow super.positionDataTips() to do all
// the "heavy-lifting" involved with dataTip positioning and dataTip box rendering
// before we do our customization of the dataTipTargets
this.setStyle("showDataTipTargets", false);
// this will do all the normal rendering of the datatips and callout
// but it will not draw the dataTipTarget because that is dependent upon
// the style, showDataTipTargets
super.positionDataTips();
// now here you draw your custom datatip target.
// Use the code from ChartBase.positionDataTips as a guide,
// I have written code to simply draw a square instead of circle.
// You can do much more complex things here as needed.
if (len > 1)
{
// calloutStroke code is copied verbatim from super function
// However, you can customize the calloutStroke rendering just as easily
// by modifying the following code!
if (calloutStroke)
{
calloutStroke.apply(g,null,null);
if (tipData.isRight)
{
g.moveTo(chartLocalPts.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x, tipData.y);
}
else
{
if(layoutDirection == LayoutDirection.RTL)
{
g.moveTo(chartLocalPts.x - tipData.width,
chartLocalPts.y + tipData.height / 2);
}
else
{
g.moveTo(chartLocalPts.x + tipData.width,
chartLocalPts.y + tipData.height / 2);
}
g.lineTo(tipData.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x, tipData.y);
}
}
}
// Here is custom dataTipTarget code!!
// It draws a 5x5 square around the point on the series
var tipColor:uint = tipData.hd.contextColor;
g.lineStyle(1, tipColor, 100);
g.moveTo(tipData.x, tipData.y);
g.beginFill(0xFFFFFF, 1);
g.drawRect(tipData.x, tipData.y, 5, 5);
g.endFill();
}
Below is the code copied from ChartBase.positionDataTip() for reference:
if (len > 1)
{
if (calloutStroke)
{
calloutStroke.apply(g,null,null);
if (tipData.isRight)
{
g.moveTo(chartLocalPts.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x, tipData.y);
}
else
{
if(layoutDirection == LayoutDirection.RTL)
{
g.moveTo(chartLocalPts.x - tipData.width,
chartLocalPts.y + tipData.height / 2);
}
else
{
g.moveTo(chartLocalPts.x + tipData.width,
chartLocalPts.y + tipData.height / 2);
}
g.lineTo(tipData.x,
chartLocalPts.y + tipData.height / 2);
g.lineTo(tipData.x, tipData.y);
}
}
}
var tipColor:uint = tipData.hd.contextColor;
g.lineStyle(1, tipColor, 100);
g.moveTo(tipData.x, tipData.y);
g.beginFill(0xFFFFFF, 1);
g.drawCircle(tipData.x, tipData.y, TOOLTIP_TARGET_RADIUS);
g.endFill();
g.beginFill(tipColor, 1);
g.drawCircle(tipData.x, tipData.y,
TOOLTIP_TARGET_INNER_RADIUS);
g.endFill();
| |
doc_23529085
|
Flow:
Step1 : Run a Jenkins job which should login to a docker container running inside the pods
Step: From the container execute the test.sh script.
test.sh
echo "This is demo file"
I have a command which will give docker image running in a kubenertes pods
kubectl get pods -n eum -o go-template --template="{{range .items}}{{range .spec.containers}}{{.image}} {{end}}{{end}}" -l app=${TIER}
TIER = list of apps added in jenkins as choice parameter
I wanted to login to the container and run the test.sh script
A: You can use command "kubectl exec ${POD } /bin/bash --all-namespaces -- /bin/sh test.sh" to run directly test.sh inside container, but make sure test.sh is available inside container. But in this case you need to pass pod name in this command. you can get all pods name using command
kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
and if you want pods only for specific label then use
kubectl get pods -l -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
here replace with your label selector of pods
| |
doc_23529086
|
I have composer on the shared host (or I believe I do, given another class works (PHPOffice))
For that the /vendor directory is in the HTDOCS folder with COMPOSER and PHPOFFICE under there, along with the autoload.php.
So then I downloaded lablnet/Encryption from php-download which gave me the same directory structure that is in the existing /vendor dir, but I am fairly sure overwriting the files will stop PHPOffice working...
Could someone please let me know how I might be able to get the two things to co-reside? And where to drop the downloaded Ecryption class...
I would love to follow the install instructions, but on the shared host, I cant run the composer require command.
Hoping for help as all I would like to be able to do is use the Encryption class.
A: Thanks... And apologies but I was meaning to post the solution...
In the end i have found out that Composer isn't 'supported' with my shared hosting provider... So as discussed above, I found php-download.
Once I got the zip down, it was then a case of playing with locations of the files, to find they have to be located within the root of the site.
I have also since realised that if you want to run multiple packages on the same site, then you need to use the 'Project' function at php-download, which will bring everything into one composer.json and lock file for you.
So, in sort this was relatively simple to fix, but you have to know that the files need to be taken out of the 'package' dir so that you have the VENDOR dir at the level below your main site files, and that's the place for the .JSON and .LOCK files.
| |
doc_23529087
|
template <typename CallableType, typename... Args>
auto invokeTest(CallableType&& fn, Args&&... args)
{
return std::invoke(fn, std::forward<Args>(args)...);
}
Is std::forward<Args> needed here?
Or is it enough to write
template <typename CallableType, typename... Args>
auto invokeTest(CallableType&& fn, Args&&... args)
{
return std::invoke(fn, args...);
}
What are the differences?
A: Well, I'd say yes but it depends on the case.
You don't need forwarding in that case:
void bar(int);
int main() {
int i = 0;
invokeTest(bar, i);
}
But, you'll need forwarding for this case:
void foo(std::unique_ptr<int>);
int main() {
auto p = std::make_unique<int>();
invokeTest(foo, p); // Won't work, cannot copy unique_ptr
}
When writing std::invoke(fn, args...), the args... are all lvalues, at which point I would recommend taking parameters by Args const&... to be clearer.
If you forward, then you move the object that were rvalues in your parameters:
template <typename CallableType, typename... Args>
auto invokeTest(CallableType&& fn, Args&&... args)
{
return std::invoke(fn, std::forward<Args>(args)...); // all forward value caterories
}
invokeTest(foo, std::move(p)); // works.
If you use Args&&..., use forwarding.
| |
doc_23529088
|
I have string such as:'
text = {'"version_name"': '"8.5.2"', '"abi"': '"arm64-v8a"', '"x_dpi"':
'515.1539916992188', '"environment"': '{"sdk_version"',
'"time_zone"':
'"America\\/Wash"', '"user"': '{}}', '"density_default"': '560}}',
'"resolution_width"': '1440', '"package_name"':
'"com.okcupid.okcupid"', '"d44bcbfb-873454-4917-9e02-2066d6605d9f"': '{"language"', '"country"':
'"US"}', '"now"': '1.515384841291E9', '{"extras"': '{"sessions"',
'"device"': '{"android_version"', '"y_dpi"': '37abc5afce16xxx',
'"model"': '"Nexus 6P"', '"new"': 'true}]', '"only_respond_with"':
'["triggers"]}\n0\r\n\r\n', '"start_time"': '1.51538484115E9',
'"version_code"': '1057', '"-104.99875"': '"0"', '"no_acks"': 'true}',
'"display"': '{"resolution_height"'}
An array has multi-string as :
Keywords =["37abc5afce16xxx","867686022684243", "ffffffff-f336-7a7a-0f06-65f40033c587", "long", "Lat", "uuid", "WIFI", "advertiser", "d44bcbfb-873454-4917-9e02-2066d6605d9f","deviceFinger", "medialink", "Huawei","Andriod","US","local_ip","Nexus", "android2.10.3","WIFI", "operator", "carrier", "angler", "MMB29M", "-104.99875"]
My code as
for x in Keywords:
pattern = r"^.*"+str(x)+"^.*"
if re.findall(pattern, str(values1),re.M):
print "Match"
print x
else:
print "Not Match"
A: Your code's goal is a bit confusing, so this is assuming you want to check for which items from the Keywords list are also in the text dictionary
In your code, it looks like you only compare the regex to the dictionary values, not the keys (assuming that's what the values1 variable is).
Also, instead of using the regex "^.*" to match for strings, you can simply do
for X in Keywords:
if X in yourDictionary.keys():
doSomething
if X in yourDictionary.values():
doSomethingElse
| |
doc_23529089
|
but I need shallow copy of this array
Please consider the following code:
@observable.ref trades: Array<TradeType> = [];
@action attachNewTrade = (trade: TradeType): Array<TradeType> => {
let newTrades = _.CloneDeep(this.trades)
newTrades.push(trade)
this.trades = newTrades
}
I am using React+Mobx in this project
Especially I need Observable function for this, not toJSON of immutable.js
A: This is not specific to mobx
@observable.ref trades: Array<TradeType> = [];
@action attachNewTrade = (trade: TradeType): Array<TradeType> => {
this.trades = [...this.trades, trade]
}
The reason you need to copy is that React can't detect internal change of objects/array, so you need to change the reference to notify React that something is changed.
If you want solution of more mobx way, please check https://github.com/mobxjs/mobx/issues/1489
A: I was having the same issue and I solved it with mobx's toJS: https://mobx.js.org/refguide/tojson.html
| |
doc_23529090
|
My code is not working:
<?php
$list = htmlentities(file_get_contents('list.html'));
preg_match("/^[a-zA-Z0-9-.]+(.org)$/", $list, $matches);
var_dump ($matches);
?>
A: $list = "google.com
http://d.org
google.org
<ul>
<li>www.yahoo.co.uk</li>
<li>http://www.bsdflj.org.uk</li>
<li>nsdfljsdf.org</li>
</ul>";
preg_match_all("~([a-zA-Z0-9-.]+.org)[^\.]~s", $list, $matches);
var_dump ($matches[1]);
$list is what I tested it with.
Output of var_dump():
array(3) {
[0]=>
string(5) "d.org"
[1]=>
string(10) "google.org"
[2]=>
string(13) "nsdfljsdf.org"
}
| |
doc_23529091
|
and I use the Cloud Foundry CLI to get the environment variables: cf env my-app,
then I get an output like:
Getting env variables for app my-app in org my-org / space my-space as user@company.com...
System-Provided:
VCAP_SERVICES: {
"service1": [
// ...
],
"service2": [
// ...
]
}
VCAP_APPLICATION: {
// ...
}
User-Provided:
VARIABLE1: value
VARIABLE2: value
Running Environment Variable Groups:
CREDHUB_API: https://credhub.company.com
No staging env variables have been set
How do I filter this output to get only the contents of the environment variable VCAP_SERVICES, so that when I test/debug my app locally, it behaves as if it was attached to the instances of the Cloud Foundry services?
My goal is to write a file named default-env.json containing only:
{
VCAP_SERVICES: {
"service1": [
// ...
],
"service2": [
// ...
]
}
}
Ideally, the command to produce this output should be a zsh one-liner.
A: cf env my-app | sed -n '/VCAP_SERVICES/,/VCAP_APPLICATION/p' | sed '$d' | sed '1s;^;{\n;' | sed '$s/$/}/' > default-env.json
Explanation
*
*sed -n '/VCAP_SERVICES/,/VCAP_APPLICATION/p'
keeps only the section between the regular expressions VCAP_SERVICES and VCAP_APPLICATION.
*sed '$d' deletes the last line (the line containing VCAP_APPLICATION).
*sed '1s;^;{\n;' prepends {\n to the first line.
*sed '$s/$/}/' appends } to the end of the file.
Credits
*
*Handy one-liners for SED
*BASH Prepend A Text / Lines To a File
*SED: insert text after the last line?
A: Another option would be:
cf curl "/v2/apps/$(cf app --guid my-super-cool-app)/env" | jq -r '.system_env_json.VCAP_SERVICES'
Explanation:
*
*$(cf app --guid <your-app-name) will run in a subshell and get the app guid for your app. You could alternatively just replace that bit with the guid for your app, if you know it already (it'll make the command faster).
*cf curl "/v2/apps/<guid>/env" will return all of the env variables for your app.
*jq -r '.system_env_json.VCAP_SERVICES' picks out the bit you want.
You could optionally redirect output to a file.
Other interesting bits from that API:
*
*.application_env_json.VCAP_APPLICATION would give you VCAP_APPLICATION.
*'.environment_json' would give you any env variables you've set
| |
doc_23529092
|
class OptionsPanel extends JPanel{
OptionsPanel op = this;
public OptionsPanel(){
JButton start = new JButton("Rozwiąż sudoku");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//some code to do
}
});
this.add(start);
}
}
here is fragment of a class which contains both gamePanel and OptionsPanel
public Sudoku () {
Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize( new Dimension(1000,550) );
GamePanel gamePanel = new GamePanel();
this.gamePanel = gamePanel;
OptionsPanel optionsPanel = new OptionsPanel();
this.optionsPanel = optionsPanel;
add(gamePanel);
add(optionsPanel);
}
A:
Java 8
Because JPanel extends Component, it can be named using Component#setName(String). I would give gamePanel a custom name so that it is identifiable in an array. For eaxmple, your gamePanel constructor might look like:
public GamePanel() {
this.setName("gamePanel");
}
And you could single it out using that name:
start.addActionListener(e -> java.util.Arrays.stream(op.getComponents()).forEach(c -> {
if (c.getName().equals("gamePanel")) {
((GamePanel) c).method();
}
}));
Java 7
If you cannot use the Stream API or lambda expressions, you can simply use a for loop:
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < op.getComponentCount(); i++) {
Component c = op.getComponent(i);
if (c.getName().equals("gamePanel")) {
((GamePanel) c).method();
}
}
}
});
Other
There is one more approach that is a lot more efficient and less messy. You could include a GamePanel parameter in the OptionsPanel constructor and pass your gamepanel to that:
public OptionsPanel(GamePanel gamePanel){
JButton start = new JButton("Rozwiąż sudoku");
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gamePanel.method();
}
});
this.add(start);
}
Then all you need to do is change how you construct your optionsPanel instance:
public Sudoku () {
Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize( new Dimension(1000,550) );
GamePanel gamePanel = new GamePanel();
this.gamePanel = gamePanel;
// Pass your GamePanel instance to the constructor.
OptionsPanel optionsPanel = new OptionsPanel(gamePanel);
this.optionsPanel = optionsPanel;
add(gamePanel);
add(optionsPanel);
}
| |
doc_23529093
|
In addition, can anyone explain to me how the function
glBlendFunc(GL_SRC_COLOR, GL_ZERO);
works? What's the source scale factor & destination scale factor and how they are used?
A: The alpha function discards fragments based on their alpha. It's part of the fixed pipeline. In the programmable pipeline you'd just compare your alpha as appropriate and call discard if necessary. Alternatively, if you prefer and your blend mode is suitable, just push the alpha down to 0.0.
If you're not using the programmable pipeline then you should use glAlphaFunc — you're explicitly writing things the old fashioned way.
glBlendFunc(GL_SRC_COLOR, GL_ZERO) effectively uses the source pixel's R, G, B, A, as the source scaling factors and 0 as the destination scaling factors. So the output pixel will be a function of the input only and each channel will be squared.
| |
doc_23529094
|
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
Here is my code:
for link in links:
#Go to MP3 converter homepage
self.__driver.get("http://convert2mp3.net/en/")
#Type in the video link
urlinput = self.__driver.find_element_by_id("urlinput")
#TEST
print(str(urlinput))
self.__action.send_keys_to_element(urlinput, "https://www.youtube.com" + link + Keys.ENTER).perform()
The test in the code was to it prove that it is actually able to fetch the element from page. It prints out the following:
<selenium.webdriver.remote.webelement.WebElement (session="509fc04e4130a25f46f6068684b97a1a", element="0.9812681457094412-1")>
<selenium.webdriver.remote.webelement.WebElement (session="509fc04e4130a25f46f6068684b97a1a", element="0.36225331932442084-1")>
So, as you can see, it goes through almost two complete iterations, but will crash on the last line of the second iteration.
Previously, I also put in a test case to output the whole page source to a text file. The element is in fact loaded by the time it gets to the error line, and the element I'm fetching is in fact in that source file. I'm not sure why it fails to work after one time.
EDIT: Someone in the comments asked me to show how I defined links:
yt_url = req.urlopen(vid_link)
#Note here that 'sopa' is BeautifulSoup
yt_page = sopa(yt_url, "html.parser")
#Get all links
temp_links = yt_page.find_all("a", href = True)
links = []
#Filter playlist to get just the video links
for l in temp_links:
if l["href"] not in links and "index" in l["href"] and l["href"].startswith("/watch"):
links.append(l["href"])
return links
A: Solution:
After some further tinkering, I found the answer. In my for loop, I was indeed finding the element again, but what I didn't realize was that Selenium wanted me to also update the ActionChain again. I had initialized it in the constructor, but I added the following line of code right below the beginning of the for loop:
self.__action = chain.ActionChains(self.__driver)
and it worked.
I had assumed that since I had passed a reference to self.__driver the first time, it would have updated information whenever I got a new web address from the driver, but that does not appear to be the way Selenium does things.
| |
doc_23529095
|
1st column goes from 0 to 255, for a total of (256*256) times.
B_1 <- as.data.frame(rep.int(0:255,256*256))
3rd column has the exact same values as the first one, but sorted from least to greatest
B_3 <- as.data.frame(sort(B_1[,1],decreasing = FALSE))
But I cannot think of a simple algorithm for the column in between the two in which I want the following- Every value in B_2 should repeat for 256 sets of 0:255 in B1. In other words, as value increment in B_3, the value in B_2 is reset to 0, for 256 times. I can join the three vectors to make the array afterwards easily enough. The purpose is illustrated in the following piece of code.
j= 0
for (i in 1: 16777216){
B_2[i,1]=j
if(B_1[i,1]>B_1[i+1,1]){
j = j + 1
}
if (j>255){
j=0
}
}
But as you can imagine, for an array of this size, for loop is highly inefficient. I understand that tidyverse will probably have a method to do this easily, but I was hoping to find one within the base packages of R. Can this be done?
A: If I understand you correctly, this is what you need.
B_3 <- as.data.frame(rep(0:255, each=255))
| |
doc_23529096
|
from time import sleep
fight = False
def start_up():
print("Fight Simulator - Test Stages.")
userInput = str(input("Enter your name "))
user_name = userInput
return user_name
def intro():
userName = start_up()
while True:
userInput = str(input("Welcome to the dojo, {}. To commence the first battle, type 'Start', or 'Begin'".format(userName)))
if userInput == "Start" or "start" or "Begin" or "begin":
return userInput
else:
print("Enter a valid response")
break
def fight_commence():
userInput = intro()
if userInput == "Start" or "start" or "Begin" or "begin":
fight = True
userHp = 100
opponentHp = 100
while fight == True:
userDmg = randint(0,100)
opponentDmg = randint(0,100)
opponentHp -= userDmg
if opponentHp <= 0:
opponentHp == 0
print("You did {} damage".format(userDmg))
sleep(1)
print("Opponent has {} hp remaining".format(opponentHp))
sleep(1)
if opponentHp <= 0:
print("You killed him!")
fight = False
else:
print("Enter a valid action")
fight_commence()
So for some reason the code doesn't print("Enter a valid response") when a response other than "Start" or "start" or "Begin" or "begin" is given. I want it to loop back to userinput stage, but instead it just carries on with the program as if everything is A ok. I can't figure out where I messed up.
Secondly, I want the opponentHp to automatically equal 0 when the health dips below 0. For instance, when opponentHp = -45, opponentHp should equal 0.
Any help is appreciated.
A: Well a big problem with the testing of the 'valid input' is the way your testing.
if userInput == "Start" or "start" or "Begin" or "begin"
This is not a valid python condition. Instead do something like this:
if userInput in ["Start", "start", "Begin", "begin"]
This comparison happens twice and is no good. For the opponenthp being 0, you currently have this as your statement and result:
if opponentHp <= 0:
opponentHp == 0
The condition is perfectly fine, but the == in the action is another conditional operator, you need to change it to:
if opponentHp <= 0:
opponentHp = 0
ADDITION
Also, in addition to the above items, when you use the break statement you will end the infinite loop you have set up and end the function without a returned value, you may want to consider changing it to a continue or pass statement, or simply remove it.
A: The conditions (if-clause) are wrong. You should repeat 'userInput==' for every or.
Or, more concisely this:
userInput.lower() in ["start", "begin"]
| |
doc_23529097
|
This is a snippet from my model:
class SmallProduct(models.Model):
name = models.CharField(max_length=35)
description = models.CharField(max_length=500)
price = CurrencyField()
image = models.ImageField(upload_to='img/product/')
category = models.ForeignKey(Category)
class Product(models.Model):
small_products = models.ManyToManyField(SmallProduct, through='Ordering')
#some other fields
class Ordering(models.Model):
small_product = models.ForeignKey(SmallProduct)
product = models.ForeignKey(Product)
date = models.DateField(auto_now_add=True)
I tried the Django Shop app and Satchmo but these apps does not fit my requirements. I dont want to rewrite a whole shop system, so I would be really glad if anyone has a smart idea how I can customize one of these apps to fit my requirements. Any help would be greatly appreciated.
A: U may try Cartridge which allows u to hook the payment steps and gives a control to you on shopping cart and other shopping objects. Also it allows u to add extra fields to the models without monkey patching.
U can do easily what u told with Cartridge.This link may give u an opinion about that:
http://cartridge.jupo.org/integration.html
| |
doc_23529098
|
i am having problem in mysql database connectivity in cloud9.io environment in sails js project.
Steps
1)mysql-ctl start
2)phpmyadmin-ctl install
it worked and opened phpmyadmin page for me.i created db there.
3)mysql-ctl cli
4)mysql> \r
here's the problem its giving
connection id:1
Current database: *** NONE
There is no error in console while running sails lift.it gives error on executing queries.i have tried all following links related to my problem but no use.
Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
and few more.
| |
doc_23529099
|
Also I have verified the AZURE AD Graph API catalogs mentioned below but i cannot able to find anything related to it.
https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/api-catalog
A: You cannot unlock a user account. See https://learn.microsoft.com/en-us/azure/active-directory/active-directory-passwords-policy for details of how account lockout duration is calculated by default.
if you have configured smart lockout policies, user remains locked based on the lockout duration specified in https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect-pass-through-authentication-smart-lockout
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.