_id stringlengths 2 6 | text stringlengths 4 46k | title stringclasses 1 value |
|---|---|---|
d10301 | The Express edition do not support extensions, use Community edition 2013 instead. Julie Lerman has an updated version, that has been fixed to work with VS 2015 http://thedatafarm.com/data-access/installing-ef-power-tools-into-vs2015/ | |
d10302 | First you need to give all groups wich u want to hide in JS, a main class name (groupclass) like this :
<div class="group1" id="d1">
<select class="cls1">
<option value="">Type</option>
<option value="QS">1</option>
<option value="SP">2</option>
<option value="XL">3</option>
</select>
</div>
<div class="div2">
<div class="group2 groupclass" , width="50%">
Division2: Hide when 3 is selected
</div>
<div class="group3 groupclass" , width="50%">
Hide when 1 or 2 is selected
</div>
</div>
Then you need to say in JS, hide all first and show just selected group like this :
<script>
$('#d1 > select').change(function() {
$('.groupclass').hide();
$('.group' + $('option:selected', this).text()).show();
});
</script>
A: Here you go
$d1 = $('#d1');
$d1.change(function() {
$("[id^=group]").show();
var value = $d1.val();
if (value === "QS" || value === "SP") {
$('#group3').hide();
} else if (value === "XL") {
$('#group2').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group1">
<select class="cls1" id="d1">
<option value="">Type</option>
<option value="QS">1</option>
<option value="SP">2</option>
<option value="XL">3</option>
</select>
</div>
<div class="div2">
<div id="group2" style="width:50%">
Division2: Hide when 3 is selected
</div>
<div id="group3" style="width:50%">
Hide when 1 or 2 is selected
</div>
</div>
A: You can try following,
$(function() {
$('#d1').change(function(){
var selected_valule = $("#d1").val();
console.log(selected_valule);
if(selected_valule == "XL" ){
$('#group3').hide();
$('#group2').show();
}else{
$('#group2').hide();
$('#group3').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group1" >
<select class="cls1" id="d1">
<option value="">Type</option>
<option value="QS">1</option>
<option value="SP">2</option>
<option value="XL">3</option>
</select>
</div>
<div class="div2">
<div id="group2" style="width:50%">
Division2: Hide when 3 is selected
</div>
<div id="group3" style="width:50%">
Hide when 1 or 2 is selected
</div>
</div> | |
d10303 | It looks like a MySQL configuration issue: for MySQL, a GRANT on localhost is different from a GRANT on localhost's FQDN. You might want to check which permissions are granted to users 'sonar'@'localhost' and 'sonar'@'fqdn-of-localhost' or 'sonar'@'%'. | |
d10304 | In Python code you have strs while in Julia code you have Chars - it is not the same.
Python:
>>> type('a')
<class 'str'>
Julia:
julia> typeof('a')
Char
Hence your comparisons do not work.
Your function could look like this:
reg_frac(state, ind_vars) = (py"reg_frac"(state::String, ind_vars::Array{Any}))
And now:
julia> reg_frac("b", Any[i for i in 2:3])
3-element Array{Any,1}:
"b"
[2, 3]
0.2853707270515166
However, I recommed using Vector{Float64} that in PyCall gets converted in-flight into a numpy vector rather than using Vector{Any} so looks like your code still could be improved (depending on what you are actually planning to do). | |
d10305 | I would use the following:
bool is_substr_of(const std::string& sub, const std::string& s) {
return sub.size() < s.size() && s.find(sub) != s.npos;
}
This uses the standard library only, and does the size check first which is cheaper than s.find(sub) != s.npos.
A: You can just use == or != to compare the strings:
if(contains(str1, str2) && (str1 != str2))
...
If string contains a string and both are not equal, you have a real subset.
If this is better than your method is for you to decide. It is less typing and very clear (IMO), but probably a little bit slower if both strings are long and equal or both start with the same, long sequence.
Note: If you really care about performance, you might want to try the Boyer-Moore search and the Boyer-Moore-Horspool search. They are way faster than any trivial string search (as apparently used in the string search in stdlibc++, see here), I do not know if boost::contains uses them.
A: About Comparaison operations
TL;DR : Be sure about the format of what you're comparing.
Be wary of how you define strictly.
For example, you did not pointed out thoses issue is your question, but if i submit let's say :
"ABC " //IE whitespaces
"ABC\n"
What is your take on it ? Do you accept it or not ? If you don't, you'll have to either trim or to clean your output before comparing - just a general note on comparaison operations -
Anyway, as Baum pointed out, you can either check equality of your strings using == or you can compare length (which is more efficient given that you first checked for substring) with either size() or length();
A: another approach, using only the standard library:
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "abc news";
string str2 = "abc";
if (str2 != str1
&& search(begin(str1), end(str1),
begin(str2), end(str2)) != end(str1))
{
cout <<"contains" << endl;
}
return 0;
} | |
d10306 | Have not tried Angular2. Though you should be able to set img src to Blob URL of first File object of input.files FileList.
At chromium, chrome you can get webkitRelativePath from File object, though the property is "non-standard" and possibly could be set to an empty string; that is, should not be relied on for the relative path to the selected file at user filesystem.
File.webkitRelativePath
This feature is non-standard and is not on a standards track. Do not
use it on production sites facing the Web: it will not work for every
user. There may also be large incompatibilities between
implementations and the behavior may change in the future.
File
The webkitRelativePath attribute of the File interface must return
the relative path of the file, or the empty string if not specified.
4.10.5.1.18. File Upload state (type=file)
EXAMPLE 16 For historical reasons, the value IDL attribute
prefixes the file name with the string "C:\fakepath\". Some legacy
user agents actually included the full path (which was a security
vulnerability). As a result of this, obtaining the file name from the
value IDL attribute in a backwards-compatible way is non-trivial.
See also How FileReader.readAsText in HTML5 File API works?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="" width="100px" alt="preview">
<input type="file" multiple onchange="onUpload(this)" id="input" accepts="image/*" />
<br><label for="input"></label>
<script>
let url;
function onUpload(element) {
console.log(element)
let file = element.files[0];
if (url) {
URL.revokeObjectURL(url);
}
url = URL.createObjectURL(file);
if ("webkitRelativePath" in file
&& file.webkitRelativePath !== "") {
element.labels[0].innerHTML = file.webkitRelativePath;
} else {
element.labels[0].innerHTML = element.value;
}
element.previousElementSibling.src = url;
element.value = null;
}
</script>
</body>
</html>
A: At last i got the answer my self,
https://github.com/ribizli/ng2-imageupload
this will work for you. It may help you for this issue. | |
d10307 | new info tells a lot... I think you should be more focused on the paste application accuracy then the carriage position precision. My bet is that the printer has far bigger dot size and error then 1 um and also the desired accuracy is dependent on the PCB usage (wiring and gaps widths). Anyway I would do this:
*
*linearize image geometry
you need to de-fisheye image. As you camera/optics setup will be fixed (especially focus and distance to PCB) you should for each PCB thickness make an image of a chess board grid. then create mapping that will linearize the chessboard to real rectangles so you discard deviations before the next process.
*normalize lighting conditions
*
*see Enhancing dynamic range and normalizing illumination
*sub pixel accuracy
each pixel of the image is integration of all the stuff in its area. So if we know the 2 colors (c0,c1) of any boundary (background/foreground) then we can estimate their sub-pixel position. Let start with axis aligned rectangles. I see it like this:
Each square of the grid represents a pixel area. c0 is the gray and c1 is the green color. In the camera image you got the final color as combination of all the colors inside each pixel:
*
*c = s0*c0 + s1*c1
where c is the final pixel color and s0,s1 are area coresponding to c0,c1 colors in range <0,1> where s0+s1=1.0. Now we want to compute the s0,s1 to obtain sub-pixel precision. So first detect the pixel position on the boundary as one of these:
*
*horizontal edge
*vertical edge
*corner
this can be done by inspecting the neighboring pixels. c0,c1 can be obtained from pixels with saturated color (all neighbors have the same color) These are in inside areas pixels. I would ignore the corner pixels as their position can be obtained from nearest H/V edge pixels (it is not possible to get both x,y coordinates from the equation above). So now for each H,V edge just solve system:
I. c = s0*c0 + s1*c1
II. s0 + s1 = 1.0;
compute the s0,s1 and the edge position for vertical edges is one of these:
x=x0 + pixel_size*s0 // if c0 is on the left
x=x0 + pixel_size*s1 // if c1 is on the left
horizontal edges are like this:
y=y0 + pixel_size*s0 // if c0 is on the top
y=y0 + pixel_size*s1 // if c1 is on the bottom
where x0,y0 is pixels top left position in pixels and the coordinate system is x+ is going to right and y+ is going down. If you got different setup just change the equations ...
Now if you got non axis aligned edges then you need to compute the slope (how many pixels it takes in one axis to change in the other dy/dx. and handle the areas accordingly:
So the only thing what changes is the conversion from computed s0,s1 to actual edge position. now you need to compute the left/right side or up/down. if you use the equation from the axis aligned example then you obtain the edge position in the middle of pixel. So you just shift it by the slope on both sides by x +/- 0.5*dx/dy or y +/- 0.5*dy/dx where dx,dy is the edge slope.
To obtain dx,dy just search along the edge for fully saturated pixels and if found then (dx,dy) is the distance between 2 closest such pixels...
[Notes]
you can do this on booth grayscale and RGB. Hope this helps a bit. | |
d10308 | If you just want to split by new line, it is as simple as :
yourstring.split("\n"):
A: yourstring.split(System.getProperty("line.separator"));
A: Don't split, search your String for key value pairs:
\$(?<key>[^=]++)=\{(?<value>[^}]++)\}
For example:
final Pattern pattern = Pattern.compile("\\$(?<key>[^=]++)=\\{(?<value>[^}]++)\\}");
final String input = "$key1={331015EA261D38A7}\n$key2={9145A98BA37617DE}\n$key3={EF745F23AA67243D}";
final Matcher matcher = pattern.matcher(input);
final Map<String, String> parse = new HashMap<>();
while (matcher.find()) {
parse.put(matcher.group("key"), matcher.group("value"));
}
//print values
parse.forEach((k, v) -> System.out.printf("Key '%s' has value '%s'%n", k, v));
Output:
Key 'key1' has value '331015EA261D38A7'
Key 'key2' has value '9145A98BA37617DE'
Key 'key3' has value 'EF745F23AA67243D' | |
d10309 | The for loop would be more appropriate for what you've been trying to achieve:
for($i=0; $i<count($size); $i++)
{
for($j=0; $j<count($template); $j++)
{
$currentSize = $template[$i];
$currentTemplate = $template[$j];
$query = "INSERT INTO tbl (Name, Size, Template) VALUES('$name', '$currentSize', '$currentTemplate')";
}
}
Warning: I only wrote the query in the same way you did to demonstrate the rest of the code. The query is actually vulnerable to SQL Injection attacks and you should definitely avoid it. Instead write the query like this:
$query = "INSERT INTO tbl (Name, Size, Template) VALUES(?,?,?)";
The question marks are place holders. You will need to prepare this statement and then bind $name, $currentTemplate and $currentSize to them before executing. Check this for more information on prepared statements. Since you need to execute the same query multiple times with different data you have one more reason to use prepared statements. I highly recommend you check Example#3 of the documentation in the link above | |
d10310 | The whole story sounds wrong. Not your words, but the model - why are you using table B? Keep payments where they are (table A). If you have to sum them, do so. Or create a view. But, keeping them separately in two tables just asks for a problem (the one you have now - finding a difference).
Anyway:
select a.id_customer, sum(a.payment), b.sum_payment
from a join b on a.id_customer = b.id_customer
where extract(year from a.date_column) = 2018
and extract(year from b.date_column) = 2018
group by a.id_customer, b.sum_payment
having b.sum_payment <> sum(a.payment) | |
d10311 | Is your problem for every files?
it's weird but you may try clearing cache, Go to Preferences> Media Cache and click delete.
if not works try:
restart your pc
close and reopen premiere (The most useful method)
test with other projects
and also check if you can drag it into project panel
if you can't, try another file that already worked.
hope this helps :) | |
d10312 | Fast Forward and Rewind are easy enough to do, though not in the conventional sense.
Both involve timers wherein you simply seek to a previous or future point on an interval. This is not playing the video at increased speed forward and backwards.
As for slow motion... you are in a much tighter fix there. There are 2 (theoretical) ways I know of to achieve slow motion in a flash video player. As you will see, neither of these are desirable solutions. (I have coded 3x full featured flash players + recorders and dealt with this very same rabbit hole):
1) You do not play via rtmp steaming but rather http progressive download. Once you have loaded the data into flash for the video you run it through an algorithm that either removes or duplicates p-frames. Thus increasing or decreasing video time. Audio syncing would be a nightmare even if you pull this off.
2) You encode a second video at whatever speed they wish for "slow motion" to be. You load the two videos simultaneously, and swap between them at appropriate times when the button is pressed/released. | |
d10313 | Your syntax is ever so slightly wrong. &contact on line 5 should be $contact. I assume you're on a production server, so error reporting would be disabled and you wouldn't get any warnings.
A: Try using @ before mail function
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$contact = $_POST['contact'];
$formcontent="From: $name \n Message: $message";
$recipient = "info@whatever.co.za";
$subject = "Contact form message";
$mailheader = "From: $email \r\n";
@mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("location: contact.php");
?>
this will let you pass even if mail function produce any issue. Also please check if there are any other header are not sent using http://php.net/manual/en/function.headers-sent.php function.
I would strongly suggest to use PHPMailer or some other class to send any kind of email.
A: Please check the contact.php file whether some redirection is happening from contact.php to mail.php
A: I think there may be an issue sending mail from your server. The mail.php file is probably tripping up on the mail function and not doing the redirect.
Create a new file with just the php mail function in there (with your email address and a test message) and browse it from your web browser, does it send?
A: Try to use ob_start() at the start of script, and exit(); after header("Location: contact.php");
smth like this ...
<?php
ob_start();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
&contact = $_POST['contact'];
$formcontent="From: $name \n Message: $message";
$recipient = "info@whatever.co.za";
$subject = "Contact form message";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: contact.php");
exit();
?>
A: Change the mail.php to the following:
<?php
mail("info@whatever.co.za", "Contact form message", $_POST['message'], "From: ".$_POST['name']." <".$_POST['email'].">");
header("Location: contact.php");
?> | |
d10314 | wrong version number (OpenSSL::SSL::SSLError)
SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number (OpenSSL::SSL::SSLError)
I have no idea how to get that solved as when I look that error up it is always in different situation than mine. | |
d10315 | You can create an order beforehand and then sort values as below.
order = ['PO','XY','AB','PC']
df['col1'] = pd.CategoricalIndex(df['col1'], ordered=True, categories=order)
df = df.sort_values(by = 'col1')
df
col1 col2
1 PO 2
8 PO 9
3 XY 4
4 XY 5
5 AB 6
6 AB 7
0 PC 1
2 PC 3
7 PC 8 | |
d10316 | I think it's a bug in the Dispose() method of ShapeCollection. If I look at this method using for example .NET Reflector, with Microsoft.VisualBasic.PowerPacks.Vs, Version=9.0.0.0, it says this:
foreach (Shape shape in this.m_Shapes)
{
shape.Dispose();
}
And if I look at this method using Microsoft.VisualBasic.PowerPacks.Vs, Version=10.0.0.0, it says this:
for (int i = this.m_Shapes.Count - 1; i >= 0; i--)
{
this.m_Shapes[i].Dispose();
}
Clearly, the implementation has evolved between versions. The latter one doesn't rely on an Enumerator object and therefore cannot fail with the error you show.
What's strange though is your stackframe seems to imply you're running off version 10, which shouldn't use the enumerator?? Maybe you need a VS 2010 update? Or you can also check at the Dispose implementation on the Microsoft.VisualBasic.PowerPacks.Vs you're using.
EDIT: after some digging, your application indeed runs on an old version of the VB Powerpacks. Upgrade to VS2010, SP1 or copy the DLL from a good installation. For this specific Dispose bug, you need at least 10.0.30319.1.
A: I had the same pblm with, especially with LineShape, after headache with installing and searching for right PowerPacks package, I replaced it with RichTextBox by adjusting backcolor to balck and the size, it seems weird but it's quite better for me than spending my time with this bug !! (0_o)
A: I had the same problem. I've been so confused as to what was causing the issue and have been stepping through debugging line by line for a day or so. After Google searching and typing in the right description, it turns out the issue is with line shapes on a form - and likely other shapes. See the links here, hope it saves somebody else some time... you have to read down through the comments, by like the above post it's with line shapes.
http://social.msdn.microsoft.com/Forums/en-US/cb89a159-c989-470f-b74f-df3f61b9dedd/systeminvalidoperationexception-when-closing-a-form?forum=vbpowerpacks
http://channel9.msdn.com/forums/TechOff/520076-VB-2010-Error-PowerPacks-Line-Shape-Dispose/ | |
d10317 | It seems that the EntryKey is not getting bound by the request.Sending this
{
"competition":{
"competitionId":6
},
"user":{
"userId":5
},
"number": 1
}
instead of this
{
"user_id": 1,
"competition_id": 2,
"number": 1
}
Should bind the values properly. | |
d10318 | To make a shift register, right click on the edge of the while loop and place a shift register. The Wait (ms) node is found in the timing functions pallet. #1 and #3 are found in the waveform generation pallet. And #2 is a waveform graph that is bound to the output of the filter. Just right click on the output of the filter and create an Indicator
A: I only have limited experience with the specific features in this code, so I don't have exact names, but it should point you in the right direction:
2 is a dynamic data indicator.
1 converts it to a waveform (it probably appears automatically if you hook up a DDT wire to a WF function.
3 unbundles the data from the waveform. It should be in the waveform palette.
4 is a shift register.
5 is a wait function.
In general, I would recommend that you get to learning, as you will need to understand these things to at least that level before you can be proficient.
Also, the NI forums are much more suitable for this type of question and they have many more users. I would suggest if you have such questions which you can't answer yourself, then post them there. | |
d10319 | Your failing requeststokens have\x`.
You will have to encode the value and send the request.
*
*In HTTP Request
Check the filed URL encode?
*Encoding the value with function
A: It sounds like a bug in your application, I don't think it's JMeter issue, presumably it's due to presence of these \x2D characters (may be incorrect work of unicode escape)
I don't know what does your application expect instead of this \x2D try to inspect the JavaScript code of the application to see what it does do the tokens, when you figure this out you can replicate this token conversion logic in JSR223 PreProcessor and Groovy language | |
d10320 | Using a class rather than a String[]
We identified that each employee has name, hours, wage, total values, instead of representing this in a String[], we can use a class
class Employee{
private String name;
private int hours;
private int wage;
private int total;
public Employee(String name, int hours, int wage){
this.name = name;
this.hours = hours;
this.wage = wage;
this.total = hours * wage;
}
public String getName(){
return name;
}
public int getHours(){
return hours;
}
public int getWage(){
return wage;
}
public int getTotal(){
return total;
}
public String toString(){
return String.format("%s %d %d %d", name, hours, wage, total);
}
}
Now we have defined how an Employee looks like, so now we can use Employee
Putting the Employee into a List
public class EmployeeData{
public static void main(String[] args){
List<Employee> employees = new ArrayList<Employee>();
Employee bobby = new Employee("Bobby", 45, 35);
Employee rick = new Employee("Rick", 15, 33);
Employee mike = new Employee("Mike", 66, 50);
Employee jayme = new Employee("Jayme", 15, 45);
employees.add(bobby);
employees.add(rick);
employees.add(mike);
employees.add(jayme);
//Now we have added all the employees, so we can just run through them
System.out.println("Employee Hours Wage Total");
for(Employee employee: employees){
System.out.println(employee.toString());
}
}
}
Now you don't have to calculate everything many times, but just run through the list once, if you want to change the total, then you can calculate it inside here
public Employee(String name, int hours, int wage){
this.name = name;
this.hours = hours;
this.wage = wage;
this.total = hours * wage;
} | |
d10321 | After a little research, I think I fixed it...I had to change my jquery to this:
...
$(document).on("click", "#loginlinkdiv a", function(e) {
e.preventDefault();
location.reload();
$("#main").load("templates/indexforms.php");
});
...
I don't think that application.js was being executed (on second login) because index.php didn't reload the script upon clicking the "loginlinkdiv" link...the only way I could think to do this was to use location.reload(); which I think is reloading index.php - and the script is being read again. Anyone who can clarify why this works (or maybe suggest a better answer) gets kudos. | |
d10322 | In case you will remove the whole rows which contain NAN, you can use simply
df.dropna()
However you can't remove particular row from specified dataframe column because each row indexed by default which means all columns in a row cohere, and if you remove rows from first column the other columns are longer which is not possible. | |
d10323 | Am I right that the with-modal and without-modal templates load from two different views? If so, the problem is how you are using Django's {% include %} template tag. Here are the docs:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include
Key line: "An included template is rendered within the context of the template that includes it."
It looks like menu_perfil.html is rendered from a different view, which doesn't pass the form object into its context. So menu_perfil.html doesn't know what {{ form }} is. Whereas change-username.html is rendered with your UsernameUpdate view with the form object. Try moving your modal HTML into change-username.html, around your form code, instead of including a separate snippet, and see if that solves the problem.
In general, inheriting from base templates using {% extends %} is preferable to using includes unless you really have to, because of limitations like this. | |
d10324 | Okay, the part you need to pass in the header is the "some-really-long-access-token"
Example:
curl --compressed --header "Authorization: Bearer some-really-long-access-token" "https://livestream.adobe.net/api/1/stream/myendpoint"
So just pay attention to the encoding on the ".
*
*“ is not the same as "
*When copying / pasting from HTML, Rich text, or something other than a code block, it's best to check this
Edit:
Your question is tagged php, but your examples are using the command line, therefore, ensure your command is formatted using the following points:
First and foremost:
*
*The examples on the Adobe Developer Connection page also showing arguments inside [square brackets], for example:
Other general things to check:
*
*A header is passed like this: -H "Header-name: Header-Value"
*
*Therefore, if my access token was 29035-97v657zyr8qk966y143k2v0p365460xbd1pvk9p6
Then my header arguments would be this:
*
*-H "Authorization: Bearer 29035-97v657zyr8qk966y143k2v0p365460xbd1pvk9p6"
*You can explicitly specify the url to cURL using --url. I don't usually do this because it shouldn't be necessary if everything is correct, but it may help refine the error message.
*
*So my URL arguments would be this:
*
*--url "https://livestream.adobe.net/api/1/stream/myendpoint"
*Be sure as described above NOT to use LEFT AND RIGHT DOUBLE QUOTATION MARK “ and ”, but the standard " found on the computer keyboard. The standard " is what the shell uses to contain arguments | |
d10325 | 1) Does jmt.test.TestCodeBase extend TestCase (junit.framework.TestCase)?
If not, it will need to to be picked up by the junit ant task.
2) Is the class written as a junit TestCase, or is it just called from the main method? See this link for an example of writing simple tests in Junit3 style. For Junit4, just add @Test above the methods.
3) Are the test methods in Junit3 style (every method starts with test) or Junit4 style (every method has a @Test above it)?
If Junit3, you should be good to go. If Junit4, you need to include the Junit4 test library in your ant classpath, rather than using junit3.8.1.
A: It seems your test class is not actually a JUnit test class. When you run it manually, you are not running it as a test, but as a regular Java application. The class has a main method, right? To run as a JUnit 3 (which you seem to be using) test, the class needs to extend TestCase and have one or more public void methods whose names start with 'test'. For testing, I would try running the class as a JUnit test in the IDE.
A: Please post sample code of jmt.test.TestCodeBase, esp. class definition and one of the test methods.
I looks like you use public static int main() instead of JUnit convention public void testFoo() methods. If you're using JUnit4, your test methods should have the @Test annotation.
JUnit tests usually cannot be run just with java <Testclass> | |
d10326 | *
*Get a GitHub account, install GitHub software, and commit some code to your repo
*Get a free Heroku account, and install Heroku CLI on your computer.
*Point your Heroku account, in its configuration, to your Git repo's master branch
*If your app consists of static files, follow the following instructions (Heroku only hosts non-static sites):
Add a file called composer.json to the root directory by running:
touch composer.json
Add a file called index.php to the root directory by running:
touch index.php
Rename the homepage (e.g. index.html) to home.html
In index.php, add the following line:
<?php include_once("home.html"); ?>
In composer.json, add the following line:
{}
From a command line, CD into your project's root directory. Run the following command:
git push heroku master
*You should now have a staging server on Heroku, with https enabled. Whenever you commit code to your master branch and sync it with GitHub.com, there will automatically be a deployment behind the scenes from your GitHub repository to your Heroku hosting account. Boom! You have all the ingredients you need to stage a successful PWA application. Production hosting is up to you, maybe try DigitalOcean to start with. | |
d10327 | You might want to use something like:
tweedie_model.estimate_tweedie_power(tweedie_result.mu, method='brentq', low=1.01, high=5.0)
Reference: https://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.estimate_tweedie_power | |
d10328 | Looks like a bubble sort to me | |
d10329 | Don't use an arrow function - it loses the binding to this which is what you're trying to access. Just use a normal function:
const setFavorite = function(val) {...}; | |
d10330 | Given that you're using the Axiom XPath library, which in turn uses Jaxen, you'll need to follow the following three steps to do this in a thoroughly robust manner:
*
*Create a SimpleVariableContext, and call context.setVariableValue("val", "value1") to assign a value to that variable.
*On your BaseXPath object, call .setVariableContext() to pass in the context you assigned.
*Inside your expression, use /a/b/c[x=$val]/y to refer to that value.
Consider the following:
package com.example;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.common.AxiomText;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axiom.om.xpath.DocumentNavigator;
import org.jaxen.*;
import javax.xml.stream.XMLStreamException;
public class Main {
public static void main(String[] args) throws XMLStreamException, JaxenException {
String xmlPayload="<parent><a><b><c><x>val1</x><y>abc</y></c>" +
"<c><x>val2</x><y>abcd</y></c>" +
"</b></a></parent>";
OMElement xmlOMOBject = AXIOMUtil.stringToOM(xmlPayload);
SimpleVariableContext svc = new SimpleVariableContext();
svc.setVariableValue("val", "val2");
String xpartString = "//c[x=$val]/y/text()";
BaseXPath contextpath = new BaseXPath(xpartString, new DocumentNavigator());
contextpath.setVariableContext(svc);
AxiomText selectedNode = (AxiomText) contextpath.selectSingleNode(xmlOMOBject);
System.out.println(selectedNode.getText());
}
}
...which emits as output:
abcd
A: It depends on the language in which you're using XPath.
In XSLT:
"//a/b/c[x=$myParamForXAttribute]"
Note that, unlike the approach above, the three below are open to XPath injection attacks and should never be used with uncontrolled or untrusted inputs; to avoid this, use a mechanism provided by your language or library to pass in variables out-of-band. [Credit: Charles Duffy]
In C#:
String.Format("//a/b/c[x={0}]", myParamForXAttribute);
In Java:
String.format("//a/b/c[x=%s]", myParamForXAttribute);
In Python:
"//a/b/c[x={}]".format(myParamForXAttribute) | |
d10331 | I would do it following way
import pandas as pd
df = pd.DataFrame({'Expected':['A','A','C','B','C','A','B','A'],'Actual':['B','A','B','D','D','A','B','D']})
ecnt = df['Expected'].value_counts()
acnt = df['Actual'].value_counts()
known = sorted(set(df['Expected']).union(df['Actual']))
cntdf = pd.DataFrame({'Value':known,'Expected':[ecnt.get(k,0) for k in known],'Actual':[acnt.get(k,0) for k in known]})
print(cntdf)
output
Value Expected Actual
0 A 4 2
1 B 2 3
2 C 2 0
3 D 0 3
Explanation: main idea here is having separate value counts for Expected column and Actual column. If you wish to rather have Value as Index of your pandas.DataFrame you can do
...
cntdf = pd.DataFrame([acnt,ecnt]).T.fillna(0)
print(cntdf)
output
Actual Expected
D 3.0 0.0
B 3.0 2.0
A 2.0 4.0
C 0.0 2.0
A: You can use apply and value_counts
df = pd.DataFrame({'Expected':['A','A','C','B','C','A','B','A'],'Actual':['B','A','B','D','D','A','B','D']})
df.apply(pd.Series.value_counts).fillna(0)
output:
Expected Actual
A 4.0 2.0
B 2.0 3.0
C 2.0 0.0
D 0.0 3.0 | |
d10332 | Normally, you just need to check in the template xaml files under the BuildProcessTemplate folder, then in Build Definition Process tab, Click New… button to add these xaml files from that fold. The path of xaml should have a \ sample in front of it.
In your case, also try to clear TFS and VS cache, then try it again.
If delete cache folder still doesn't work, please try it with older Visual Studio Version such as Visual Studio 2015 and create a new build definition, select the template.
Also take a look at this blog shows the customize process template experience in TFS 2013, which may be helpful. | |
d10333 | There is clearly room for improvement on the kernel side here and chances are it's a reasonably low hanging fruit. I'm not going to speculate. Chances are the problem will be easily visible with flamegraphs.
However, considerations of the sort in this context are a red herring. For the sake of argument let's assume the kernel pushes all these error messages with 0 overhead. You have generated gigabytes of repetitive error messages adding no value.
Instead, when there is a major event just log it once and then log again that it is cleared (e.g. note the connection to the database died, note when it got back up, but don't log on each query that it is dead). Alternatively you can log this periodically or with ratelimit. Either way, just spamming is the wrong thing to do.
The sheer number of children (1000+?) seems extremely excessive and puts a question mark on the validity of the design of this project. Can you elaborate what's happening there? | |
d10334 | Correct
This is correct because you specify that the content of CUSTOMPATH is actually a reference a different Property (or Directory because a certain point Directory elements become available to be used like Property elements):
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" />
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/>
The above will visualize the content of INSTALLFOLDER so that's ok.
However, the actual value of CUSTOMPATH will never change. It should always remain a reference to another property because you use it with Indirect=Yes.
Possible root cause of your problem
In the next part you assign a value to CUSTOMPATH and that's where I think something goes wrong. I tried the following and it gave me the requested result ("C:\Program Files..." in the registry value).
<Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[INSTALLFOLDER]" Order="1">1</Publish>
<RegistryValue Root='HKLM' Key='Software\Test\TestRegEntry1' Type='string' Value='[INSTALLFOLDER]' KeyPath='yes'/>
If this doesn't work, could you provide me with the logfile?
zzz.msi /lvoicewarmupx debug.log
A: So basically what I did to fix this issue was that I created right beside INSTALLFOLDER another directory. Since I didn't add any files into it, that folder will not be created, but value as such remains.
<Directory Id="INSTALLFOLDER2" Name="!(bind.property.ProductName)"></Directory>
<Directory Id="INSTALLFOLDER" Name="!(bind.property.ProductName)">
<!-- Here are files I wanted to include -->
</Directory>
Registry entry now looks like this:
<DirectoryRef Id="TARGETDIR">
<Component Id="RegistryEntries" Guid="here comes your guid">
<RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value="[INSTALLFOLDER2]" KeyPath='yes' />
</Component>
</DirectoryRef>
And Property like this:
<Property Id="CUSTOMPATH" Value="INSTALLFOLDER2" Secure="yes" />
Folder selector controls look like this, so both typing and button (folder selector) work. Dialog that uses them is exactly like InstallDirDlg, but with a different name.
<Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes" />
<Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" /> | |
d10335 | boolean flag=false;
for(String files:user){
for(String dbu:docbaseuser){
if(files.equalsIgnoreCase(dbu)){
flag=true;
}
}
if(flag){
//user already exists
flag=false;
}
A: I think u can achieve it this way:
public Set<String> fetch (Set<String> here, Set<String> notHere) {
return here.stream()
.filter(h -> !isIn(h, notHere))
.collect(Collectors.toCollection(HashSet::new));
}
private boolean isIn (String s, Set<String> set) {
for (String str : set) {
if (str.equalsIgnoreCase(s)) return true;
}
return false;
}
EDIT: If you don't need equalsIgnoreCase then you can do this:
public Set<String> fetch (Set<String> here, Set<String> notHere) {
return here.stream()
.filter(h -> !notHere.contains(h))
.collect(Collectors.toCollection(HashSet::new));
}
A: If you need a set of all strings in user which are not present in docbaseuser as if you compared one by one using String.equalsIgnoreCase() but want the O(1) complexity of looking up elements in a HashSet or O(log n) complexity of TreeSet beware not to simply convert all strings to upper case or lower case by using String.toUpperCase() or alike. E.g. one might be tempted to use new TreeSet<>(String.CASE_INSENSITIVE_ORDER).
Here is a solution that behaves exactly like comparing strings using String.equalsIgnoreCase() with O(1) complexity at the initial cost of building a HashSet which is used as an index. But depending on context this could be maintained somewhere else and kept in sync with changes to docuserbase contents.
@FunctionalInterface
private static interface CharUnaryOperator {
char applyAsChar(char operand);
}
private static String mapCharacters(String s, CharUnaryOperator mapper) {
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++)
chars[i] = mapper.applyAsChar(chars[i]);
return String.valueOf(chars);
}
private static Set<String> stringsNotPresentInOtherSetIgnoreCase(Set<String> set, Set<String> otherSet) {
Set<String> index = otherSet.stream()
.flatMap(s -> Stream.of(
mapCharacters(s, Character::toUpperCase),
mapCharacters(s, Character::toLowerCase)
))
.collect(Collectors.toCollection(HashSet::new));
return set.stream()
.filter(s -> !index.contains(mapCharacters(s, Character::toUpperCase)))
.filter(s -> !index.contains(mapCharacters(s, Character::toLowerCase)))
.collect(Collectors.toCollection(HashSet::new));
}
private static void test() {
Set<String> user = Stream.of("max", "John", "PETERSSON", "Tommy", "Strauß").collect(Collectors.toSet());
Set<String> docbaseuser = Stream.of("Max", "Petersson", "Steve", "Brad", "Strauss").collect(Collectors.toSet());
Set<String> usersNotInDocbaseuser = stringsNotPresentInOtherSetIgnoreCase(user, docbaseuser);
if (!usersNotInDocbaseuser.equals(Stream.of("John", "Tommy", "Strauß").collect(Collectors.toSet()))) {
System.out.println("Wrong result");
}
}
Paste that code to some class and call test() in order to make sure that the stringsNotPresentInOtherSetIgnoreCase() method works correctly. Pay special attention to the strings Strauß and Strauss which are considered equal when transformed using String.toUpperCase() before:
System.out.println("Strauß".toLowerCase().equals("strauss".toLowerCase()));
System.out.println("Strauß".toUpperCase().equals("strauss".toUpperCase()));
System.out.println("Strauß".equalsIgnoreCase("strauss"));
Result:
false
true
false | |
d10336 | Try something like this just to make your code look a little bit more elegant and not so clunky
$dayOfWeek = date('w'); //0 for Sunday through 6 for Saturday
$hourOfDay = date('H'); //0-23
$eventOne = null;
$eventTwo = null;
$eventThree = null;
//logic structure to set events
if($hourOfDay >= 0 && $hourOfDay < 2){
$dayOfWeek -= 1; //set to previous day if earlier than 2AM
$dayOfWeek = $dayOfWeek == 0 ? 6 : $dayOfWeek; //quick check to set to Sunday if day was on Monday
$eventOne = $dayOfWeek;
$eventTwo = $dayOfWeek+1;
$eventThree = $dayOfWeek+2;
//single line if statements to correct weekly overflow
if($eventTwo == 7) $eventTwo = 0;
if($eventThree == 7) $eventThree = 0;
if($eventThree == 8) $eventThree = 1;
}else{
$eventOne = $dayOfWeek;
$eventTwo = $dayOfWeek+1;
$eventThree = $dayOfWeek+2;
//single line if statements to correct weekly overflow
if($eventTwo == 7) $eventTwo = 0;
if($eventThree == 7) $eventThree = 0;
if($eventThree == 8) $eventThree = 1;
}
function getDayOfEvent($event){
switch($event){
case 0: return "Sunday"; break;
case 1: return "Monday"; break;
case 2: return "Tuesday"; break;
case 3: return "Wednesay"; break;
case 4: return "Thursday"; break;
case 5: return "Friday"; break;
case 6: return "Saturday"; break;
}
}
print "Event One: ". getDayOfEvent($eventOne)."\nEvent Two: ".getDayOfEvent($eventTwo)."\nEvent Three: ".getDayOfEvent($eventThree);
Let me know if something like this works for you. I'm sorry but I was having a hard time translating your English, I tried my best :) I hope this helps you, if not please let me know and I will help you fix it so that it does.
Here's a paste on CodePad where you can play around with the code a little bit if you want http://codepad.org/SLcTeGEt
A: Try this program... maybe is what you want. (Your question is very confusing.)
/* Day Of Week 0 = Sun ... 6 = Sat
* ---------------------------------
* Day Hour Result Case
* ---------------------------------
* 5 00 - 02 No event C
* 5 02 - 24 Event 1 B
* 6 00 - 02 Event 1 A
* 6 02 - 24 Event 2 B
* 0 00 - 02 Event 2 A
* 0 02 - 24 Event 3 B
* 1 00 - 02 Event 3 A
* 1 02 - 24 No Event C
* Other Other No Event C
* ---------------------------------
*/
function getEvent( $timestamp, $eventTime ) {
$d = (int) date( 'w', $timestamp ); // Day
$h = (int) date( 'G', $timestamp ); // Hour
$event = $h < $eventTime && ( $d > 5 || $d < 2 ) // Case A
? ( $d + 2 ) % 7 // Case A Result
: ( $h >= $eventTime && ( $d > 4 || $d == 0 ) // Case B
? ( $d + 3 ) % 7 // Case B Result
: null ); // Case C Result
printf ( "\n%s %02d:00 :: %s", // ... and show
date( 'D', strtotime( "Sunday +{$d} days" ) ),
$h, $event ? "Event $event" : 'No event' );
}
$eventTime = 2;
echo '<pre>';
/* Testing the getEvent function */
for ( $timestamp = mktime( 23, 0, 0, 4, 30, 2015 ); // Thu at 23:00
$timestamp <= mktime( 22, 0, 0, 5, 7, 2015 ); // Thu at 22:00
$timestamp += 3600 * 2 ) { // Each 2 hours
getEvent( $timestamp, $eventTime );
}
?> | |
d10337 | lapply(mtcars[,-1], cor, mtcars[,1])
# [[1]]
# [1] -0.852162
# [[2]]
# [1] -0.8475514
# [[3]]
# [1] -0.7761684
# [[4]]
# [1] 0.6811719
# [[5]]
# [1] -0.8676594
# [[6]]
# [1] 0.418684
# [[7]]
# [1] 0.6640389
# [[8]]
# [1] 0.5998324
# [[9]]
# [1] 0.4802848
# [[10]]
# [1] -0.5509251
A: Actually, dumb answer, still can do a correlation matrix but using use="pairwise.complete.obs
A: If there is no missing values, you can just do:
set.seed(100)
mat = data.frame(matrix(runif(1000),ncol=100))
colnames(mat) = paste0("V",1:100)
cor(mat[,1],mat[,2:100])
If there are missing values:
set.seed(100)
mat = matrix(runif(1000),ncol=100)
mat[sample(length(mat),100)] <- NA
mat = data.frame(matrix(runif(1000),ncol=100))
colnames(mat) = paste0("V",1:100)
cor(mat[,1],mat[,2:100],use="p") | |
d10338 | You should use that id_option as the key in your new array, otherwise you're stuck having to hunt through the new array to find where the matching items are, which you're ALREADY doing in the first loop
$newarray = array();
foreach($oldarray as $item) {
$newarray[$item['id_option']][] = $item;
}
A: I have tested with you example and seems to work fine :
$notFactored; # you should provide here your input array
$factored = array();
foreach($notFactored as $nf) {
$found = FALSE;
foreach($factored as &$f) { # passed by address !
if(!empty($f[0]) && $nf['id_option'] == $f[0]['id_option']) {
$f[] = $nf;
$found = TRUE;
break;
}
}
if(!$found) {
$factored[count($factored)][] = $nf;
}
}
print 'my factored array : ' . print_r($factored);
Hope that Helps :) | |
d10339 | Short answer: adding Peach to this collection is possible, because Groovy does dynamic cast from Collection to Set type, so fruitSet variable is not of type Collections$UnmodifiableCollection but LinkedHashSet.
Take a look at this simple exemplary class:
class DynamicGroovyCastExample {
static void main(String[] args) {
Set<String> fruits = new HashSet<String>()
fruits.add("Apple")
fruits.add("Grapes")
fruits.add("Orange")
Set<String> fruitSet = Collections.unmodifiableCollection(fruits)
println(fruitSet)
fruitSet.add("Peach")
println(fruitSet)
}
}
In statically compiled language like Java, following line would throw compilation error:
Set<String> fruitSet = Collections.unmodifiableCollection(fruits)
This is because Collection cannot be cast to Set (it works in opposite direction, because Set extends Collection). Now, because Groovy is a dynamic language by design, it tries to cast to the type on the left hand side if the type returned on the right hand side is not accessible for the type on the left side. If you compile this code do a .class file and you decompile it, you will see something like this:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class DynamicGroovyCastExample implements GroovyObject {
public DynamicGroovyCastExample() {
CallSite[] var1 = $getCallSiteArray();
MetaClass var2 = this.$getStaticMetaClass();
this.metaClass = var2;
}
public static void main(String... args) {
CallSite[] var1 = $getCallSiteArray();
Set fruits = (Set)ScriptBytecodeAdapter.castToType(var1[0].callConstructor(HashSet.class), Set.class);
var1[1].call(fruits, "Apple");
var1[2].call(fruits, "Grapes");
var1[3].call(fruits, "Orange");
Set fruitSet = (Set)ScriptBytecodeAdapter.castToType(var1[4].call(Collections.class, fruits), Set.class);
var1[5].callStatic(DynamicGroovyCastExample.class, fruitSet);
var1[6].call(fruitSet, "Peach");
var1[7].callStatic(DynamicGroovyCastExample.class, fruitSet);
}
}
The interesting line is the following one:
Set fruitSet = (Set)ScriptBytecodeAdapter.castToType(var1[4].call(Collections.class, fruits), Set.class);
Groovy sees that you have specified a type of fruitSet as Set<String> and because right side expression returns a Collection, it tries to cast it to the desired type. Now, if we track what happens next we will find out that ScriptBytecodeAdapter.castToType() goes to:
private static Object continueCastOnCollection(Object object, Class type) {
int modifiers = type.getModifiers();
Collection answer;
if (object instanceof Collection && type.isAssignableFrom(LinkedHashSet.class) &&
(type == LinkedHashSet.class || Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers))) {
return new LinkedHashSet((Collection)object);
}
// .....
}
Source: src/main/org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.java#L253
And this is why fruitSet is a LinkedHashSet and not Collections$UnmodifableCollection.
Of course it works just fine for Collections.unmodifiableSet(fruits), because in this case there is no cast needed - Collections$UnmodifiableSet implements Set so there is no dynamic casting involved.
How to prevent similar situations?
If you don't need any Groovy dynamic features, use static compilation to avoid problems with Groovy's dynamic nature. If we modify this example just by adding @CompileStatic annotation over the class, it would not compile and we would be early warned:
Secondly, always use valid types. If the method returns Collection, assign it to Collection. You can play around with dynamic casts in runtime, but you have to be aware of consequences it may have.
Hope it helps. | |
d10340 | Try this:
Pathtest::Application.routes.draw do
resources :first do
resources :second do
resources :third
end
end
end | |
d10341 | In a PHP script you can turn error reporting on with:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Error and warnings will show up that will give you possibly a hint where your script is failing. | |
d10342 | In the end I realized I was over-thinking the problem. Nested styles were unnecessary. The solution was to set the background as the VisualBrush (with its content set up as the desired final appearance) inside its own tag within the ItemsControl and then animate the opacity of the VisualBrush using EventTriggers directly on the ItemsControl. Note the various events to manage both mouse and dragging user activity.
Thanks to anyone who was thinking about this problem. The final XAML looks like this and hopefully will be useful to someone.
<ItemsControl x:Name="OrFilterItemsTarget"
ItemsSource="{Binding Assets.OrFilters}"
ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
ItemContainerStyle="{StaticResource DraggableItemStyle}"
BorderThickness="0,0,0,0.5"
BorderBrush="DimGray"
AllowDrop="True"
IsHitTestVisible="True"
Margin="0,2.95,15.934,77"
HorizontalAlignment="Right"
Width="105">
<ItemsControl.Background>
<VisualBrush x:Name="OrFilterContentType"
AlignmentX="Center"
AlignmentY="Center"
Stretch="None"
Opacity="0">
<VisualBrush.Visual>
<Label Content="OR"
Foreground="DarkGray"
Opacity="0.5" />
</VisualBrush.Visual>
</VisualBrush>
</ItemsControl.Background>
<ItemsControl.Triggers>
<EventTrigger RoutedEvent="ItemsControl.MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="0" To="1"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.DragEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="0"
To="1"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1" To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.DragLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1"
To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.Drop">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1"
To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</ItemsControl.Triggers>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"
Background="Transparent">
<i:Interaction.Behaviors>
<ei:FluidMoveBehavior AppliesTo="Children"
Duration="0:0:0.3">
<ei:FluidMoveBehavior.EaseY>
<BackEase EasingMode="EaseIn"
Amplitude="0.1" />
</ei:FluidMoveBehavior.EaseY>
</ei:FluidMoveBehavior>
</i:Interaction.Behaviors>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl> | |
d10343 | You can disable resizing with
object_resizing : false | |
d10344 | This post is not going to be an answer, it didn't really solve the problem. The purpose is to provide more valuable information.
Create two symbolic links in your build top directory. It will get rid of the problem. Run following command in you build top directory.
$ ln -s build/soong/bootstrap.bash
$ ln -s build/soong/Android.bp
But as you go further, you will encounter problems like following
FAILED: out/soong/.bootstrap/bin/minibp -t -m ./build/soong/build.ninja.in -b out/soong -d out/soong/.bootstrap/bootstrap.ninja.in.d -o out/soong/.bootstrap/bootstrap.ninja.in Android.bp
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint"
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint-bootstrap"
[2/4] minibp out/soong/.bootstrap/primary.ninja.in
FAILED: out/soong/.bootstrap/bin/minibp --build-primary -t -m ./build/soong/build.ninja.in --timestamp out/soong/.bootstrap/primary.ninja.in.timestamp --timestampdep out/soong/.bootstrap/primary.ninja.in.timestamp.d -b out/soong -d out/soong/.bootstrap/primary.ninja.in.d -o out/soong/.bootstrap/primary.ninja.in Android.bp
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint"
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint-bootstrap"
ninja: error: rebuilding 'out/soong/build.ninja': subcommand failed
make: *** [run_soong] Error 1
I have no idea how to solve this either. Maybe the new build system for aosp master branch is not fully prepared. | |
d10345 | After trying with few examples on gstreamer elements, found the problem.
Apart from filesrc, filter, fakesink:: If I add 'decoder' element also to the pipeline, then I am able to change the state to PLAYING
But why is that required - I am still trying to figure it out
And sometimes, the name used to create pipeline is also causing problems: Better to use some unique name rather than pipeline in gst_pipeline_new ("pipeline"); | |
d10346 | Based on the fact that all collations align, then one reason may be a trigger firing on update. This is why the exact error message is important.
For example, do you have an audit trigger attempting to log the update into a case sensitive column?
Saying that, I've never tried to create an FK between 2 different collations (I can't test right now): not sure if it would work.
One factual way to test for SomeUser vs someuser would be a simple GROUP BY: do you get one count per value or one for both values
Edit: check for trailing spaces... | |
d10347 | ... Because they're test data ?
You can't rely on real rakismet data in your test. Because any test can be detected as spam one day or an other.
Or just because using rakismet requires that you have an internet connection, which can sometimes not be the case.
You should mock the rakismet methods and force them to return what you expect them to.
For example you can use mocha. And do something like the following :
Object.stubs(:spam?).returns(false)
So your objects will never be spams. | |
d10348 | I believe this occurs when you are running Postgres 9.x and the data you imported came from Postgres 10. | |
d10349 | If you are trying to expose the entire object, you build it like you would any other JavaScript object and then use module.exports at the end :
MyObj = function(){
this.somevar = 1234;
this.subfunction1 = function(){};
}
module.exports = MyObj;
If you just want to expose certain functions, you don't NEED to build it like an object, and then you can export the individual functions :
var somevar = 1234;
subfunction1 = function(){};
nonExposedFunction = function(){};
module.exports = {
subfunction1:subfunction1,
somevar:somevar
};
A: you simply assign the result of JSON.parse to this.jsonObj:
module.exports = {
parse: function (res) {
this.jsonObj = JSON.parse(res);
}
};
Using this.jsonObj you are exposing the JSON object to the outside and you can use your module in this way:
var parser = require('./parser.js'),
jsonString = // You JSON string to parse...
parser.parse(jsonString);
console.log(parser.jsonObj); | |
d10350 | Ok! So I am responding my own question in case someone needs it.
Thanks to Tenfour04 for his comment, since it helped me to find it.
The correct method to call was clearChildren(). This is my new code:
public void setVisible(boolean visible) {
if (!visible){
this.clearChildren();
} else {
this.add(new Label("Name: " + getCalledBy().getName(), getSkin()));
this.row();
this.add(new Label("Attack: " + getCalledBy().getAttack(), getSkin()));
this.row();
this.add(new Label("Defense: " + getCalledBy().getDefense(), getSkin()));
this.row();
this.add(new Label("Health: " + getCalledBy().getHealth(), getSkin()));
}
super.setVisible(visible);
}
Hope this helps someone else in the future. | |
d10351 | Looks like the expected results in both cases... In the first case C calls to A (next class in MRO) which prints "init A" and returns so flow comes back to C which prints "init C" and returns. Matches your output.
In the second case C calls A (next in MRO) which calls B (next to A in MRO) which prints "init B" and returns so flow comes back to A which prints "init A" and returns back to C which prints "init C". | |
d10352 | You can set android:exported="false" for the activity in your manifest:
android:exported :
This element sets whether the activity can be
launched by components of other applications — "true" if it can be,
and "false" if not. If "false", the activity can be launched only by
components of the same application or applications with the same user
ID. If you are using intent filters, you should not set this element
"false". If you do so, and an app tries to call the activity, system
throws an ActivityNotFoundException. Instead, you should prevent other
apps from calling the activity by not setting intent filters for it.
If you do not have intent filters, the default value for this element
is "false". If you set the element "true", the activity is accessible
to any app that knows its exact class name, but does not resolve when
the system tries to match an implicit intent.
This attribute is not the only way to limit an activity's exposure to
other applications. You can also use a permission to limit the
external entities that can invoke the activity (see the permission
attribute).
<activity
android:name=".activities.YourActivity"
android:exported="false" />
You can do same for BroadcastReceiver. | |
d10353 | Putting it in the Detail band is wrong (as you noticed). Putting it in the Title or Summary will work. Your choice of evaluationTime="Page" doesn't look right. Try changing this to evaluationTime="Report" | |
d10354 | The FirebaseUI-Android/Firestore project has an adapter that does what you want. This does the heavy lifting of managing a RecyclerView for you. In order to have a layout like in GridView, you can create an instance of GridLayoutManager in onCreate and pass that to RecyclerView.setLayoutManager
If you want to hack it yourself, the QuerySnapshot has a property documentChanges that you can check for REMOVED - cf. View changes between snapshots. To get an idea of how it would be implemented with a GridView you can look at the source code of RecyclerView.Adatper - epecially the notifyItemXXX methods. | |
d10355 | Your top level element is an NSArray (@[], with square brackets, makes an array) of two NSDictionary's. To access an attribute in one of the dictionaries, you would do array[index][key], e.g. array[0][@"Country"] would give you @"Afghanistan". If you did NSArray *array = ... instead of NSDictionary *dict = ...
If you want to pick a country at random, you can get a random number, get it mod 2 (someInteger % 2) and use that as your index, e.g. array[randomNumber % 2][@"Country"] will give you a random country name from your array of dictionaries.
If you store an image name in the dictionaries, you can load an image of that name using UIImage's +imageNamed: method.
A: Here's more complete instruction on mbuc91's correct idea.
1) create a country
// Country.h
@interface Country : NSObject
@property(strong,nonatomic) NSString *name;
@property(strong,nonatomic) NSString *capital;
@property(strong,nonatomic) NSString *flagUrl;
@property(strong,nonatomic) UIImage *flag;
// this is the only interesting part of this class, so try it out...
// asynchronously fetch the flag from a web url. the url must point to an image
- (void)flagWithCompletion:(void (^)(UIImage *))completion;
@end
// Country.m
#import "Country.h"
@implementation Country
- (id)initWithName:(NSString *)name capital:(NSString *)capital flagUrl:(NSString *)flagUrl {
self = [self init];
if (self) {
_name = name;
_capital = capital;
_flagUrl = flagUrl;
}
return self;
}
- (void)flagWithCompletion:(void (^)(UIImage *))completion {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.flagUrl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
completion(image);
} else {
completion(nil);
}
}];
}
@end
2) Now, in some other class, use the Country
#import "Country.h"
- (NSArray *)countries {
NSMutableArray *answer = [NSMutableArray array];
[answer addObject:[[Country alloc]
initWithName:@"Afghanistan" capital:@"Kabul" flagUrl:@"http://www.flags.com/afgan.jpg"]];
[answer addObject:[[Country alloc]
initWithName:@"Albania" capital:@"Tirana" flagUrl:@"http://www.flags.com/albania.jpg"]];
return [NSArray arrayWithArray:answer];
}
- (id)randomElementIn:(NSArray *)array {
NSUInteger index = arc4random() % array.count;
return [array objectAtIndex:index];
}
-(void)someMethod {
NSArray *countries = [self countries];
Country *randomCountry = [self randomElementIn:countries];
[randomCountry flagWithCompletion:^(UIImage *flagImage) {
// update UI, like this ...
// self.flagImageView.image = flagImage;
}];
}
A: You cannot initialize an NSDictionary in that way. An NSDictionary is an unsorted set of key-object pairs - its order is not static, and so you cannot address it as you would an array. In your case, you probably want an NSMutableDictionary since you will be modifying its contents (see Apple's NSMutableDictionary Class Reference for more info).
You could implement your code in a few ways. Using NSDictionaries you would do something similar to the following:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:@"Afghanistan", @"Country",
@"Kabul", @"Capital", nil];
You would then have an array of dictionaries, with each dictionary holding the details of one country.
Another option would be to create a simple model class for each country and have an array of those. For example, you could create a Class named Country, with Country.h as:
#import <Foundation/Foundation.h>
@interface Country : NSObject
@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *Capital;
//etc...
@end | |
d10356 | A good way to do this is to add the gesture recognizer in the UITableViewCell subclass and also have a delegate property in that class as well. So in your subclass:
protocol MyCustomCellDelegate {
func cell(cell: MyCustomCell, didPan sender: UIPanGestureRecognizer)
}
class MyCustomCell: UITableViewCell {
var delegate: MyCustomCellDelegate?
override func awakeFromNib() {
let gesture = UIPanGestureRecognizer(target: self, action: "panGestureFired:")
contentView.addGestureRecognizer(gesture)
}
func panGestureFired(sender: UIPanGestureRecognizer) {
delegate?.cell(self, didPan: sender)
}
}
Then in cellForRowAtIndexPath you just assign you view controller as the cells delegate.
A: You could add your pan gesture to the UITableViewCell in cellForRowAtIndexPath.
Then extract the optional UITableViewCell and look up the indexPath in the tableView.
Make sure you setup the UITableView as an IBOutlet so you can get to it in didPan:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PanCell", forIndexPath: indexPath)
let panGesture = UIPanGestureRecognizer(target: self, action: "didPan:")
cell.addGestureRecognizer(panGesture)
return cell
}
func didPan(sender: UIPanGestureRecognizer) {
// Sender will be the UITableViewCell
guard let cell = sender.view as? UITableViewCell else {
return
}
let indexPathForPan = tableView.indexPathForCell(cell)
} | |
d10357 | If WriteMessage returns an error, then the application should close the connection. This releases resources used by the connection and causes the reader to return with an error.
It is not possible to send a closing handshake after WriteMessage returns an error. If WriteMessage returns an error, then all subsequent writes will also return an error. | |
d10358 | I asked for a quota increase and someone at google checked my account to find the problem.
Here is their reply.
I understand that you want to know what specific quota you are
reaching whenever you try to backup your Cloud SQL to Cloud Datastore.
Upon checking your project, it seems that the problem is that your App
Engine application is at or near its spending limit. As of this time
of writing, the Datastore Write Operations you have executed costed
you 1.10$, which will be refreshed after 5 hours. It can definitely
cause your resources to become unavailable until the daily spending
limit is replenished. Kindly try to increase your spending limit as
soon as possible to avoid service interruption and then run or execute
your datastore write operations.
Give this a shot and let me know what happens. I will be looking
forward to your reply.
This fixed the problem. I just needed to go into app engine and set a much higher daily spending limit.
Hopefully the code I included above will help others. | |
d10359 | The setPreLoader function doesn't do anything itself beside returning another anonymous function. Therefore, just calling setPreLoader(true) does nothing because the anonymous function is not called.
You have to call the result of setPreLoader(true) with appropriate function:
setPreLoader(true)(someFunction) | |
d10360 | Found my mistake, thanks to Artem Bilan. I assumed that :id would map to "id" among the column names in the SELECT's result set and not to getId() on the POJOs. My RowMapper was mapping the "id" into "requestId" in the POJO. That was the mistake. | |
d10361 | Easiest way:
^09[0-9]{7}$
Explanation:
^09 => begins by 09
[0-9] => any character between 0 and 9
{7} exactly seven times
$ => Ends with the latest group ([0-9]{7})
A: If you use matcher.contains() instead of matcher.find() it will match against the whole string instead of trying to find a matching substring. Or you can add ^ and $ anchors as suggested in other answer.
If you don't really need to use a regexp, perhaps it would be more readable to just use
string.startsWith("09") && string.length() == 9 | |
d10362 | Take a look to the DT doc
2.9 Escaping table content
You will see that you can put HTML content to your table and by using escape=Fmake it readable in HTML.
and you can do something like this on the varibles of your dataframe.
apply(yourMatrix,2,function(x) ifelse(x>value,
paste0('<span style="color:red">',x,'</span>'),
paste0('<span style="color:blue">',x,'</span>')
)
For example if you have a vector x <- c(1,2,3,4) and want value higher than 0 be red you will have
[1] "<span style=\"color:red\">1</span>"
[2] "<span style=\"color:red\">2</span>"
[3] "<span style=\"color:red\">3</span>"
[4] "<span style=\"color:red\">4</span>"
and then
datatable(yourMatrix, escape = FALSE) | |
d10363 | In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;
or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;
A: this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for details.
So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:
Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.
Would probably want to set up a python script and try it out, placing your own values into the variables. | |
d10364 | Answer 1 - Questions
You do not provide enough information to allow any one to give you pointers. Some initial questions:
*
*How many questionaires are you expecting: 10, 100, 1000?
*How many questions are there per questionaire?
*How are the questionaires reaching you? You say "email back". Does this mean as an attachment or as a table in the body of the email.
*You say the data is arriving as Excel files and you intend to do the analysis in Excel. Why are you storing the answers in Access? I am not saying you are wrong to store the results in Access; I just want to be convinced you have a reason.
*Have you designed the planned table structure for Access?
*Have you designed the structure of the Excel workbook(s) on which you will perform the analysis?
A: Answer 2
Firstly, I should say that I agree with Mat. I am not an expert on questionnaires but my understanding is that there are companies that will host online questionnaires and provide the results in a convenient form.
Most of the rest of this answer assumes it is too late to consider an online questionnaire or you have, for whatever reason, rejected that approach.
An Access project is, to a degree, self-documenting. You can look at its list of tables and see that Table 1 has columns A, B and C. If created properly you can see the relationships between tables. With an Excel workbook you just have a number of worksheets which can contain anything. There is no automatic documentation.
However, with both Excel and Access the author can create complete documentation that explains each table, worksheet, report and macro. If this project is going to last indefinitely and have a succession of project managers, such documentation will be essential. I can tell you from bitter experience that trying to understand a complex Access project or Excel workbook that you have inherited without proper documentation is at best difficult and at worst impossible.
Don’t even start this unless you plan to create and maintain proper documentation. I do not mean: “We will knock up something when we have finished.” Once it is finished, people will be moving onto their next projects and will have little time for boring stuff like documentation. After the event documentation also loses all the decisions and the reasons for those decisions. The next team is left wondering why their predecessors did it that way. The reason will not matter in many cases but I have seen a product destroyed by a new team removing “unnecessary complexity” they did not understand. I always kept a notebook in which I recorded what I was doing and why during the day. I encouraged my staff to do the same. I insisted something for the project log every week. The level of detail depends on the project. The question I asked myself was: “If I had just inherited this project, what happened during the last week that I would need to know?” This was in addition to an up-to-date specification for each component.
Sorry, I will get off my hobby-horse.
“In the short - medium term, we are expecting 50-100 replies. In the long term, it will be more as, people will be asked to send updates when their situation changes - these will have to be added as new entries with a new date attached to them.”
If you are going to keep a history of answers then Access will probably be a better repository than Excel. However, who is going to maintain the Access project and the central Excel workbooks? Access does not operate in the same way as Excel. Access VBA is not quite the same as Excel VBA. This will not matter if you are employing professionals experienced in both Access and Excel. But if you are employing amateurs who are picking up the necessary skills on the job then using both Access and Excel will increase what they have to learn and the likelihood that they will get confused.
If there are only 100 people/organisations submitting responses, you could merge responses and maintain one workbook per respondent to create something like:
Answers -->
Question 1May2014 20Jun2014 7Nov2014
Aaaaaa aa bb cc
Bbbbbb dd ee ff
I am not necessarily recommending an Excel approach but it will have benefits in some circumstances. Personally, unless I was using professional programmers, I would start with an Excel only solution until I knew why I needed Access.
“I envision the base table to have all the 80 variables in different columns, and the answers as rows (i.e. each new colum that comes with each excel file will need to be transposed and added as a new row).” I interpret this to mean a row will contain:
*
*Respondent identifier
*Date
*Answer to Q1
*Answer to Q2
*: :
*Answer to Q80.
My Access is very rusty. Is there a way of accessing attribute “Answer to Q(n)” or are you going to need 80 statements to move answers in and out? I hope there is no possibility of new questions. I found updating the database when a row changed a pain. I always favoured small rows such as:
*
*Respondent identifier
*Date
*Question number
*Answer
There are disadvantages to having lots of small rows but I always found the advantages outweighed them.
Hope this helps. | |
d10365 | The JmsTemplate reliably closes its resources after each operation (returning the session to the cache), including execute().
That comment is related to user code using sessions directly; the close operation is intercepted and used to return the session to the cache, instead of actually closing it. You MUST call close, otherwise the session will be orphaned.
Yes, the transaction will roll back (immediately) if its sessionTransacted is true.
You should NOT call commit - the template will do that when execute exits normally (if it is sessionTransacted). | |
d10366 | my guess is because its emulating. so either a. it needs flash installed in the emulator or b. it cannot access flash | |
d10367 | The renderer needs world matrix data for the raycasting to work. Make the following modification to the CombinedCamera code:
// Add to the .toPerspective() method:
this.matrixWorldInverse = this.cameraP.matrixWorldInverse; //
this.matrixWorld = this.cameraP.matrixWorld; //
// and to the .toOrthographic() method add:
this.matrixWorldInverse = this.cameraO.matrixWorldInverse; //
this.matrixWorld = this.cameraO.matrixWorld; //
r73. | |
d10368 | Looks like an issue with how the shapefile has been put together - polygons in LSOA_2011_London_gen_MHW.shp not sharing boundaries completely.
Using the snap argument in poly2nb will force the function to treat boundaries within a certain defined distance to be contiguous, e.g:
w <- poly2nb(ldn_sp, snap=10)
In above example, 10 = decimal degrees as your original data are in WGS84 - might want to convert to BNG and set a reasonable small distance in metres to snap. You'll need to experiment at bit, but 10 decimal degrees in the quick and dirty example above seems to generate something approximating an expected neighbours list. | |
d10369 | I'm still looking for a more elegant answer but with the help of a developer I was able to create an external folder on our Apache server to store the images and link to them. Then I added parameters to our Jenkins server to alter the security policy and restarted. The screenshots are now showing up. | |
d10370 | I haven't used Bucket Map Join in production, so just some inference based on bucket map join's principle.
In Bucket Join, correlated buckets from both tables are join together, using small table's bucket to build hashtable, and iterate the large table's bucket file one by one in original order, probe the hash table in memory and generate join results.
So, I think small table's each bucket should be small enough to put in memory (map slot's heap size you set in mapred-site.xml). the bigger the small table is, the more buckets you should set for it.
I think big table's bucket number can be arbitrary number, just multiple of small table's bucket number. | |
d10371 | When using var to declare variables, the variable can take on either function or global scope. If var is used within a function, it has function scope, if var is used outside of any function, the variable has Global scope.
So, your statement of:
But I also learnt that var has a global scope. Then var show not allow
variable redeclaration.
Is actually, not really accurate because it depends on where var is used and redeclaration (more correctly known as variable "hiding") is possible in any smaller scope than the first declaration was made.
When declaring with var, the declaration is hoisted to the top of the scope.
I've written another answer that describes and demonstrates this in detail.
A: In JavaScript, function declarations are hoisted before var declarations, and assignments are not hoisted.
So the sample code from the question:
var DEFAULT_RATE=0.01;
var rate=0.04;
function getRate() {
if(!rate) {
var rate=DEFAULT_RATE;
}
return rate;
}
has this effective ordering:
// hoisted function
function getRate() {
var rate = undefined; // <- hoisted local variable
if(!rate) { // <- always true
rate = DEFAULT_RATE; // <- always executed
}
return rate; // <- always returns DEFAULT_RATE (0.01)
}
// hoisted vars
var DEFAULT_RATE;
var rate;
// not-hoisted assignments
DEFAULT_RATE = 0.01;
rate = 0.04;
// not-hoisted function call
console.log(`Rate is`,getRate());
Since getRate() contains var rate, the function-scoped rate is hoisted to the beginning of getRate(), with a value of undefined.
Therefore if(!rate) evaluates to if(!undefined), which is always true, and getRate() always returns DEFAULT_RATE (0.01). | |
d10372 | The azurerm_sql_failover_group resource is deprecated in version 3.0 of the AzureRM provider and will be removed in version 4.0. Please use the azurerm_mssql_failover_group resource instead.
*
*Here is the Sample code of SQL Fail over group using Terraform.
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_sql_server" "primary" {
name = "sql-primary"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
version = "12.0"
administrator_login = "sqladmin"
administrator_login_password = "pa$$w0rd"
}
resource "azurerm_sql_server" "secondary" {
name = "sql-secondary"
resource_group_name = azurerm_resource_group.example.name
location = "northeurope"
version = "12.0"
administrator_login = "sqladmin"
administrator_login_password = "pa$$w0rd"
}
resource "azurerm_sql_database" "db1" {
name = "db1"
resource_group_name = azurerm_sql_server.primary.resource_group_name
location = azurerm_sql_server.primary.location
server_name = azurerm_sql_server.primary.name
}
resource "azurerm_sql_failover_group" "example" {
name = "example-failover-group"
resource_group_name = azurerm_sql_server.primary.resource_group_name
server_name = azurerm_sql_server.primary.name
databases = [azurerm_sql_database.db1.id]
partner_servers {
id = azurerm_sql_server.secondary.id
}
read_write_endpoint_failover_policy {
mode = "Automatic"
grace_minutes = 60
}
}
*
*You can go through this reference for complete information. | |
d10373 | You can attach to a running Excel instance via GetObject:
Set xl = GetObject(, "Excel.Application")
If you have several instances launched, that will only get you the first one, though. You'd have to terminate the first instance to get to the second one.
With that said, a better approach would be to have Excel open the URL directly:
Set xl = CreateObject("Excel.Application")
For Each a In IE.Document.GetElementsByTagName("a")
If InStr(a.href, LinkHref) > 0 Then
Set wb = xl.Workbooks.Open(a.href)
Exit For
End If
Next | |
d10374 | The only ways to pass data directly from a web page to your app is on the URL that you register in an intent-filter. All to be retrieved via the Uri object - whether the data is on the path or with query params, as outlined below. There is no way to set extras on an Intent from a web page.
Uri uri = getIntent().getData();
String param1Value = uri.getQueryParameter("param1");
A: This is how I overcome this issue,
I developed my own browser and made browsable like you do
Uri data = getIntent().getData();
if(data == null) { // Opened with app icon click (without link redirect)
Toast.makeText(this, "data is null", Toast.LENGTH_LONG).show();
}
else { // Opened when a link clicked (with browsable)
Toast.makeText(this, "data is not null", Toast.LENGTH_LONG).show();
String scheme = data.getScheme(); // "http"
String host = data.getHost(); // "twitter.com"
String link = getActualUrl(host);
webView.loadUrl(link);
Toast.makeText(this,"scheme is : "+scheme+" and host is : "+host+ " ",Toast.LENGTH_LONG).show();
}
I think you are looking for this functions
data.getQueryParameter(String key);
A: One could use "intent scheme URL" in order to send more information like extra objects and actions when redirecting to a custom intent scheme URL via javascript or HTML.
intent://foobar/#Intent;action=myaction1;type=text/plain;S.xyz=123;end
Although this method doesn't actually answer the question as the scheme part is destined to always be "intent", this is a possible way to send intents from browsers with extra object or actions.
See more extensive information in the following report:
http://www.mbsd.jp/Whitepaper/IntentScheme.pdf
Or use the chrome documentation:
https://developer.chrome.com/multidevice/android/intents | |
d10375 | I just learned from https://blog.expo.dev/building-a-code-editor-with-monaco-f84b3a06deaf that to set the theme you call monaco.editor.setTheme('<theme-name>'). I was incorrectly calling setTheme on my editor instance. | |
d10376 | Yes, the issue can be easily solved by applying the following refactoring:
// singleton used by multiple threads
class A {
public void method() {
Set<String> codeSet = SomeRepo.someMethod(session.getUser()); // Heavy repo call.
new AProcessor(codeSet).method();
}
}
// not a singleton, only one thread uses an instance of this class
class AProcessor {
private final Set<String> codeSet;
AProcessor(Set<String> codeSet) {
this.codeSet = codeSet;
}
public void method() {
method1();
method2();
....
methodn();
}
private methodn() {
codeSet.iterator().next();
}
} | |
d10377 | You can use the parts accessor like this. The first element is what you call the duration_type and the last one the integer value:
2.day.parts
=> [:days, 2] | |
d10378 | While VBA can create and modify ribbons (and even add images) it can't change the overall color of the ribbon as seen when the ribbon is not selected.
To change the ribbon color, you need a COM add-in. COM add-ins are different than regular add-ins. Instead of using VBA (which at first glance looks like Visual Basic and is similar to an outdated version of VB), COM add-ins utilize modern Visual Basic or Visual C++.
How to write a COM add-in for Excel is beyond the scope of the question but here are some resources to get you started from Microsoft and Chuck Pearson:
About Excel COM Add-ins
Creating a COM Add-in
Customizing Ribbon Colors | |
d10379 | use Double.Parse() - http://msdn.microsoft.com/en-us/library/system.double.parse.aspx to format the value when you read it in. This will allow you to use double and you can then apply the appropriate formatting for output.
Updated:
The issue you seem to be having that when reading from file the value is null and when reading from database it is DBNull. By default DataTable allows for DBNull values. If you want to mimic this for read, try the following
DataTable r = new DataTable();
try
{
r.Columns.Add("ID");
r.Columns.Add("EmployerName");
r.Columns.Add("FlatMinAmount");
r.Columns.Add("DistrictRate");
r.Columns.Add("VendorRate");
r.Columns.Add("Description");
r.Columns.Add("EmployeeCount");
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader(filename))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
//foreach (string s in row)
{
double d;
double? val2 = null;
double? val3 = null;
double? val4 = null;
if (Double.TryParse(row[2], out d)) val2 = d;
if (Double.TryParse(row[3], out d)) val3 = d;
if (Double.TryParse(row[4], out d)) val4 = d;
r.Rows.Add(row[0], row[1], val2, val3, val4, row[5], row[6]);
}
}
}
A: Use the TargetNullValue attribute:
<dg:DataGridTextColumn Binding=""{Binding FlatMinAmount,TargetNullValue='Not Specified',StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>
A: If you know the number is null, can't you just set the value of the column to DBNull?
row["FlatMinAmount"] = DBNull.Value;
Here's a little console app I ran to show this working:
class Program
{
static void Main(string[] args) {
DataTable tbl = new DataTable();
DataColumn col = new DataColumn("Blah", typeof(double));
tbl.Columns.Add(col);
DataRow row = tbl.NewRow();
row["Blah"] = DBNull.Value;
Console.WriteLine("Result: " + row["Blah"].ToString());
Console.ReadKey();
}
} | |
d10380 | Well the error actually followed one of the workbooks. I'm still puzzled with where in the workbook path and file name it's giving me the issue, but the code itself is now working. | |
d10381 | There are probably hundreds of ways to do this, but this is what I would do:
*
*They should never have a direct download path as it can be abused.
*All files could be stored in the same place.
*File names should be changed to unique ids to avoid dupilcates.
*Store the file name, unique id, and user id in a database.
*When they visit the page for the unique id, you can do your checks and display the file info.
*You will then pass the file to them rather than having them download it directly.
*Their user page would show file names and links to those pages, etc.
I hope that is a good jumping off point.
A: At its simplest: Store files somewhere in any hierarchy you want in a location that's not simply publicly accessible through the web server. Store meta information about each file in a database. In said database, store who the owner of the file is. Write a script that allows people to download those files (see readfile), require that users are logged in and that only owners of files can them. | |
d10382 | Looks like, you've got this solution from this page, yeah? Unfortunately, it's not the actual documentation, but only API suggestion, for further implementation. Just promises and nothing more at the moment=\ | |
d10383 | You need to set lineWidth property to 0:
let plotOptions = HIPlotOptions()
plotOptions.waterfall = HIWaterfall()
plotOptions.waterfall.lineWidth = 0
options.plotOptions = plotOptions
API Reference: https://api.highcharts.com/ios/highcharts/ | |
d10384 | Constructors are not inherited. Superclass constructor 'exists' in a way that you could call it from a subclass unless it's marked as private.
And as I.K. has mentioned class could have a default constructor:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared. | |
d10385 | change this echo get_avatar( get_the_author_email(), '32' ); to echo get_avatar( $autid, '32' );
get_the_author_email() returns email of the author in the current loop of wordpress and not from your foreach loop. | |
d10386 | You don't actually declare a specific route in DefaultRouter. The router takes care of creating all sub urls for you. Just doing router.register(r'portal', PortalViewSet) will give you:
*
*[.format]
*{prefix}/[.format]
*{prefix}/{methodname}/[.format] - @list_route decorated method
*{prefix}/{lookup}/[.format]
*{prefix}/{lookup}/{methodname}/[.format] - @detail_route decorated method
So unless you want to create a custom router, you're gonna have to change your url pattern to something like /portal/{pk}/portalProject/?id={pk}
Also, if you're requesting the portalProject by pk anyway, then there is no need for nesting the url under /portal/{pk}. The pk of portalProject is already specific enough. You already have a route for portalProject, so you would effectively be getting two ways of accessing the same data, one of them being more complicated for no good reason.
However, I believe this is what you're looking for:
https://github.com/alanjds/drf-nested-routers
or https://chibisov.github.io/drf-extensions/docs/#nested-routes | |
d10387 | Another easy method in Netbeans is also avaiable here,
There are libraries inside Netbeans itself,where the solutions for this type of situations are available.Select the relevant one as well.It is much easier.After doing the prescribed steps in the link,please restart Netbeans.
Step1:- Select Tools->Palette->Swing/AWT Components
Step2:- Click 'Add from JAR'in Palette Manager
Step3:- Browse to [NETBEANS HOME]\ide\modules\ext and select swingx-0.9.5.jar
Step4:- This will bring up a list of all the components available for the palette. Lots of goodies here! Select JXDatePicker.
Step5:- Select Swing Controls & click finish
Step6:- Restart NetBeans IDE and see the magic :)
A: I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;
public class DatePickerExample extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("JXPicker Example");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400, 400, 250, 100);
JXDatePicker picker = new JXDatePicker();
picker.setDate(Calendar.getInstance().getTime());
picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));
panel.add(picker);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
A: I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
String s = "";
if (dayNo >= 1 && dayNo <= maxDayNo) {
s = String.valueOf(dayNo);
}
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
A: The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.
Fair disclosure: I'm the primary developer.
Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.
The most commonly used date formats are automatically supported, and additional date formats can be added if desired.
To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.
Besides the DatePicker, the library also has the TimePicker and DateTimePicker components.
I pasted screenshots of all the components (and the demo program) below.
The library can be installed into your Java project from the project release page.
The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .
A: *
*Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
*Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
*Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
*Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog. | |
d10388 | Your code works fine in Windows environment it seems.
In case you are running on Linux environment, but I am not quite sure whether system("PAUSE");works over there or not. Even, this seems to me as non - portable code.
I would recommend you to use cin.get() or getchar() instead, to make it portable. If you want to more why I am saying so, you can go through this link: http://www.gidnetwork.com/b-61.html
A: The source code you posted compiles just fine with both Microsoft Visual C++ 2015 and gcc (tried on ideone.com).
The only way to get the C2447 compile error you are getting, with Visual C++, is to add a semi-colon (;) right after main():
int main();
{
(but Visual Studio 2015 editor highlights the error, even before compiling the code). | |
d10389 | Yep, that workflow would work, or stash them - and don't forget if you do make a clone of the heroku repo you'll have made changes to a different clone of the repo and you'll need to make those changes in your original local repo.
In future I'd suggest that you assume that your 'master' branch is what's live on Heroku and branch of that to work in - you can even push this branch into a new app for testing purposes. This way bug fixes can be performed on your local master branch (or another branch and merged into master) and pushed to heroku and then when you've finished your new work you merge the branch back into master and deploy that to your live environment. I wrote a blog article on the subject a while back, here
A: I haven't used heroku but if I wanted to make changes to a deployed application while I had unsaved changes in my sandbox, I would do one of the following.
*
*stash my local changes, cut a branch from the point where I want to make a fix, make it, deploy it, switch back to my original branch and pop from the stash.
*Commit my unsaved changes (into the current branch - say work), cut a branch from the point where I want to make a fix, make my fix, deploy it, switch back to work, reset my HEAD to before my "temporary" commit and resume work.
Unless you're using git in an unconventional fashion, there's no need to make another clone.
A: If you clone the heroku repository to a separate directory, made changes and push it from there, then there is a possibility of conflicts later down the road.
If its only the issue with the uncommitted changes then certainly you can stash them using "git stash" and later retrieve it using "git stash pop".
A: My work-cycle: I always keep a master branch with the #1 rule "always push to Heroku after committing something to master". If I code on something that I do not want to deploy immediately, I have to branch.
I know this works not for all use cases, but having always a branch that is identical to the app that is productive on Heroku makes me sleep better ;) | |
d10390 | Assuming you return valid JSON from your (?) web service, you can use JSONKit to convert from and to JSON.
PHP has json_encode and json_decode for this purpose. See here. | |
d10391 | I think your code needs restructuring. You need to check if the seat is empty before doing anything else. Also "main" is entry point of program in C, it is better not to use it for other purposes.
As described in the comments, instead of using if-else statement for assignment it is better to use the following:
seat[p.seatrow - 1][p.seatcol - 'A'] = ...
Considering all of these, the following code will do the job you want.
First, it asks about user input, then it checks if it is in valid range of inputs. After that, it checks if the seat is already taken or not.
If the seat was empty it reserves it and quits the function. If any of the above steps fails, it asks for user input again.
The code:
#include <stdio.h>
#include <stdbool.h>
#define ROWS 11
#define COLS 8
#define PASSENGERSIZE sizeof(passenger)
typedef struct{
char city[20], name[50], seatcol;
int age, seatrow, id;
}passenger;
char seat[ROWS][COLS]={0};
int selection;
int seatavailable=60;
int i,j,x,k;
char answer, Y ;
int status=0;
void chooseseat(){
passenger p;
// Read the user input until it reserves a seat or request quitting.
while (true){
// Read user input.
printf("\nEnter your seat number: (EX: 1A)");
scanf(" %d%c",&p.seatrow, &p.seatcol);
// Check if the seat requested is valid entry.
if (p.seatrow > 0 && p.seatrow <= ROWS &&
p.seatcol >= 'A' && p.seatcol <= 'A' + COLS){
// Input range is valid, check if seat is already taken.
if (seat[p.seatrow - 1][p.seatcol - 'A'] != 'X'){
// Seat is available, reserve it and break the loop.
seat[p.seatrow - 1][p.seatcol - 'A'] = 'X';
printf("Congratulations. Your seat number is %d%c\n",p.seatrow,p.seatcol);
break;
}
else{
// Seat is already taken.
printf("Seat is already taken\n.");
}
}
else{
// Input range is invalid.
printf("Invalid seat row/col,\n");
}
// Ask user if he wants to continue.
printf("\nChoose another seat? (Y/N)");
scanf(" %c", &answer);
if (answer != 'Y'){
printf("Your data will be not saved and will be returned to main menu.\n");
break;
}
}
}
int main() {
chooseseat();
return 0;
} | |
d10392 | You need to define the association for Post also as you are querying upon Post model
Post.associate = function(models) {
Post.belongsTo((models.Author);
};
You need to add an association from both ends, Post -> Author and Author -> Post , this way you will never stuck in this kind of error.
A: Summarizing this documentation we have the following:
If you have these models:
const User = sequelize.define('user', { name: DataTypes.STRING });
const Task = sequelize.define('task', { name: DataTypes.STRING });
And they are associated like this:
User.hasMany(Task);
Task.belongsTo(User);
You can fetch them with its associated elements in these ways:
const tasks = await Task.findAll({ include: User });
Output:
[{
"name": "A Task",
"id": 1,
"userId": 1,
"user": {
"name": "John Doe",
"id": 1
}
}]
And
const users = await User.findAll({ include: Task });
Output:
[{
"name": "John Doe",
"id": 1,
"tasks": [{
"name": "A Task",
"id": 1,
"userId": 1
}]
}] | |
d10393 | From a logical point of view, there is no way that AudioManager would use Bluetooth and thus need android.permission.BLUETOOTH.
From a source code point of view, setMode() needs only android.permission.MODIFY_AUDIO_SETTINGS:
*
*AudioManager:1425
public void setMode(int mode) {
IAudioService service = getService();
try {
service.setMode(mode, mICallBack);
} catch (RemoteException e) {
Log.e(TAG, "Dead object in setMode", e);
}
}
*AudioService:703
public void setMode(int mode, IBinder cb) {
if (!checkAudioSettingsPermission("setMode()")) {
return;
}
*AudioService:1250
boolean checkAudioSettingsPermission(String method) {
if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
== PackageManager.PERMISSION_GRANTED) {
return true;
}
String msg = "Audio Settings Permission Denial: " + method + " from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid();
Log.w(TAG, msg);
return false;
} | |
d10394 | A website usually consists of two major portions, the server side logic (back-end) and the client side logic (front-end). Both logics usually execute separately from each other, and therefore can only communicate via network channels, and not via logic. This means they do not share variables or data as conventional program logic does.
From the code you have shared, it appears that you are attempting to execute client side logic on your server side application. The document object in JavaScript is used to access and manipulate the DOM within an HTML page. The server side application does not have access to this document object, and therefore its access is invalid. In the server side application's context, document object is undefined.
You can make this work by calling these functions via client side logic. Try registering a function call for upload and start functions against a button click. That will most likely work.
A: NodeJS has a module called files system module. file system module has different methods that can be used to server nodejs static pages. it has:
const readStream = createReadStream('./staticfile/index.html');
res.writeHeader(200, {"content-type"}:"text/html");
readStream.pipe(res)
this sends the html file in chucks of data.
refer here: https://nodejs.org/api/fs.html | |
d10395 | In JavaScript you would of course call .flat(Infinity), which would return the completely flattened array. But I'll assume these constraints:
*
*No use of array methods besides push and pop (as you target a custom, simpler language)
*No use of recursion
*No use of a generator or iterator
I hope the use of a stack is acceptable. I would then think of a stack where each stacked element consists of an array reference and an index in that array. But to avoid "complex" stack elements, we can also use two stacks: one for array references, another for the indices in those arrays.
To implement "iteration", I will use a callback system, so that you can specify what should happen in each iteration. The callback can be console.log, so that the iterated value is just output.
Here is an implementation:
function iterate(arr, callback) {
let arrayStack = [];
let indexStack = [];
let i = 0;
while (true) {
if (i >= arr.length || arr[i] === null) {
if (arrayStack.length == 0) return; // all done
arr = arrayStack.pop();
i = indexStack.pop();
} else if (Array.isArray(arr[i])) {
arrayStack.push(arr);
indexStack.push(i + 1);
arr = arr[i];
i = 0;
} else {
callback(arr[i]);
i++;
}
}
}
let arr = [1, 2, 3, [4, 5]];
iterate(arr, console.log); | |
d10396 | You can try with this (conditional aggregation)
select
max(case when role = 'Primary Contact' then email else null end) as PrimaryContact,
max(case when role = 'Secondary Contact' then email else null end) as SecondaryContact,
max(case when role = 'End User' then email else null end) as EndUser,
userId
from contact_details
group by userId | |
d10397 | Add a property for your children, like this:
public ICollection<Person> { get; set; }
Then configure the mapping like this:
HasMany(p => p.Children).WithOptional(p => p.Parent);
Then you simply have to access the Children property using lazy loading, eager loading (Include(p => p.Children) or explicit loading.
If you don't have the navigation property is still possible to do it, but less obvious.
MyContext.Person.Where(p => p.ParentId = parentId); | |
d10398 | If you want your label to display multiple lines you need to specify that in its numberOfLines property:
This property controls the maximum number of lines to use in order to fit the label’s text into its bounding rectangle. The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.
You could set it either in code or in Attributes inspector in the storyoard:
Also make sure that the constraints of the label allows it to expand accordingly to its content. | |
d10399 | Install cocoapods pod 'AWSS3'.
Here filePath is the path of the file to be uploaded.
func saveModelInAmazonS3() {
let remoteName = fileName + ".mov" //extension of your file name
let S3BucketName = "bucketName"
let uploadRequest = AWSS3TransferManagerUploadRequest()!
uploadRequest.body = filePath!
uploadRequest.key = remoteName
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "application/zip"
uploadRequest.acl = .publicRead
uploadRequest.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
DispatchQueue.main.async(execute: { // here you can track your progress
let amountUploaded = totalBytesSent
let fileSize = totalBytesExpectedToSend
print("\(amountUploaded)/\(fileSize)")
let progress = (CGFloat(amountUploaded) / CGFloat(fileSize)))
})
}
let transferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest).continueWith(block: { (task: AWSTask) -> Any? in
if let error = task.error {
self.delegate.errorInUpload(uploadState: self.uploadState)
print("Upload failed with error: (\(error.localizedDescription))")
}
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
print("Uploaded to:\(String(describing: url))")
}
return nil
})
} | |
d10400 | Create a new class add this class to the modelinputs
.form-control-login {
width: 100% !important;
}
A: add below css
#loginModal .form-inline .form-control,
#registerModal .form-inline .form-control {
width: 100%!important;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.