_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1601 | train | You're POSTing your credentials to "/api/accounts/j_spring_security_check", while the monitored URL is just "/j_spring_security_check". You should construct the action URL in the form using:
<c:url value="/j_spring_security_check"/>
So the result would be:
<form name="f" action="<c:url value="/j_spring_security_check"/>" method="post">
Update after changed question...
Your authentication fails throwing Exception or returning null. The result of call to your UserDetailsProvider are checked like this (inside DaoAuthenticationProvider) with the result of throwing AuthenticationServiceException:
try {
loadedUser = this.getUserDetailsService().loadUserByUsername(username);
} catch (UsernameNotFoundException notFound) {
throw notFound;
} catch (Exception repositoryProblem) {
throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
}
if (loadedUser == null) {
throw new AuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
You should:
*
*improve your code to include some logging
*start debugger and go through your code to see what fails or returns null
*or implement a custom AuthenticationFailureHandler which will print complete content of the exception it receives as a parameter and plug it instead of the default one | unknown | |
d1602 | train | do() is called tap() in RxJS 6+. | unknown | |
d1603 | train | If you haven't figured out the issue yet, it's likely that you don't have write permissions to the directory the image is in. | unknown | |
d1604 | train | As @jezrael commented, it was missing ( from df[PCR]=='not_detec' | unknown | |
d1605 | train | to reply to a callback query with a msg, photo, audio, video document you have to do:
import time
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
TOKEN = "super secret bot token"
def on_chat_message(msg):
#here you handel messages and create the iniline keyboard
content_type, chat_type, chat_id = telepot.glance(msg)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='button text', callback_data='callback query data for reconizing it')],
])
def on_callback_query(msg):
#here you handels callback querys,
#the event that are fired when user clickan inline keyboard'sbutton
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
#do something HERE based on the callback query to reply,
#to recognize the button pressed check query_data,
#that corresponds to he callback_data setted when creating the button
#to send text messages:
bot.sendMessage(chat_id, "your test message")
#to send photo:
bot.sendPhoto(chat_id, "C:/path/to/your/photo or https://link.to/your/photo")
#to send video:
bot.sendPhoto(chat_id, "C:/path/to/your/video or https://link.to/your/video")
#to send audio:
bot.sendPhoto(chat_id, "C:/path/to/your/audio or https://link.to/your/audio")
#to send document:
bot.sendPhoto(chat_id, "C:/path/to/your/document or https://link.to/your/document")
#please note that you can do the exactly above thing
#in the on_chat_message to reply to a txt message
#ans that in any case you can use if...else statement to make the
#reply different by the msg/inline button pressed
bot = telepot.Bot(TOKEN)
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
while True:
time.sleep(10) | unknown | |
d1606 | train | I personally think a "where not exists" type of clause might be easier to read, but here's a query with a join that does the same thing.
select distinct u.* from User u
left join User_Prefs up ON u.id = up.user_id and up.pref = 'EMAIL_OPT_OUT'
where up.user_id is null
A: Why not have your user preferences stored in the user table as boolean fields? This would simplify your queries significantly.
SELECT * FROM User WHERE EMAIL_OPT_OUT = false | unknown | |
d1607 | train | You should identify when the text is the final answer and reset the text before adding new one.
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
Window.size = (350, 450)
class MainWidget(Widget):
def __init__(self):
self.textIsResult = false
def clear(self):
self.ids.input.text=""
def back(self):
expression = self.ids.input.text
expression = expression[:1]
self.ids.input.text = expression
def pressed(self, button):
expression = self.ids.input.text
if self.textIsResult:
self.ids.input.text = f"{button}"
if "Fault" in expression:
expression = ""
self.textIsResult = false
if expression == "0":
self.ids.input.text = ""
self.ids.input.text = f"{button}"
else:
self.ids.input.text = f"{expression}{button}"
def answer(self):
expression = self.ids.input.text
try:
self.ids.input.text = str(eval(expression))
self.textIsResult = true
except:
self.ids.input.text = "Fault"
class TheLabApp(App):
pass
TheLabApp().run() | unknown | |
d1608 | train | I suspect (!?) this is excluded from Task on retrieval perhaps for security reasons but, it appears not possible to get the request body from tasks in the queue.
Note: On way to investigate this is to use e.g. Chrome's Developer Tools to understand how Console achieves this.
You can validate this using gcloud and APIs Explorer:
gcloud tasks list \
--queue=${QUEUE} \
--location=${LOCATION} \
--project=${PROJECT} \
--format=yaml \
--log-http
Note: You don't need the --format to use --log-http but I was using both.
Or: projects.locations.queues.tasks.list and filling in the blanks (you don't need to include API key).
Even though all should be Task in my case (using HttpRequest, the response does not include body.
IIRC, when I used Cloud Tasks a while ago, I was similarly perplexed at being unable to access response bodies. | unknown | |
d1609 | train | You should rethrow the error/throw a new error to catch error again.
It's an example:
Promise.reject("throwed on demo 1")
.catch((e) => {
console.log("Catched", e)
})
.catch((e) => {
// unreached block
console.log("Can NOT recatch", e)
})
Promise.reject("throwed on demo 2")
.catch((e) => {
console.log("Catched", e)
throw e
})
.catch((e) => {
console.log("Recatched", e)
})
UPDATE: Another issue, you need to send a response even error/success. Otherwise, the request will not respond, the client will be pending forever.
_server.get(`/select`, (req, res) => {
return DefaultSQL.select(table).then((result) => {
res.send(result)
//return result
}).catch((err) => {
res.status(500).send(err)
console.log(err)
});
}) | unknown | |
d1610 | train | ID's should never be repeated, use the class of the buttons instead as a common attribute.
A: You are binding to all the elements and you are duplicating ids. Ids are singular.
You would be better off with either binding to the one button alone or event delegation with a data attribute.
userDataRef.on('child_added', function(childSnapshot) {
/* cut out the vars */
var myRow = $("<tr><td>" + title_val + "</td><td><a href=" + url_val + " target='_blank'> <button class='box'>GO</button></a></td><td><button class='box'>Delete</button></a></td></tr>");
myRow.find("button").on("click", function(){
console.log(key)
});
$("#data").append(myRow);
});
or event delegation with a data attribute
$("#data").on("click", "button[data-key]", function(evt){
var btn = $(this);
console.log(btn.data("key"))
});
userDataRef.on('child_added', function(childSnapshot) {
/* cut out the vars */
var myRow = $("<tr><td>" + title_val + "</td><td><a href=" + url_val + " target='_blank'> <button class='box'>GO</button></a></td><td><button class='box' data-key='" + key + "'>Delete</button></a></td></tr>");
$("#data").append(myRow);
}); | unknown | |
d1611 | train | Just open the csv file in append mode. This will solve your problem.
Use:
with open("pav.csv",'a',newline='') as wr:
A: You need to open the file in append mode so that it will write to the end of the file:
with open("C:\pavan\pav.csv",'a',newline='') as wr:
This will open the file in write mode, and append to the end of the file if it exists. | unknown | |
d1612 | train | Under some conditions, the code in this line:
$thisSheet = $objPHPExcel->addSheet($myWorkSheet);
$thisSheet will be null,
change the following code to:
if ($thisSheet) {
for ($k=0;$k<count($myQueryArray);$k++){
$thisSheet->write(0, $k, $titleList[$myQueryArray[$k]]); //Error on this line
}
}
to avoid the error.
The reason why $objPHPExcel->addSheet reutuns null may be that the memory usage is reach limit, you can use ini_set("memory_limit", -1); to set memory usage to unlimited. | unknown | |
d1613 | train | Sanjeev got it, there is a parameter you can add to specify version:
FacebookClient fbClient = new FacebookClient();
fbClient.Version = "v2.2";
fbClient.Post("me/feed", new
{
message = string.Format("Hello version 2.2! - Try #2"),
access_token = "youraccesstokenhere"
});
If you are not specifying a version, it'll default to the oldest supported version:
https://developers.facebook.com/docs/apps/versions#unversioned_calls
Facebook will warn you that you are nearing end of support for that version.
Don't take any chances that the auto-upgrade to newer version will work, better to develop, test and deliver with the latest version. | unknown | |
d1614 | train | Without knowing too much about the module I have a theory:
The first evaluation (ngModel && ngModel.$modelValue), when true, returns a Boolean which does not have a slice method.
A: There was an issue filed in Github about this https://github.com/danialfarid/ng-file-upload/issues/1139
Reportedly fixed in release 10.0.3. | unknown | |
d1615 | train | You can use Import/Export option for this task.
*
*Right click on your table
*Select "Import/Export" option & Click
*Provide proper option
*Click Ok button
A: You should try this it must work
COPY kordinater.test(id,date,time,latitude,longitude)
FROM 'C:\tmp\yourfile.csv' DELIMITER ',' CSV HEADER;
Your csv header must be separated by comma NOT WITH semi-colon or try to change id column type to bigint
to know more
A: I believe the quickest way to overcome this issue is to create an intermediary temporary table, so that you can import your data and cast the coordinates as you please.
Create a similar temporary table with the problematic columns as text:
CREATE TEMPORARY TABLE tmp
(
id integer,
date date,
time time without time zone,
latitude text,
longitude text
);
And import your file using COPY:
COPY tmp FROM '/path/to/file.csv' DELIMITER ';' CSV HEADER;
Once you have your data in the tmp table, you can cast the coordinates and insert them into the test table with this command:
INSERT INTO test (id, date, time, latitude, longitude)
SELECT id, date, time, replace(latitude,',','.')::numeric, replace(longitude,',','.')::numeric from tmp;
One more thing:
Since you're working with geographic coordinates, I sincerely recommend you to take a look at PostGIS. It is quite easy to install and makes your life much easier when you start your first calculations with geospatial data. | unknown | |
d1616 | train | What you need is a way to check if variable is defined and not-empty. Bash has built in for it. (-z)
if [ -z "$VAR" ];
More details at question in server fault question: How to determine if a bash variable is empty? | unknown | |
d1617 | train | Unfortunatelly, FTP won't work.
DownloadManager supports HTTP. And HTTPS is supported since ICS.
If you try downloading from FTP you receive one of these exceptions:
java.lang.IllegalArgumentException: Can only download HTTP URIs
or
java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs | unknown | |
d1618 | train | Use where statement:
$products = ORM::factory('products')->where('contry_id', 'NOT IN', $csl)->find_all();
$csl must be array | unknown | |
d1619 | train | Managed to solve this .
had to use a templating language (jinja2) instead of ajax, to get my form schema into my html document.. so that json form ( a jquery form builder) couple execute on a full html doc on the page loading .
Silly !
Hope this helps . | unknown | |
d1620 | train | It turns out that /arch:CORE-AVX2 is recognized and compiled executable contains FMA instructions! I really do not understand why this option is not listed in Visual Studio and in ICL /help ?!?
Dropbox menu in Visual Studio (NO AVX2!)
http://i.cubeupload.com/c1xidV.png
ICL /help
http://i.cubeupload.com/y2Cre6.png
A: The Ryzen supports these instruction sets, but the code will not run on AMD processors because it checks if the processor is "GenuineIntel". There has been a long discussion and legal battle about this issue. See http://www.agner.org/optimize/blog/read.php?i=49 | unknown | |
d1621 | train | It depends on the app you are building.
Database connection pools are used because of following reasons:
*
*Acquiring DB connection is costly operation.
*You have limited resources and hence at a time can have only finite number of DB connections open.
*Not all the user requests being processed by your server are doing DB operations, so you can reuse DB connections between requests.
Since acquiring new connections are costly, you should keep min_size to be non-zero. Based on what is load during light usage of your app, you can use a good guess here. Typically, 5 is specified in most examples.
acquire_increment depends on how the fast the number of users that are using your app increases. So, imagine if you ask 1 new connection every time you needed an extra connection, your app may perform badly. So, anticipating user burst, you may want to increment in larger chunks, say 5 or 10 or more.
Typically, max. number of DB connections you have can be lesser than the number of concurrent users that are using your app. However, if you are application is database-heavy, then, you may have to configure max_size to match the number of concurrent users you have.
There will be a point when you may not be able to deal with so many users even after configuring max_size to be very high. That's when you will have to think about re-designing your app to avoid load on database. This is typically done by offloading read operations to alternate DB instance that serves only read operations. Also, one employs caching of such data which do not change often but are read very often.
Similar justification can be applied for other fields as well | unknown | |
d1622 | train | "no makefile found" usually means you have no file named literally GNUmakefile, makefile or Makefile in the current directory (or the directory pointed at if you use -C).
In the Makefile you need to specify at least one rule so that make can do something. The first rule in the file (sequentially, not chronologically) becomes the default rule, so you don't actually have to specify a target like the error message indicates. | unknown | |
d1623 | train | We could use get to get the value of the object. If there are multiple objects, use mget. For example, here I am assigning 'debt_a' with the value of 'debt_30_06_2010'
assign('debt_a', get(paste0('debt_', date[1])))
debt_a
#[1] 1 2 3 4 5
mget returns a list. So if we are assigning 'debt_a' to multiple objects,
assign('debt_a', mget(paste0('debt_', date)))
debt_a
#$debt_30_06_2010
#[1] 1 2 3 4 5
#$debt_30_06_2011
#[1] 6 7 8 9 10
data
debt_30_06_2010 <- 1:5
debt_30_06_2011 <- 6:10
date <- c('30_06_2010', '30_06_2011')
A: I'm not sure if I understood your question correctly, but I suspect that your objects are names of functions, and that you want to construct these names as characters to use the functions. If this is the case, this example might help:
myfun <- function(x){sin(x)**2}
mychar <- paste0("my", "fun")
eval(call(mychar, x = pi / 4))
#[1] 0.5
#> identical(eval(call(mychar, x = pi / 4)), myfun(pi / 4))
#[1] TRUE | unknown | |
d1624 | train | Make sure you add python to the Windows path environment variable.
Check this resource to find out how to do that.
A: Control Panel -> add/remove programs -> Python -> change-> optional Features (you can click everything) then press next -> Check "Add python to environment variables" -> Install
enter image description here
I followed the link specially the image .... | unknown | |
d1625 | train | From the sample I don't understand the usage of percentage sizing. I suppose this is the issue. You enable it initially but the parent composite doesn't has a size, therefore the width of all columns is set to 0. By enabling it again the column widths are not automatically set to some width and stay 0.
The width of the table is derived from the columns. In case of the ViewportLayer the width is maxed to the available client area. But as all columns have a width of 0, the width of the whole NatTable is 0. And setting the default column width after percentage sizing was enabled will probably also not lead to the result you expect, because there is a size value for every column stored, which overrides the default width.
In short, your whole idea doesn't seem to work with NatTable. | unknown | |
d1626 | train | It looks like you have the most serious issue of view scale addressed, the other issues are proper YCbCr rendering (which it sounds like you are going to avoid by outputting BGRA pixels when decoding) and then there is scaling the original movie to match the dimensions of the view. When you request BGRA pixel data the data is encoded as sRGB, so you should treat the data in the texture as sRGB. Metal will automatically do the non-linear to linear conversion for you when reading from a sRGB texture, but you have to tell Metal that it is sRGB pixel data (using MTLPixelFormatBGRA8Unorm_sRGB). To implement scaling, you just need to render from the BGRA data into the view with linear resampling. See the SO question I linked above if you want to have a look at the source code for MetalBT709Decoder which is my own project that implements proper rendering of BT.709. | unknown | |
d1627 | train | Use parseFloat instead of parseInt. And toFixed(2) for limiting two decimal points.
setInterval(function() {
var counters = document.getElementsByClassName("count");
for (var i = 0; i < counters.length; i++) {
counters[i].innerHTML = parseFloat(counters[i].innerHTML).toFixed(2) + parseFloat(counters[i].dataset.increment).toFixed(2);
}
}, 1000);
A: JSFIDDLE
You need to use parseFloat to covert string to float.
and toFixed on float to truncate extra decimal. toFixed return string you need to use parseFloat again so that it became float addition not string concatenation.
var counters = document.getElementsByClassName("count");
setInterval(function () {
for(var i = 0 ; i < counters.length ; i++) {
counters[i].innerHTML = (parseFloat(parseFloat(counters[i].innerHTML).toFixed(2)) + parseFloat(parseFloat(counters[i].dataset.increment).toFixed(2))).toFixed(2);
}
}, 1000);
<div class="count" data-increment="10">10</div>
<div class="count" data-increment="10.02">10.02</div>
A: Try wrapping addition within String() , .innerHTML , .dataset within Number() , Number() within expression () chained to .toFixed(2) ; set counters[i].innerHTML to result derived within String((Number(/* innerHTML */) + Number(/* dataset *)).toFixed(2))
var interval = setInterval(function() {
var counters = document.getElementsByClassName("count");
for (var i = 0; i < counters.length; i++) {
counters[i].innerHTML = String((Number(counters[i].innerHTML)
+ Number(counters[i].dataset.increment)).toFixed(2));
}
}, 1000);
<div class="count" data-increment="10.02">10.02</div> | unknown | |
d1628 | train | Read the process output stream and check for the input prompt, if you know the input prompt, then put the values to process inupt stream.
Otherwise you have no way to check.
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
BufferedReader b1 = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter w1 = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String line = "";
String outp = "";
while ((line = b1.readLine()) != null) {
if (line.equals("PLEASE INPUT THE VALUE:")) {
// output to stream
w1.write("42");
}
outp += line + "\n";
}
...
UPD: for your code it should be something like that
ProcessBuilder pb2=new ProcessBuilder("/home/ahijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);
script_exec = pb2.start();
OutputStream in = script_exec.getOutputStream();
InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());
pb2.redirectError();
BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));
StringBuffer out=new StringBuffer();
String output_line = "";
while ((output_line = reader1.readLine())!= null)
{
out=out.append(output_line+"/n");
System.out.println("val of output_line"+output_line);
//---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream
if (output_line.equals("PLEASE INPUT THE VALUE:")) {
// output to stream
in.write("42");
}
} | unknown | |
d1629 | train | Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart.
Here's an example upstart config for a hypothetical Python service:
description "My service"
author "Some Dude <[email protected]>"
start on runlevel [234]
stop on runlevel [0156]
chdir /some/dir
exec /some/dir/script.py
respawn
If you save this as script.conf to /etc/init you simple do a one-time
$ sudo initctl reload-configuration
$ sudo start script
You can stop it with stop script. What the above upstart conf says is to start this service on reboots and also restart it if it dies.
As for signal handling - your process should naturally respond to SIGTERM. By default this should be handled unless you've specifically installed your own signal handler.
A: Rloton's answer is good. Here is a light refinement, just because I spent a ton of time debugging. And I need to do a new answer so I can format properly.
A couple other points that took me forever to debug:
*
*When it fails, first check /var/log/upstart/.log
*If your script implements a daemon with python-daemon, you do NOT use the 'expect daemon' stanza. Having no 'expect' works. I don't know why. (If anyone knows why - please post!)
*Also, keep checking "initctl status script" to make sure you are up (start/running). (and do a reload when you update your conf file)
Here is my version:
description "My service"
author "Some Dude <[email protected]>"
env PYTHON_HOME=/<pathtovirtualenv>
env PATH=$PYTHON_HOME:$PATH
start on runlevel [2345]
stop on runlevel [016]
chdir <directory>
# NO expect stanza if your script uses python-daemon
exec $PYTHON_HOME/bin/python script.py
# Only turn on respawn after you've debugged getting it to start and stop properly
respawn | unknown | |
d1630 | train | I tried following query:
SELECT username, friend_count
FROM user
WHERE username = jonathan.petitcolas
But, as you can see, the friend_count property is always null. On my public profile, and also on other profiles.
Nope, it’s not always null. If I do that query with my own user name (and correcting the syntax error in your query), I get back the correct number of friends. Only if I authenticated that app making the query, of course.
So, is it possible to retrieve number of friends of a public profile on Facebook?
Nope.
That says enough already:
“Can only lookup for the logged in user or the logged in user's friends that are users of your app.” | unknown | |
d1631 | train | Sometimes SWFRender is stuck at very heavy files, especially when producing 300dpi+ images. In this case Gnash may help:
gnash -s<scale-image-factor> --screenshot last --screenshot-file output.png -1 -r1 input.swf
here we dump a last frame of a movie to file output.png disabling sound processing and exiting after the frame is rendered. Also we can specify the scale factor here or use
-j width -k height
to specify the exact size of resulting image.
A: You could for example build an AIR app that loads each SWF, takes the screenshot and writes it to a file.
The thing is you'll need to kick off something to do the render and, as far as i know, you can't do that without the player or some of its Open Source implementation.
I think your best bet is going AIR, the SDK is free and cross-platform. If you are used to python, the AS3 necessary should be easy enough to pick up.
HTH,
J
A: I'm sorry to answer my own question, but I found an undocumented feature of swfrender (part of the swftools) by browsing through the sources.
swfrender path/to/my.swf -X<width of output> -Y<height of output>
-o<filename of output png>
As you might have guessed the X option lets you determine the width (in pixels) of the output and Y does the same for the height. If you just set one parameter, then the other one is chosen in relation to the original height-width-ratio (pretty useful)
That does the trick for me but as Zarate offered a solution that might be even better (I'm thinking of swf to PDF conversion) he deserves the credits.
Cheers | unknown | |
d1632 | train | You have a infinite recursive loop.
if(*this == temp)
calls bool operator==(opo temp) which contains the if statement which in turn call the function again and so on. This will cause the program to run out of resources eventually cause a stack overflow or segfault.
When you ceck for equality you need to check the members. Since you class is stateless(no members) any two objects should be equal.
If you had class members like
class Foo
{
public:
int a, b;
};
Then we would have a comparison object like
bool Foo::operator ==(const Foo & rhs)
{
return a == rhs.a && b == rhs.b;
// or with std::tie
return std::tie(a, b) == std::tie(rhs.a, rhs.b);
}
A: bool opo::operator==(opo temp)
{
if(*this == temp) // calls this->operator==(temp)
This just calls the same function again, leading to an infinite recursion and, eventually, stack overflow.
You need to come up with some actual way to tell if two objects are identical, and then do that.
As an aside, your operator's signature is weird. You're forcing a temporary copy of the right-hand-side argument (a2 in your original code). A more normal implementation might look like
struct opo {
int m_value = 0;
bool operator== (opo const &) const;
};
bool opo::operator==(opo const &other) const {
// actually compare something
return m_value == other.m_value;
}
Notes:
*
*we take the right-hand-side argument by reference, meaning we don't create a temporary copy
*we take it by const reference, meaning we promise not to change it (why would you change something while comparing it?)
*our operator is also marked const, so we'er promising not to change the left-hand-side either
*I added a member so I have something to compare | unknown | |
d1633 | train | <input id="uploadBtn" type="file" class="upload" name="pimage">
Function media_handle_upload upload your image in wordpress
Use $filename = $_POST['filename']['temp_name']; not $filename = $_POST['filename'];
if ( !empty( $_FILES["pimage"]["name"] ) ) {
$attachment_id = media_handle_upload( 'pimage', 0 );
} | unknown | |
d1634 | train | A few issues you can run into if you just kill the sqlldr process:
*
*If the number of commit rows is small you may have data already-commited which will now have to be removed. This may not matter if you are truncating the tables before use but the cleanup is an operational issue that is dependent upon your system.
*If the number of commit rows and the size of your file is large then you may get issues with the rollback segments being too small or the rollback itself taking a long time to complete (shouldn't an issue if you are using direct path).
You can kill using kill -9 as mentioned, or you can kill the session from within the database:
alter system kill session 'sid,serial#';
If you are using Windows then you can use the orakill utility. | unknown | |
d1635 | train | I guess in foo you assign ptr some value (otherwise the *& has no value). You cannot pass nullptr and you have to declare a pointer like you shown in the wrapper because nullptr is an rvalue. An rvalue is an expression, or an "unnamed object" and you cannot take the address of it. There is more information here Why don't rvalues have an address?. | unknown | |
d1636 | train | Your approach must be generally refactored. I don't say about code - just about architecture. It has a big problem with memory - let's calculate!
*
*The size of the one RGB frame 1920x1080: frame_size = 1920 * 1080 * 3 = 6 Mb
*How many frames do you want capture from 2 cameras? For example 1 minute of video with 30 fps: video_size = 2 camera * 6 Mb/frame * 60 seconds = 21 Gb! Do you have so memory per process?
I advice to make queues in different threads for capture frames and 2 threads for pick up frames from capture queues and write it to files. | unknown | |
d1637 | train | You have two problems in money():
Sub money(ByVal t1 As Integer)
'prend cash'
If temp = 6 Then
Console.WriteLine("Jackpot $$$$$$$$$$$$$")
ElseIf temp = 3 Then
Console.WriteLine(" money = 120")
ElseIf temp = 4 Then
Console.WriteLine("money = 500")
ElseIf temp = 5 Then
Console.WriteLine("money= 10,000")
Else
Console.WriteLine(" try next time")
End
End If
End Sub
Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...
A: I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random
Public Sub Main()
'keep variables with as narrow a scope as possible
Dim answer As String = Nothing
'This line initializes and array of strings called words
Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
Dim WinnersChosen(5) As Integer
Do
'To shorten your code use a For loop
For index = 0 To 5
Console.WriteLine($"Please enter your {words(index)} number")
WinnersChosen(index) = CInt(Console.ReadLine)
Next
Dim RandomWinners = GetRandomWinners()
Console.WriteLine("The random winners are:")
For Each i As Integer In RandomWinners
Console.WriteLine(i)
Next
Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)
If WinnersCount = 1 Then
Console.WriteLine($"You have guessed {WinnersCount} number")
Else
Console.WriteLine($"You have guessed {WinnersCount} numbers")
End If
Dim Winnings = Money(WinnersCount)
'The formatting :N0 will add the commas to the number
Console.WriteLine($"Your winnings are {Winnings:N0}")
Console.WriteLine("do you want to continue? y/n")
answer = Console.ReadLine.ToLower
Loop Until answer = "n"
Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
Dim RandomWinners As New List(Of Integer)
Dim rn As Integer
'Good use of .Contains and good logic in Loop Until
Do
rn = rg.Next(1, 40)
If Not RandomWinners.Contains(rn) Then
RandomWinners.Add(rn)
End If
Loop Until RandomWinners.Count = 6
Return RandomWinners
End Function
Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
Dim temp As Integer
For count1 As Integer = 0 To 5
For count2 As Integer = 0 To 5
If r(count1) = WinnersChosen(count2) Then
temp = temp + 1
End If
Next
Next
Return temp
End Function
Private Function Money(Count As Integer) As Integer
'A Select Case reads a little cleaner
Select Case Count
Case 3
Return 120
Case 4
Return 500
Case 5
Return 10000
Case 6
Return 1000000
Case Else
Return 0
End Select
End Function
End Module | unknown | |
d1638 | train | you could just use the php function glob() to get all filenames from the download directory. then setup a cronjob for every 5m or whatever interval you want where you save the names to your database. | unknown | |
d1639 | train | In your onCellMouseOver you can get the row index (e.rowIndex). From that you can get the item from the grid assuming you are using an ItemFileReadStore (I have not tried it with a ItemFileWriteStore)
function cellMouseOver (e)
{
var rowIndex = e.rowIndex;
var item = grid.getItem(e.rowIndex);
} | unknown | |
d1640 | train | This is usually because sometimes the mouse is not over the clip when MOUSE_UP occurs, either because of other clips getting in the way or maybe the player is not refreshing the stage fast enough, etc...
I'm not sure this is your case, but either way it is often recommended to assign the MOUSE_UP event to the stage, so you can safely assure it is always triggered. Make sure to remove the listener on the mouseUp handler though ;)
spr["sprite"].addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
public function mouseDownHandler(me:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
}
public function mouseUpHandler(me:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
}
The down side is that you lose your clip reference on mouseUp, but you can create a reference by hand on mouseDown, or do the whole thing internally (within the sprite's code). | unknown | |
d1641 | train | I found:
*
*hibernate.cfg.xml is not neede
*only persistence.xml and tomee.xml are required
I give you my example:
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="docTracingPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:comp/env/jdbc/docTracing</jta-data-source>
<non-jta-data-source>java:comp/env/jdbc/docTracing</non-jta-data-source>
<class>com.emaborsa.doctracing.core.persistentobject.UtentePO</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.transaction.flush_before_completion" value="true"/>
<property name="hibernate.transaction.auto_close_session" value="true"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.apache.openejb.hibernate.TransactionManagerLookup" />
<property name="hibernate.transaction.flush_before_completion" value="true"/>
<property name="hibernate.transaction.auto_close_session" value="true"/>
<!-- Print SQL to stdout. -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
<?xml version="1.0" encoding="UTF-8"?>
<tomee>
<Resource id="docTracingPU" type="DataSource">
JdbcDriver org.postgresql.Driver
JdbcUrl jdbc:postgresql://127.0.0.1:5432/myDb
UserName ****
Password ****
JtaManaged false
TestWhileIdle true
InitialSize 5
</Resource>
<Resource id="docTracingPU" type="DataSource">
JdbcDriver org.postgresql.Driver
JdbcUrl jdbc:postgresql://127.0.0.1:5432/myDb
UserName *****
Password *****
JtaManaged true
TestWhileIdle true
InitialSize 5
</Resource>
</tomee> | unknown | |
d1642 | train | I've got exactly the same problem for a few days.
I finally got a way to solve it temporarily.
GoogleMaps has released a new version (3.19) the 17th of February.
You can force your pages use the previous version (3.18), which is unchanged, by adding in the javascript parameters the version :
<script language="JavaScript"
type="text/javascript"
src="http://maps.google.fr/maps/api/js?sensor=false&language=fr&v=3.18">
With the 3.18 version, maps are correctly displayed.
We have now to find what we have to change to make the 3.19 version work ! | unknown | |
d1643 | train | The blocking of bad bots is a non discrete, nebulous task so I'll deal with that at the end of this answer.
After each itemized question I'll adjust the .htaccess to cover the solution along with all previous questions. The final solution will address all questions.
1. Switches my site from http to https
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com [R=301,L]
2. Switches my site from https://with no www to https://with www.
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]
4. Prevent viewing of .htaccess file
Taken from How to deny access to a file in .htaccess
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]
5. Add compression to ALL file types on the site*
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
*Note that not all file types should/could be compressed. I've added the boilerplate that we used to use above which seemed to work well. If you're interested in truly maximizing compression opportunities without the complexities of browser compatibility, look into ModPagespeed
3. block bad bots
I wish it was easy as BlockBadBots yes. If you'd prefer to not analyze bandwidth usage and blocking of bots based on consumption etc., I would recommend that you put your site behind CloudFlare. This service has a good reputation for dealing with high profile DDOS attacks, limiting harmful bots, and keeping sites alive even as demand increases.
Good luck! | unknown | |
d1644 | train | That (notice) message is based on changes to PHP 7.
So an old way of using a constructor is still in use, is what that message means. It will be ok at the moment, until the support is completely removed in the future. However, I don't believe that should/would cause any connection trouble ?
What is expected is instead of having a class with a constructor like this:
<?php
class foo {
function foo() {
echo 'I am the constructor';
}
}
?>
... would now be expected to look like this:
<?php
class foo {
function __construct() {
echo 'I am the constructor';
}
}
?>
See the first section section of this PHP 7 deprecation info.
You could apply that change yourself, just comment-out the old way, and use the other constructor form. | unknown | |
d1645 | train | No, there's no way to do it, and you should not think of it this way. The sender should perform the same no matter what number of slots are connected to a signal. That's the basic contract of the signal-slot mechanism: the sender is completely decoupled from, and unaware of, the receiver.
What you're trying to do is qualified dispatch: there are multiple receivers, and each receiver can process one or more message types. One way of implementing it is as follows:
*
*Emit (signal) a QEvent. This lets you maintain the signal-slot decoupling between the transmitter and the receiver(s).
*The event can then be consumed by a custom event dispatcher that knows which objects process events of given type.
*The objects are sent the event in the usual fashion, and receive it in their event() method.
The implementation below allows the receiver objects to live in other threads. That's why it needs to be able to clone events.
class <QCoreApplication>
class <QEvent>
class ClonableEvent : public QEvent {
Q_DISABLE_COPY(ClonableEvent)
public:
ClonableEvent(int type) : QEvent(static_cast<QEvent::Type>(type)) {}
virtual ClonableEvent * clone() const { return new ClonableEvent(type()); }
}
Q_REGISTER_METATYPE(ClonableEvent*)
class Dispatcher : public QObject {
Q_OBJECT
QMap<int, QSet<QObject*>> m_handlers;
public:
Q_SLOT void dispatch(ClonableEvent * ev) {
auto it = m_handlers.find(ev->type());
if (it == m_handlers.end()) return;
for (auto object : *it) {
if (obj->thread() == QThread::currentThread())
QCoreApplication::sendEvent(obj, ev);
else
QCoreApplication::postEvent(obj, ev.clone());
}
}
void addMapping(QClonableEvent * ev, QObject * obj) {
addMapping(ev->type(), obj);
}
void addMapping(int type, QObject * obj) {
QSet<QObject*> & handlers = m_handlers[type];
auto it = handlers.find(obj);
if (it != handlers.end()) return;
handlers.insert(obj);
QObject::connect(obj, &QObject::destroyed, [this, type, obj]{
unregister(type, obj);
});
m_handlers[type].insert(obj);
}
void removeMapping(int type, QObject * obj) {
auto it = m_handlers.find(type);
if (it == m_handlers.end()) return;
it->remove(obj);
}
}
class EventDisplay : public QObject {
bool event(QEvent * ev) {
qDebug() << objectName() << "got event" << ev.type();
return QObject::event(ev);
}
public:
EventDisplay() {}
};
class EventSource : public QObject {
Q_OBJECT
public:
Q_SIGNAL void indication(ClonableEvent *);
}
#define NAMED(x) x; x.setObjectName(#x)
int main(int argc, char ** argv) {
QCoreApplication app(argc, argv);
ClonableEvent ev1(QEvent::User + 1);
ClonableEvent ev2(QEvent::User + 2);
EventDisplay NAMED(dp1);
EventDisplay NAMED(dp12);
EventDisplay NAMED(dp2);
Dispatcher d;
d.addMapping(ev1, dp1); // dp1 handles only ev1
d.addMapping(ev1, dp12); // dp12 handles both ev1 and ev2
d.addMapping(ev2, dp12);
d.addMapping(ev2, dp2); // dp2 handles only ev2
EventSource s;
QObject::connect(&s, &EventSource::indication, &d, &Dispatcher::dispatch);
emit s.indication(&ev1);
emit s.indication(&ev2);
return 0;
}
#include "main.moc"
A: If connection was in one thread, I think that you can throw an exception. But in this case you should be catch any exception during emit a signal:
try {
emit someSignal();
} catch(...) {
qDebug() << "catched";
}
But I think that it's bad idea. I'll would be use event dispatching for this. | unknown | |
d1646 | train | As mentionned in the comment of my question:
Since it is a relative URL, it will use the protocol of the page it is executed in. But instead of asking, you could also have found this out easily yourself by just looking at the request in the net panel of your browser’s developer tools … – CBroe 4 mins ago | unknown | |
d1647 | train | This is in conjunction with Seth McClaine's answer.
Echo your values using:
<?php echo $Name; ?> <?php echo $Bech; ?>
Instead of <?=$Name?> <?=$Bech?>
The use of short tags is not recommended for something like this.
Reformatted code:
<?php
$abfrage = "SELECT * FROM tester";
$ergebnis = mysql_query($abfrage);
$row = mysql_fetch_object($ergebnis);
$Name=$row->Name;
$Bech=$row->Beschreibung;
?>
<a href="" title="<?php echo $Name; ?> <?php echo $Bech; ?>">Test Link</a>
A: If you just want the first result remove the while...
<?php
$abfrage = "SELECT * FROM tester";
$ergebnis = mysql_query($abfrage);
$row = mysql_fetch_object($ergebnis);
$Name=$row->Name;
$Bech=$row->Beschreibung;
?>
<a href="" title="<?=$Name?> <?=$Bech?>">Test Link</a> | unknown | |
d1648 | train | Add this intent filter in your manifest to your activity
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/xml" />
<data android:pathPattern=".*\\.x" />
</intent-filter>
on your onCreate files are passed on as:
Uri uri = this.getIntent().getData();
if(uri!=null){
Log.v(getClass().getSimpleName(), "importing uri:"+uri.toString());
} | unknown | |
d1649 | train | I tried the code you posted, except that I added: require('Zend/Soap/AutoDiscover.php');. It worked.
A: Try adding docblocking to the hello function. the WSDL generator relies on it to generate proper WSDL file. http://framework.zend.com/manual/en/zend.soap.autodiscovery.html See the important notes in that link.
A: Yep, you are missing require('Zend/Soap/AutoDiscover.php'); that's all. | unknown | |
d1650 | train | If they are created dynamically you will need event delegation
$(document).on('click', ':button' , function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
alert(buttonElementId);
});
See In jQuery, how to attach events to dynamic html elements? for more info
A: For dynamically created elements you should use:
$(document).on("click", ":button", function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
alert(buttonElementId);
}); | unknown | |
d1651 | train | I was able to have correct character spacing by adding a space between each character and makeing that space to have a size of 8pt (because my text has a size of 16).
It looks good in my report. | unknown | |
d1652 | train | Sessions, SessionIDs and Session state are managed by the .NET server (by default), not by the client. Turning off JavaScript at the client won't affect the server.
Quote from MS Docs:
The in-memory [default session state] provider stores session data in the memory of the server where the app resides.
A: Session is stored on server side and session id is stored on client side, and javascript don't impact the session. So session will work if you turn off the javascript | unknown | |
d1653 | train | A workaround to this is including and referencing the required lib in your project. For example:
*
*locate the JAR-file org-netbeans-modules-java-j2seproject-copylibstask.jar, which will typically reside in a location like C:\Program Files\NetBeans 8.2\java\ant\extra on a computer with NetBeans.
*Copy that JAR into your project, f.x. project/ant/org-netbeans-modules-java-j2seproject-copylibstask.jar.
*Open nbproject/project.properties and at the end of it add the line:
libs.CopyLibs.classpath=ant/org-netbeans-modules-java-j2seproject-copylibstask.jar
With the lib in your project and project.properties pointing to its location Ant should be able to build without an actual NetBeans installation. | unknown | |
d1654 | train | You can use Braintree using API calls with their GraphQL client. Read the whole guide on how to make API calls on their website.
Making API Calls | unknown | |
d1655 | train | You can use a build shell script that creates/updates a Dart file in lib/... with constants holding the date before running flutter build ....
You then import that file in your code and use it.
A: I'll suggest that you also consider basically rolling your own version of the package_info library which includes all the information you want to get from the platform code. I use the Gradle build files to update some variables on each build, which I then retrieve from Flutter.
Examining the package_info code shows that it is really a fairly simple MethodChannel use case. You could add anything that you can get from the native side.
A: Expanding on Günter Zöchbauer answer...
*
*Create a text file in your source folder and enter the following
#!/bin/sh
var = "final DateTime buildDate =
DateTime.fromMillisecondsSinceEpoch(($(date "+%s000")));"
echo "$var" > lib/build_date.dart
*Save the text file as
build_date_script.sh
*In Android Studio, open Edit Configurations -> Add New Configuration and add a new 'Shell Script'
*Give it a name, such as 'Write build date'
*Select 'Script file' and enter the location of the 'build_date_script.sh' we created it stage 2.
*Download and install GitBash https://gitforwindows.org/
*Back to Android Studio, change the interpreter path to 'C:\Program Files\Git\git-bash.exe'.
*Uncheck 'Execute in terminal' and click 'Apply'
*Then in your main flutter run configuration, add a 'Before launch' item, select 'Run another configuration' and choose the script config we named in stage 4.
*Click OK.
Now every time you build it will create a new dart file in your lib folder called 'build_date.dart' with a variable called 'buildDate' for use as a build date within your application. | unknown | |
d1656 | train | It uses version 3.14.9 of okhttp. You can see that in the build.gradle file. Additionally, you could use the command gradlew app:dependencies. You should see something as follows in the output of that command:
+--- com.squareup.retrofit2:retrofit:2.9.0
| \--- com.squareup.okhttp3:okhttp:3.14.9
| \--- com.squareup.okio:okio:1.17.2
If you want to force it to use version 3.12.0 of okhttp, adding the following seems to work:
implementation ('com.squareup.okhttp3:okhttp:3.12.0') {
force = true
} | unknown | |
d1657 | train | You can use loops to create an array of rows and an array of columns beforehand and assign these to the RowDefinitions and ColumnDefinitions properties.
I should have thought you'd need to call RowDefinitions.Add() and ColumnDefinitions.Add() in a loop to do so, though.
A: No, this is not possible because the only way this would work is if you could assign a completely new value to the RowDefinitions property, which you can't:
public RowDefinitionCollection RowDefinitions { get; }
^^^^
The syntax as shown in your question is just a handy way of calling .Add on the object in that property, so there is no way for you to inline in that syntax do this. Your code is just "short" for this:
var temp = new Grid();
temp.RowSpacing = 12;
temp.ColumnSpacing = 12;
temp.VerticalOptions = LayoutOptions.FillAndExpand;
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
Specifically, your code is not doing this:
temp.RowDefinitions = ...
^
You would probably want code like this:
var grid = new Grid()
{
RowSpacing = 12,
ColumnSpacing = 12,
VerticalOptions = LayoutOptions.FillAndExpand,
RowDefinitions = Enumerable.Range(0, 100).Select(_ =>
new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }),
ColumnDefinitions = Enumerable.Range(.....
But you cannot do this as this would require that RowDefinitions and ColumnDefinitions was writable.
The closest thing is like this:
var temp = new Grid
{
RowSpacing = 12,
ColumnSpacing = 12,
VerticalOptions = LayoutOptions.FillAndExpand,
};
for (int index = 0; index < rowCount; index++)
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
var grid = temp;
A: RowDefinitions is RowDefinitionCollection. RowDefinitionCollection is internal which you cannot create outside Grid. | unknown | |
d1658 | train | I am not sure what you mean when you say "files in drawn." Did you mean to say "files is drawn" as in "how does TFS know how to compare files?
Resolve conflict tool is used when TFS cannot resolve the conflict on its own.
This MS Article will walk you through how to get more detailed information and explain how the tool works.
There are a few "buckets" for conflicts (see below).
As for wanting video tutorials, there are a few that simply show you how to use the tool and some cursory conflicts but there are no videos that I have found that go over each conflict case type.
Conflicts are always difficult when they can't be automatically managed. I would consider swapping out your merge tool to a better one.
I hope that helps you.
Version Conflict
Version conflicts can occur in Team
Foundation version control with a
check-in, get, or merge operation. In
each case, the evolution of an item
along divergent paths results in a
conflict.
Check-in Two users check out the latest version of a file. The
first user checks in changes; this
creates a new version of the file.
When the second user tries a check-in,
there is a version conflict because
the second user's changes were not
made against the latest version of the
file.
*
Get Two users check out the latest version of a file. The first
user checks in changes; this creates a
new version of the file. When the
second user performs a get latest
operation, there is a version conflict
because the get latest operation is
trying to update the checked-out file
in the workspace.
*
Merge A branched file has been modified in both branches. A user
tries to merge changes from one branch
to the other. There is a version
conflict because the file has been
modified on both branches.
File Name Collision Conflict
File name collisions can occur in Team
Foundation version control with a
check-in, get, or merge operation. In
all three cases, the conflict results
when two or more items try to occupy
the same path in the source control
server.
Check-in Two users each add a file to the same application.
Coincidentally, the two users choose
the same name for the new files. One
user checks in his or her file. When
the second user tries a check-in,
there is a file name collision.
*
Get Two users add files with identical names to an application. One
user checks in the file. When the
second user tries a get latest
operation, there is a file name
collision. This is because the first
user's file cannot be retrieved where
the second user has added a file.
*
Merge An application has been branched and has then been worked on
in both branches. In both branches, a
file that has the same name has been
added. A user tries to merge changes
from one branch to the other. There is
a file name collision because the file
added to the source branch can not be
branched where a file has already been
added to the target branch.
Local overwrite conflict
Local overwrite conflicts only occur
in Team Foundation version control
during a get operation. These
conflicts occur when a get operation
tries to write over a writable file in
your workspace. By default, the get
operation will only replace files that
are read-only. Resolving local
overwrite conflicts involves either
overwriting the file or checking out
the file and merging changes. | unknown | |
d1659 | train | You might be knowing data types in JS.
If you pass circle or star as argument without quotes then the argument will be interpreted as object (which is not your intension).
As per you function definition it is expecting string, means you should pass string literal e.g. symbols('star') or you should have a variable containing string value e.g. var circle = 'circle';
symbols(circle); | unknown | |
d1660 | train | First of all, I assume that you use linq2sql or something similar.
In order to update an object in your database, that object has to be fetched through a DataContext.
Inside your method "ManageNewsArticles" you're calling db.SaveChanges(); but since there is no objects loaded through db no rows will get updated.
A solution to this is to fetch all news you want to update, and then use the Controller.UpdateModel method to update your actual instances, and then call db.SaveChanges(); to persist your changes.
A: Try using the
UpdateModel(NewsViewModel);
db.SaveChanges();
return RedirectToAction("Admin");
A: I've never tried using EditorFor on lists of complex objects. I'm guessing that MVC is unable to encode your NewsArticle objects in such a way that they can be reassembled into a NewsViewModel object. Have you tried using something like Firebug to see what the actual POST looks like? What are the query parameter keys and values?
You may be able to simply take an IEnumerable<NewsArticle>, and then re-parse that out using the same logic you use in the ManageNewsArticles method. Give that a shot, and let us know what you find out. | unknown | |
d1661 | train | Have you tried updating the notification instead? And use setOnlyAlertOnce()
"You can optionally call setOnlyAlertOnce() so your notification interupts the user (with sound, vibration, or visual clues) only the first time the notification appears and not for later updates."
Check this link
https://developer.android.com/training/notify-user/build-notification.html#Updating
A:
setPriority(NotificationCompat.PRIORITY_DEFAULT)?
lower it, so wont be shown on lockscreen (android 7 and up)
and here we go with a small fix for this part:
setPriority(NotificationCompat.PRIORITY_LOW)
you can also add:
setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
but it'll also remove notification from lockscreen...
docs:
*
*https://developer.android.com/training/notify-user/build-notification.html#lockscreenNotification
*https://developer.android.com/training/notify-user/channels#importance
hope this helps =] | unknown | |
d1662 | train | I see you are using thymeleaf so try to access your resources like this :
<script th:src="@{/js/socket.io/socket.io.js}"></script>
<script th:src="@{/js/moment.min.js}"></script>
<script th:src="@{/js/demoApp.js}"></script>
Also and if this does not work can you add your index.html.
A: I have found the problem , everything was correct but :
1) I was not extending my Application class from WebMvcAutoConfiguration.
@SpringBootApplication
@EnableWebMvc
public class HLACUIApplication extends WebMvcAutoConfiguration {
public static void main(String[] args) {
SpringApplication.run(HLACUIApplication.class, args);
}
}
This is how the application class should be.
2) I don't need to use templates folder because I am using angularjs and not thymeleaf. I have put everything in static folder.
A: I was facing the same issue. I think you are having html code like below:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<!-- Main Styles -->
<link rel="stylesheet" href="/css/bar.css" />
<script src="/js/foo.js"></script>
</head>
<body>
<div>Welcome to Foo!</div>
</body>
</html>
I solved the problem by adding type="text/javascript" to the <script> element. In Spring Boot applications it's required to define type="text/javascript", otherwise it's not going to load.
The solution for your example would look like this:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<!-- Main Styles -->
<link rel="stylesheet" href="/css/bar.css" />
<script type="text/javascript" src="/js/foo.js"></script>
</head>
<body>
<div>Welcome to Foo!</div>
</body>
</html>
A: In my case with thymeleaf, helped when I skipped '/' before 'js'.
Example, instead of
<script src="/js/demoApp.js"></script>
I've put
<script src="js/demoApp.js"></script>
A: If you are using Eclipse IDE right click on Project Properties/Project Facets | unknown | |
d1663 | train | There are some easy to follow examples in this GitHub mirror of django-autocomplete.
A: some time ago I put together a small tutorial on this, you might find that useful... it's here | unknown | |
d1664 | train | You can do this in your code:
Random RandomView = new Random();
int nextViewIndex = RandomView.nextInt(3);
while (nextViewIndex == MyViewFlipper.getDisplayedChild()) {
nextViewIndex = RandomView.nextInt(3);
}
MyViewFlipper.setDisplayedChild(nextViewIndex);
Basically just call Random.nextInt() until it doesn't match current viewFlipper's index.
To only show a viewFlipper once randomly:
// Intialize this once
List<Integer> vfIndices = new ArrayList<Integer>();
for (int i = 0; i < MyViewFlipper.getChildCount(); i++) {
vfIndices.add(i);
}
// when button is clicked
if (vfIndices.size() == 0) {
return; // no more view flipper to show!
}
int viewIndex = RandomView.nextInt(vfIndices.size());
MyViewFlipper.setDisplayedChild(vfIndices.get(viewIndex));
vfIndicies.remove(viewIndex);
The idea is use an ArrayList to keep track of the viewFlipper index that has not been shown. When button is clicked, pick an index randomly from this array and set the viewFlipper to. Then remove that index from the ArrayList. Next time the button is clicked, it will show one of the remaining flippers. | unknown | |
d1665 | train | You can use SciPy
from scipy.signal import find_peaks
peaks, _ = find_peaks(x, height=0) # x is the signal
print("x-values: ", peaks," y-values: ", x[peaks])
SciPy documentation for finding peaks
.. Or a quick solution if you signal is not too noisy then you can manually smooth the signal, differentiate the smoothed signal, find a threshold value and count the zeroes :) | unknown | |
d1666 | train | Issue Resolved: Apparently, for SiteMinder to protect ASP.NET MVC Apps, it must be upgraded to version R12.5 / WebAgent 7 or higher. Just update SiteMinder on your IIS server and it should start working. | unknown | |
d1667 | train | The following command was failing with failed to compute cache key: not found:
docker build -t tag-name:v1.5.1 - <Dockerfile
Upon changing the command to the following it got fixed:
docker build -t tag-name:v1.5.1 -f Dockerfile .
A: In my case I found that docker build is case sensitive in directory name, so I was writing /bin/release/net5.0/publish in the COPY instruction and failed with the same error, I've just changed to /bin/Release/net5.0/publish and it worked
A: Error : failed to compute cache key: "src" not found: not found
in my case , folder/file excluded in .dockerignore
*
*after resolving file from dockerignore able to create image.
A: In my case, I had something like this:
FROM mcr.microsoft.com/dotnet/aspnet:5.0
COPY bin/Release/net5.0/publish/ app/
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApi.dll"]
And I finally realized that I had the bin folder in my .dockerignore file.
A: Check your .dockerignore file. Possible it ignores needed files for copy command and you get failed to compute cache key error.
.dockerignore may be configured to minimize the files sent to docker for performance and security:
*
!dist/
The first line * disallows all files. The second line !dist/ allows the dist folder
This can cause unexpected behavior:
FROM nginx:latest
# Fails because of * in .dockerignore
# failed to compute cache key: "/nginx.conf.spa" not found: not found
# Fix by adding `!nginx.conf.spa` to .dockerignore
COPY nginx.conf.spa /etc/nginx/nginx.conf
RUN mkdir /app
# Works because of !dist/ in .dockerignore
COPY dist/spa /app
Belts and suspenders.
A: I had the same issue, I set the Docker environment to Windows in when adding Docker support. Even running in Visual Studio threw error to that. I changed the environment to Linux as my Docker is running in the Windows Subsystem for Linux (WSL).
Then I moved back to the terminal to run the commands.
I was able to resolve this by moving to the Solutions folder (Root folder).
And I did docker build like this:
docker build -t containername/tag -f ProjectFolder/Dockerfile .
Then I did docker run:
docker run containername/tag
A: The way Visual Studio does it is a little bit odd.
Instead of launching docker build in the folder with the Dockerfile, it launches in the parent folder and specifies the Dockerfile with the -f option.
I was using the demo project (trying to create a minimal solution for another question) and struck the same situation.
Setup for my demo project is
\WorkerService2 ("solution" folder)
+- WorkerService2.sln
+- WorkserService2 ("project" folder)
+- DockerFile
+- WorkerService2.csproj
+- ... other program files
So I would expect to go
cd \Workerservice2\WorkerService2
docker build .
But I get your error message.
=> ERROR [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/] 0.0s
------
> [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/]:
------
failed to compute cache key: "/WorkerService2/WorkerService2.csproj" not found: not found
Instead, go to the parent directory, with the .sln file and use the docker -f option to specify the Dockerfile to use in the subfolder:
cd \Workerservice2
docker build -f WorkerService2\Dockerfile --force-rm -t worker2/try7 .
docker run -it worker2/try7
Edit (Thanks Mike Loux, tblev & Goku):
Note the final dot on the docker build command.
For docker the final part of the command is the location of the files that Docker will work with. Usually this is the folder with the Dockerfile in, but that's what's different about how VS does it. In this case the dockerfile is specified with the -f. Any paths (such as with the COPY instruction in the dockerfile) are relative to the location specified. The . means "current directory", which in my example is \WorkerService2.
I got to this stage by inspecting the output of the build process, with verbosity set to Detailed.
If you choose Tools / Options / Projects and Solutions / Build and Run you can adjust the build output verbosity, I made mine Detailed.
Edit #2 I think I've worked out why Visual Studio does it this way.
It allows the project references in the same solution to be copied in.
If it was set up to do docker build from the project folder, docker would not be able to COPY any of the other projects in the solution in. But the way this is set up, with current directory being the solution folder, you can copy referenced projects (subfolders) into your docker build process.
A: Asking for a directory that does not exist throws this error.
In my case, I tried
> [stage-1 7/14] COPY /.ssh/id_rsa.pub /.ssh/:
------
failed to compute cache key: "/.ssh/id_rsa.pub" not found: not found
I had forgotten to add the /.ssh folder to the project directory. In your case you should check whether /client is really a subfolder of your Dockerfile build context.
A: I had the same issue. In my case there was a wrong directory specified.
My Dockerfile was:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll
Then I realised that in the second build stage I am trying to copy project files from directory publish/web:
COPY --from=publish publish/web .
But as I specified workdir /app in the first stage, my files are located in that directory in image filesystem, so changing path from publish/web to app/publish/web resolved my issue.
So my final working Dockerfile is:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish app/publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll
A: In my case there was a sneaky trailing whitespace in the file name.
------
> [3/3] COPY init.sh ./:
------
failed to compute cache key: "/init.sh" not found: not found
So the file was actually called "init.sh " instead of "init.sh".
A: I had a similar issues: Apparently, docker roots the file system during build to the specified build directory for security reasons. As a result, COPY and ADD cannot refer to arbitrary locations on the host file system. Additionally, there are other issues with syntax peculiarities. What eventually worked was the following:
COPY ./script_file.sh /
RUN /script_file.sh
A: I had faced the same issue.
The reason was the name of the DLL file in the Docker file is case sensitive.
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY MyFirstMicroService.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "**MyFirstMicroService.dll**"]
This .dll name should match your .csproj file.
A: This also happens when you don't provide the proper path to your COPY command input. The most important clue I had is that WORKDIR command opens a folder for the container, not in the windows explorer (so it doesn't affect the path you need to specify for the COPY command).
A: In my Case,
i was doing mistake in '/' and ''. Let me explain
Open your dockerfile (it should be named as dockerfile only, not DockerFile or Dockerfile).
You may have something like this-
FROM mcr.microsoft.com/dotnet/runtime:5.0
COPY bin\Release\net5.0\publish .
ENTRYPOINT ["dotnet", "HelloDocker.dll"]
Replace COPY bin\Release\net5.0\publish . to COPY bin/Release/net5.0/publish .
A: in my case, it was a wrong Build with PATH configuration e.g. Docker build context
*
*Simple docker script
docker build .
where . is path to build context
*Gradle+Docker
docker {
dependsOn build
dependsOn dockerFilesCopy
name "${project.name}:${project.version}"
files "build" // path to build context
}
*Gradle+GitHub action
name: Docker build and push
on:
push:
branches: [ main ]
# ...
jobs:
build:
runs-on: ubuntu-latest
# ...
steps:
- name: Checkout
uses: actions/checkout@v2
# ...
- name: Build and export to Docker
uses: docker/build-push-action@v2
with:
# ...
file: src/main/docker/Dockerfile
context: ./build # path to build context
A: In my case, with Angular project, my project was in the folder called ex: My-Folder-Project and I was putting on Dockerfile COPY --from=publish app/dist/My-Folder-Project .
But of course the correct thing is put the "name" in your package.json like COPY --from=publish app/dist/name-in-package.json .
A: In my case I changed context, and path of Dockerfile within docker-compose.yml config:
services:
server:
# inheritance structru
extends:
file: ../../docker-compose.server.yml
# I recommend you to play with this paths
build:
context: ../../
dockerfile: ./apps/${APP_NAME}/Dockerfile
... | unknown | |
d1668 | train | You were missing a pair of parentheses. The corrected code looks like:
library(rmutil)
X=c(8,1,2,3)
Y=c(5,2,4,6)
correlation=cor(X,Y)
bvtnorm <- function(x, y, mu_x = mean(X), mu_y = mean(Y), sigma_x = sd(X), sigma_y = sd(Y), rho = correlation) {
function(x, y)
1 / (2 * pi * sigma_x * sigma_y * sqrt(1 - rho ^ 2)) *
exp(- 1 / (2 * (1 - rho ^ 2)) * (((x - mu_x) / sigma_x) ^ 2 +
((y - mu_y) / sigma_y) ^ 2 - 2 * rho * (x - mu_x) * (y - mu_y) /
(sigma_x * sigma_y)))
}
f2 <- bvtnorm(x, y)
print("sum_double_integral :")
integral_1=int2(f2, a=c(-Inf,-Inf), b=c(Inf,Inf)) # should normaly give 1
print(integral_1) # prints 1.000047
This was hard to spot. From a debugging point of view, I found it helpful to first integrate over a finite domain. Trying it with things like first [-1,1] and then [-2,2] (on both axes) showed that the integrals were blowing up rather than converging. After that, I looked at the grouping even more carefully.
I also cleaned up the code a bit. I dropped SD in favor of sd since I don't see the motivation in importing the package psych just to make the code less readable (less flippantly, dropping psych from the question makes it easier for others to reproduce. There is no good reason to include a package which isn't be used in any essential way). I also dropped the force() which was doing nothing and used the built-in function cor for calculating the correlation. | unknown | |
d1669 | train | 1) The Kalman filter should not require massive, non linear scaling amounts of memory : it is only calculating the estimates based on 2 values - the initial value, and the previous value. Thus, you should expect that the amount of memory you will need should be proportional to the total amount of data points. See : http://rsbweb.nih.gov/ij/plugins/kalman.html
2) Switching over to floats will 1/2 the memory required for your calculation . That will probably be insignificant in your case - I assume that if the data set is crashing due to memory, you are running your JVM with a very small amount of memory or you have a massive data set.
3) If you really have a large data set ( > 1G ) and halving it is important, the library you mentioned can be refactored to only use floats.
4) For a comparison of java matrix libraries, you can checkout http://code.google.com/p/java-matrix-benchmark/wiki/MemoryResults_2012_02 --- the lowest memory footprint libs are ojAlgo, EJML, and Colt.
Ive had excellent luck with Colt for large scale calculations - but I'm not sure which ones implement the Kalaman method. | unknown | |
d1670 | train | It is a known issue that has been there for a number of years now.
We dedicated a lot of time to investigating the issue in work but found even with a MVCE the issue occurs.
We also found a Radar link from iOS 8: https://openradar.appspot.com/18957593
We replicated the issue in iOS 9, 10, 11 and 12.
A: I came across this issue and the only solution I found is to make your own crop functionality. Nothing else works. | unknown | |
d1671 | train | sqlite3_bind_text() wants a pointer to the entire string, not only the first character. (You need to understand how C pointers and strings (character arrays) work.)
And the sqlite3_bind_text() documentation tells you to use five parameters:
sqlite3_bind_text(res, 1, updatedName.c_str(), -1, SQLITE_TRANSIENT); | unknown | |
d1672 | train | In C++17 and over, for this purpose we can apply std::variant as follows:
#include <variant>
class state_type {};
template<class T>
class euler {};
template<class T>
class runge_kutta4 {};
template<class T>
using stepper_t = std::variant<euler<T>, runge_kutta4<T>>;
Then you can do like this:
DEMO
stepper_t<state_type> stepper;
if (integration_scheme == "euler") {
stepper = euler<state_type>{};
}
else{
stepper = runge_kutta4<state_type>{};
}
std::cout << stepper.index(); // prints 0.
But although I don't know the whole code of your project, I think the subsequent code would not be simple one in the above way.
If I were you, I will define the base calss stepperBase and euler and runge_kutta4 as the inheritances of stepperBase. | unknown | |
d1673 | train | You may use ClippingMediaSource:
ClippingMediaSource(MediaSource mediaSource, long startPositionUs, long endPositionUs)
Creates a new clipping source that wraps the specified source and provides samples between the specified start and end position.
You can convert to have a new media source and set this new media source for your ExoPlayer:
// Create a new media source with your specified period
val newMediaSource = ClippingMediaSource(mediaSource, 0, 5_000_000) | unknown | |
d1674 | train | Unfortunately, what you want is not supported. There is a method in Activity called onCreateThumbnail() that can be overridden to provide a custom thumbnail, but according to a post from Dianne Hackborn in 2009, this method is never actually called:
https://groups.google.com/d/msg/android-developers/J5uBtHzhG8E/bX43j_GAm4gJ
I've tried it relatively recently myself to no effect, so I have to assume that's still the case. | unknown | |
d1675 | train | The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here:
https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/
Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs.
Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here:
https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/
and also here:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples
Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs. | unknown | |
d1676 | train | Here are two MSDN pages that give an answer to your question:
*
*http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
*http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx
Hopefully one of them will be sufficient. | unknown | |
d1677 | train | Well you could Publish the workbook to PDF, just make sure your fist page is the first sheet
Option Explicit
Sub PDF_And_Mail()
Dim FileName As String
'// Call the function with the correct arguments
FileName = Create_PDF(Source:=ActiveWorkbook, _
OverwriteIfFileExist:=True, _
OpenPDFAfterPublish:=False)
If FileName <> "" Then
Mail_PDF FileNamePDF:=FileName
End If
End Sub
'// Create PDF
Function Create_PDF(Source As Object, OverwriteIfFileExist As Boolean, _
OpenPDFAfterPublish As Boolean) As String
Dim FileFormatstr As String
Dim Fname As Variant
'// Test If the Microsoft Add-in is installed
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then
'// Open the GetSaveAsFilename dialog to enter a file name for the pdf
FileFormatstr = "PDF Files (*.pdf), *.pdf"
Fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
Title:="Create PDF")
'// If you cancel this dialog Exit the function
If Fname = False Then
Exit Function
End If
'If OverwriteIfFileExist = False we test if the PDF
'already exist in the folder and Exit the function if that is True
If OverwriteIfFileExist = False Then
If Dir(Fname) <> "" Then Exit Function
End If
'Now the file name is correct we Publish to PDF
Source.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=OpenPDFAfterPublish
'If Publish is Ok the function will return the file name
If Dir(Fname) <> "" Then
Create_PDF = Fname
End If
End If
End Function
'// Email Created PDF
Function Mail_PDF(FileNamePDF As String)
Dim GMsg As Object
Dim gConf As Object
Dim GmBody As String
Dim Flds As Variant
Set GMsg = CreateObject("CDO.Message")
Set gConf = CreateObject("CDO.Configuration")
gConf.Load -1 ' CDO Source Defaults
Set Flds = gConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "[email protected]"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
GmBody = "Hi there" & vbNewLine & vbNewLine
With GMsg
Set .Configuration = gConf
.To = "[email protected]"
.CC = ""
.BCC = ""
.From = "[email protected]"
.Subject = "Important message"
.TextBody = GmBody
.AddAttachment FileNamePDF
.Send
End With
End Function
Most codes from Ron de Bruin | unknown | |
d1678 | train | WARNING!
The following are potential reasons for a segmentation fault. It is virtually impossible to list all reasons. The purpose of this list is to help diagnose an existing segfault.
The relationship between segmentation faults and undefined behavior cannot be stressed enough! All of the below situations that can create a segmentation fault are technically undefined behavior. That means that they can do anything, not just segfault -- as someone once said on USENET, "it is legal for the compiler to make demons fly out of your nose.". Don't count on a segfault happening whenever you have undefined behavior. You should learn which undefined behaviors exist in C and/or C++, and avoid writing code that has them!
More information on Undefined Behavior:
*
*What is the simplest standard conform way to produce a Segfault in C?
*Undefined, unspecified and implementation-defined behavior
*How undefined is undefined behavior?
What Is a Segfault?
In short, a segmentation fault is caused when the code attempts to access memory that it doesn't have permission to access. Every program is given a piece of memory (RAM) to work with, and for security reasons, it is only allowed to access memory in that chunk.
For a more thorough technical explanation about what a segmentation fault is, see What is a segmentation fault?.
Here are the most common reasons for a segmentation fault error. Again, these should be used in diagnosing an existing segfault. To learn how to avoid them, learn your language's undefined behaviors.
This list is also no replacement for doing your own debugging work. (See that section at the bottom of the answer.) These are things you can look for, but your debugging tools are the only reliable way to zero in on the problem.
Accessing a NULL or uninitialized pointer
If you have a pointer that is NULL (ptr=0) or that is completely uninitialized (it isn't set to anything at all yet), attempting to access or modify using that pointer has undefined behavior.
int* ptr = 0;
*ptr += 5;
Since a failed allocation (such as with malloc or new) will return a null pointer, you should always check that your pointer is not NULL before working with it.
Note also that even reading values (without dereferencing) of uninitialized pointers (and variables in general) is undefined behavior.
Sometimes this access of an undefined pointer can be quite subtle, such as in trying to interpret such a pointer as a string in a C print statement.
char* ptr;
sprintf(id, "%s", ptr);
See also:
*
*How to detect if variable uninitialized/catch segfault in C
*Concatenation of string and int results in seg fault C
Accessing a dangling pointer
If you use malloc or new to allocate memory, and then later free or delete that memory through pointer, that pointer is now considered a dangling pointer. Dereferencing it (as well as simply reading its value - granted you didn't assign some new value to it such as NULL) is undefined behavior, and can result in segmentation fault.
Something* ptr = new Something(123, 456);
delete ptr;
std::cout << ptr->foo << std::endl;
See also:
*
*What is a dangling pointer?
*Why my dangling pointer doesn't cause a segmentation fault?
Stack overflow
[No, not the site you're on now, what is was named for.] Oversimplified, the "stack" is like that spike you stick your order paper on in some diners. This problem can occur when you put too many orders on that spike, so to speak. In the computer, any variable that is not dynamically allocated and any command that has yet to be processed by the CPU, goes on the stack.
One cause of this might be deep or infinite recursion, such as when a function calls itself with no way to stop. Because that stack has overflowed, the order papers start "falling off" and taking up other space not meant for them. Thus, we can get a segmentation fault. Another cause might be the attempt to initialize a very large array: it's only a single order, but one that is already large enough by itself.
int stupidFunction(int n)
{
return stupidFunction(n);
}
Another cause of a stack overflow would be having too many (non-dynamically allocated) variables at once.
int stupidArray[600851475143];
One case of a stack overflow in the wild came from a simple omission of a return statement in a conditional intended to prevent infinite recursion in a function. The moral of that story, always ensure your error checks work!
See also:
*
*Segmentation Fault While Creating Large Arrays in C
*Seg Fault when initializing array
Wild pointers
Creating a pointer to some random location in memory is like playing Russian roulette with your code - you could easily miss and create a pointer to a location you don't have access rights to.
int n = 123;
int* ptr = (&n + 0xDEADBEEF); //This is just stupid, people.
As a general rule, don't create pointers to literal memory locations. Even if they work one time, the next time they might not. You can't predict where your program's memory will be at any given execution.
See also:
*
*What is the meaning of "wild pointer" in C?
Attempting to read past the end of an array
An array is a contiguous region of memory, where each successive element is located at the next address in memory. However, most arrays don't have an innate sense of how large they are, or what the last element is. Thus, it is easy to blow past the end of the array and never know it, especially if you're using pointer arithmetic.
If you read past the end of the array, you may wind up going into memory that is uninitialized or belongs to something else. This is technically undefined behavior. A segfault is just one of those many potential undefined behaviors. [Frankly, if you get a segfault here, you're lucky. Others are harder to diagnose.]
// like most UB, this code is a total crapshoot.
int arr[3] {5, 151, 478};
int i = 0;
while(arr[i] != 16)
{
std::cout << arr[i] << std::endl;
i++;
}
Or the frequently seen one using for with <= instead of < (reads 1 byte too much):
char arr[10];
for (int i = 0; i<=10; i++)
{
std::cout << arr[i] << std::endl;
}
Or even an unlucky typo which compiles fine (seen here) and allocates only 1 element initialized with dim instead of dim elements.
int* my_array = new int(dim);
Additionally it should be noted that you are not even allowed to create (not to mention dereferencing) a pointer which points outside the array (you can create such pointer only if it points to an element within the array, or one past the end). Otherwise, you are triggering undefined behaviour.
See also:
*
*I have segfaults!
Forgetting a NUL terminator on a C string.
C strings are, themselves, arrays with some additional behaviors. They must be null terminated, meaning they have an \0 at the end, to be reliably used as strings. This is done automatically in some cases, and not in others.
If this is forgotten, some functions that handle C strings never know when to stop, and you can get the same problems as with reading past the end of an array.
char str[3] = {'f', 'o', 'o'};
int i = 0;
while(str[i] != '\0')
{
std::cout << str[i] << std::endl;
i++;
}
With C-strings, it really is hit-and-miss whether \0 will make any difference. You should assume it will to avoid undefined behavior: so better write char str[4] = {'f', 'o', 'o', '\0'};
Attempting to modify a string literal
If you assign a string literal to a char*, it cannot be modified. For example...
char* foo = "Hello, world!"
foo[7] = 'W';
...triggers undefined behavior, and a segmentation fault is one possible outcome.
See also:
*
*Why is this string reversal C code causing a segmentation fault?
Mismatching Allocation and Deallocation methods
You must use malloc and free together, new and delete together, and new[] and delete[] together. If you mix 'em up, you can get segfaults and other weird behavior.
See also:
*
*Behaviour of malloc with delete in C++
*Segmentation fault (core dumped) when I delete pointer
Errors in the toolchain.
A bug in the machine code backend of a compiler is quite capable of turning valid code into an executable that segfaults. A bug in the linker can definitely do this too.
Particularly scary in that this is not UB invoked by your own code.
That said, you should always assume the problem is you until proven otherwise.
Other Causes
The possible causes of Segmentation Faults are about as numerous as the number of undefined behaviors, and there are far too many for even the standard documentation to list.
A few less common causes to check:
*
*UD2 generated on some platforms due to other UB
*c++ STL map::operator[] done on an entry being deleted
DEBUGGING
Firstly, read through the code carefully. Most errors are caused simply by typos or mistakes. Make sure to check all the potential causes of the segmentation fault. If this fails, you may need to use dedicated debugging tools to find out the underlying issues.
Debugging tools are instrumental in diagnosing the causes of a segfault. Compile your program with the debugging flag (-g), and then run it with your debugger to find where the segfault is likely occurring.
Recent compilers support building with -fsanitize=address, which typically results in program that run about 2x slower but can detect address errors more accurately. However, other errors (such as reading from uninitialized memory or leaking non-memory resources such as file descriptors) are not supported by this method, and it is impossible to use many debugging tools and ASan at the same time.
Some Memory Debuggers
*
*GDB | Mac, Linux
*valgrind (memcheck)| Linux
*Dr. Memory | Windows
Additionally it is recommended to use static analysis tools to detect undefined behaviour - but again, they are a tool merely to help you find undefined behaviour, and they don't guarantee to find all occurrences of undefined behaviour.
If you are really unlucky however, using a debugger (or, more rarely, just recompiling with debug information) may influence the program's code and memory sufficiently that the segfault no longer occurs, a phenomenon known as a heisenbug.
In such cases, what you may want to do is to obtain a core dump, and get a backtrace using your debugger.
*
*How to generate a core dump in Linux on a segmentation fault?
*How do I analyse a program's core dump file with GDB when it has command-line parameters? | unknown | |
d1679 | train | No. Microsoft.Office.Interop.Word (and all other interop) will just work when Office is installed on that machine. It is a requirement to actually create the instance of Word.
Interop does start the Word executable and can't stand on its own.
It is also discouraged to use Interop on a server.
A: I concur with Patrick's answer.
If you need to manipulate a docx file on a machine without the Word application installed you can work directly with the file via the Office Open XML file format. This can be done with any tools that can work with Zip packages (a docx file is a zip package of the files that make up the document) and XML.
Microsoft provides the Open XML SDK for VB.NET and C# which makes things simpler. There's also an SDK for JavaScript.
You'll find more information at OpenXMLDeveloper.org. | unknown | |
d1680 | train | Typescript expects the string to be literally one of the options of the position property - absolute, relative etc
One way to solve it is to tell him that you know the type will be ok, like so :
<span style={{
position: this.props.position,
left: this.props.left,
top: this.props.top,
height: this.props.height,
width: this.props.width
}: as React.CSSProperties} /> </span>)}
Another option is to go where the position property is originally defined (parent element) and let Typescript enforce type, for example:
const styles: ('absolute' | 'relative' | 'fixed') = 'absolute';
A: There is no need to cast the object but declare the type React.CSSProperties when initializing.
function MyComponent(props) {
const styles: React.CSSProperties = {
position: this.props.position,
left: this.props.left,
top: this.props.top,
height: this.props.height,
width: this.props.width
};
return (
<span style={styles}></span>
);
} | unknown | |
d1681 | train | You can 'revert' B. This effectively creates a new commit which 'undoes' the changes made by B. This works with one bad commit or a whole series of bad commits. | unknown | |
d1682 | train | Use key:value pairs and remove that semicolon.
{
"cars": [
{
"model": "test"
},
{
"model": "test2"
}
]
}
Then once you parse your JSON and assign it to a variable, e.g. jsonVar, you can loop over the array jsonVar.cars to get each dictionary, which has model property.
More examples of correctly formatted JSON.
Finally, this JSON validator can provide helpful hints on incorrectly formatted JSON. | unknown | |
d1683 | train | Row(
children: <Widget>[
Expanded(
flex: 1,
//SizedBox(height: 20.0),
child: CountryPicker(
dense: true,
showFlag: false, //displays flag, true by default
showDialingCode:
true, //displays dialing code, false by default
showName: true, //displays country name, true by default
showCurrency: false, //eg. 'British pound'
showCurrencyISO: false,
onChanged: (Country country) {
setState(() => _selected = country);
print(country.dialingCode);
countryCode = country.dialingCode;
},
selectedCountry: _selected,
),
),
Expanded(
flex: 3,
//SizedBox(height: 20.0),
child: TextFormField(
decoration: InputDecoration(
labelText: 'Mobile no.',
border: OutlineInputBorder(),
),
validator: (val) => val.length != 10
? 'Enter a mobile number of 10 digits'
: null,
onChanged: (val) {
setState(() => phone = val);
phoneno = phone;
},
),
),
],
), | unknown | |
d1684 | train | Sounds like you actually want to recycle an Application pool rather than stop/start a website.
To do this you can use the IISAPP.vbs utility:
cscript c:\windows\system32\iisapp.vbs /a "My AppPool" /r
You can run the utility with a /? flag for full usage details and some sample commandlines.
If you really want to start/stop a website you can use the ADSUTIL.vbs utility:
cscript c:\inetpub\adminscripts\adsutil.vbs STOP_SERVER W3SVC/1
cscript c:\inetpub\adminscripts\adsutil.vbs START_SERVER W3SVC/1
For more information on ADSUTIL.vbs please see this page :
Using the Adsutil.vbs Administration Script (IIS 6.0) | unknown | |
d1685 | train | This issue is scope.
init() and vidPause() are private to the (function($) { call. They will not be directly accessible the way you are trying to access them.
Many jquery plugins use text (not my preference, but that's how they work), eg $.dialog("open"), so you could do something like that (not sure if opt is meant to mean action, so update accordingly) :
(function($) {
$.fn.controlls = function(action, opt) {
switch (action) {
case "pause":
vidPause(opt);
break;
...
usage
$('video').controlls("pause");
It might be possible to add the methods as if using namespaces, but I've not seen this in plugins so depends on what you are doing with your plugin (ie releasing it) whether you want to be consistent, eg:
(function($) {
$.fn.controlls = {};
$.fn.controlls.pause = function(opt) {
video.pause();
...
usage
$('video').controlls.pause() | unknown | |
d1686 | train | Thanks to Wiktor Stribizew for the answer in his comment.
There are a couple of "gotchas" for anyone who might land on this question with the same problem. The first is that you have to give the (presumably Unicode) hex value rather than the EBCDIC value that you would use, e.g. in ordinary interactive SQL on the IBM i. So in this case it really is \x27 and not \x7D for an apostrophe. Presumably this is because the REGEXP_ ... functions are working through Unicode even for EBCDIC data.
The second thing is that it would seem that the hex value cannot be the last one in the set. So this works:
^[A-Z0-9_\+\x27-]+ ... etc.
But this doesn't
^[A-Z0-9_\+-\x27]+ ... etc.
I don't know how to highlight text within a code sample, so I draw your attention to the fact that the hyphen is last in the first sample and second-to-last in the second sample.
If anyone knows why it has to not be last, I'd be interested to know. [edit: see Wiktor's answer for the reason]
btw, using double quotes as the string delimiter with an apostrophe in the set didn't work in this context.
A: A single quote can be defined with the \x27 notation:
^[A-Z0-9_+\x27-]+
^^^^
Note that when you use a hyphen in the character class/bracket expression, when used in between some chars it forms a range between those symbols. When you used ^[A-Z0-9_\+-\x27]+ you defined a range between + and ', which is an invalid range as the + comes after ' in the Unicode table. | unknown | |
d1687 | train | Take a look at ArryList. There are also many other collection classes in the util package that are also worth looking at. However, if you do not need a List and would like to be able to retrieve your Object by a known key a HashMap would be a better choice. For instance you should be able to use a JPanel or a TextField as the key.
A: Try using the collections, from java.util.collection package.
1. If every question you create has a unique identifier attached to it, then try to use Map, where let an Integer be your unique identifier and String may be the question
Map<Integer, String> map = HashMap<Integer, String>();
2. If you are storing the question is in sequence, List may also suffice.
List<String> list = ArrayList<String>();
A: Do you mean ArrayList?
You could also use a Map to have a key and then the JPanel as an instance?
It sounds like an ArrayList is better and then you generate a new JPanel biased on the Object/String in the ArrayList when it is clicked on. | unknown | |
d1688 | train | http://149.4.223.238:8080/manager/html
It looks like you might not have configured it yet. that link also tell you how to set it up. Also if you remote connect with that machine and access that site through localhost:8080/manager/html that should work too.
more details at
https://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
A: Your valve configuration is restricting access to IPs in the server itself, the public one and the loopback addresses
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="149\.4\.223\.238|127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
So, if you want to allow access from your public IP (be careful with that, it's a security hole) you should include it on the regexp.
As an option, you can access it through an ssh tunnel (can be done with putty too)
ssh -L 8080:localhost:8080 [email protected]
Now it should be accessible from localhost:8080. | unknown | |
d1689 | train | Looks like you're trying to get the counter before you submitted the job.
A: I had the same error at the time of an sqoop export.
The error was generated because the hdfs directory was empty.
Once I populated the directory (corresponding to a hive table), the sqoop ran without problems. | unknown | |
d1690 | train | it's a simple replacement, no need to use regex. use this instead:
new_name = filename.replace('_', ' ')
A: You could try something like this:
import glob, re, os
for filename in glob.glob('*.ext'):
new_name = ' '.join(filename.split('_')) # another method
os.rename(filename, new_name)
Cheers | unknown | |
d1691 | train | Have you checked if (T1.ID = T2.ID) there are IDs which equal each other? Otherwise your queryresponse is empty because your where case declines a result.
Sometimes there is a extra column at first place. So maybe your data is not inserted correctly?
A: Using Double or Float for id purposes is an issue here, I suppose, as precision is always in issue.
Simply, when you save a floating point number, like 7.2 it may be represented as 7.199999 or 7.199998 or 7.2000001 etc, thus ids won't be equal.
For id I suggest using integer or something like UUID. | unknown | |
d1692 | train | We have to wait for Google Play team to migrate away from the deprecated APIs. You can follow this issue on Google's Issue Tracker.
A: Create this result launcher
private val updateFlowResultLauncher =
registerForActivityResult(
ActivityResultContracts.StartIntentSenderForResult(),
) { result ->
if (result.resultCode == RESULT_OK) {
// Handle successful app update
}
}
After that try to launch your intent like this
val starter =
IntentSenderForResultStarter { intent, _, fillInIntent, flagsMask, flagsValues, _, _ ->
val request = IntentSenderRequest.Builder(intent)
.setFillInIntent(fillInIntent)
.setFlags(flagsValues, flagsMask)
.build()
updateFlowResultLauncher.launch(request)
}
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.FLEXIBLE,
starter,
requestCode,
)
Give it a try!
A: You can use below code snippet alternative of onActivityResult()
First Activity
Step 1
private val openActivity =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
handleActivityResult(REQUEST_CODE, it)
}
Step 2
openActivity.launch(
Intent(this, YourClass::class.java).apply {
putExtra(ANY_KEY, data) // If any data you want to pass
}
)
Step 3
private fun handleActivityResult(requestCode: Int, result: ActivityResult?) {
Timber.e("========***handleActivityResult==requestActivty==$requestCode====resultCode=========${result?.resultCode}")
if (requestCode == REQUEST_CODE) {
when (result?.resultCode) {
Activity.RESULT_OK -> {
val intent = result.data // received any data from another avtivity
}
Activity.RESULT_CANCELED->{
}
}
}
}
In second class
val intent = Intent()
intent.putExtra(ANY_KEY, data)
setResult(Activity.RESULT_OK, intent)
finish() | unknown | |
d1693 | train | You have to create the variable $a on a separate statement, before calling any of the commands that uses it.
Get-ChildItem -Filter *.mp4 | ForEach {
$a = $_.BaseName + '.mp4'
mp4box -add c:\intro.mp4 -cat $_ -new $a -force-cat &&
del $_ &&
auto-editor $a --edit_based_on motion --motion_threshold 0.000001% --no_open
}
I've also added some line breaks to make the code more readable. | unknown | |
d1694 | train | You can only use service name as a domain name when you are inside a container. In you case it's your browser making the call, it does not know what api is. In you web app, you should have an env like base url set to the ip of your docker machine or localhost. | unknown | |
d1695 | train | Your streaming array isn't initialized, so this can't be done due there's no 0,1,... element on it
window.streaming[window.progress]="streaming"; //streaming.length == 0, streaming[0] == 'undefined'
maybe you would like to clone the users.length on it to have a index
streaming = []; // length == 0
streaming.length = users.length; // length == users.length | unknown | |
d1696 | train | if you want to use static varaibles and also use inspector for assigning you can use singleton , here is where you can learn it | unknown | |
d1697 | train | Chose to use an iFrame plugin https://github.com/Nikku/jquery-bootstrap-scripting/pull/69 | unknown | |
d1698 | train | Here is a simple solution using async , but you need to put all your scripts inside scripts folder beside the main file
const fs = require('fs')
const exec = require('child_process').exec
const async = require('async') // npm install async
const scriptsFolder = './scripts/' // add your scripts to folder named scripts
const files = fs.readdirSync(scriptsFolder) // reading files from folders
const funcs = files.map(function(file) {
return exec.bind(null, `node ${scriptsFolder}${file}`) // execute node command
})
function getResults(err, data) {
if (err) {
return console.log(err)
}
const results = data.map(function(lines){
return lines.join('') // joining each script lines
})
console.log(results)
}
// to run your scipts in parallel use
async.parallel(funcs, getResults)
// to run your scipts in series use
async.series(funcs, getResults) | unknown | |
d1699 | train | You need to make sure that the width of the scroll view contentSize is greater than the width of the scroll view itself. Something as simple as the following should cause horizontal scrolling to happen:
override func viewDidLayoutSubviews() {
scrollView.isScrollEnabled = true
// Do any additional setup after loading the view
scrollView.contentSize = CGSize(width: view.frame.width * 2, height: 200)
} | unknown | |
d1700 | train | printf("Name, type: %s %c\n", h.objName, h.msgType[0]);
should print the whole string objName and the first character from msgType.
For the first to work you'd have to be sure that objName is really null terminated.
Also unsigned char is not the correct type to use for strings use plain char without unsigned. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.