_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d15801 | val | You will need the development header files. The package is probably named libgstreamer-plugins-base1.0-dev or close to that.
A: You need the include (headers) and link (libs) directories for gstreamer-app-1.0, part of the gstreamer base-plugins.
If you are using pkg-config, try the following command to get all the compilation flags you need:
pkg-config --cflags --libs gstreamer-app-1.0
In case of CMake with pkg-config:
# pkg-config
find_package(PkgConfig)
pkg_check_modules(GSTREAMER REQUIRED gstreamer-1.0)
pkg_check_modules(GSTREAMER_APP REQUIRED gstreamer-app-1.0)
# including header files directories
include_directories(
${GSTREAMER_INCLUDE_DIRS}
${GSTREAMER_APP_INCLUDE_DIRS}
)
# linking library directories
link_directories(
${GSTREAMER_LIBRARY_DIRS}
${GSTREAMER_APP_LIBRARY_DIRS}
)
# linking gstreamer library with target executable
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${GSTREAMER_APP_LIBRARIES}) | unknown | |
d15802 | val | You could use something like this to loop from row 1 to the specified row:
For Each C In ActiveSheet.Range("B1:B" & GetLine).Cells | unknown | |
d15803 | val | You have to determine where the tool is dropped: How do I get the coordinate position after using jQuery drag and drop?
You also have to determine where your toolbox is placed: http://api.jquery.com/position/
Then you have to determine the width and height of your toolbox: http://api.jquery.com/width/
After that calculate the rectangle of your toolbox and check if the tool is placed there. If it is placed there then deny dropping, if not allow dropping. | unknown | |
d15804 | val | I was using the STLLoader from react three fiber and it turnes out you can give the URL from firebase storage directly to this loader. | unknown | |
d15805 | val | I agree: it is a flawed example. The code itself exhibits defined behavior.
The comment before the final assignment, *ncpi = 0;, disagrees with the code. Probably the author intended to do something different.
My first response was as if the code overwrote a const: I have revised my answer.
A: It's undefined because it might be stored in read only memory for example. This won't be the case on x86 systems, but here we have a whole slew of other problems, like aliasing issues if you enable heavy optimizations.
Either way, even just intuitively, why would you think modifying a const through a pointer to it that the compiler can't statically validate would be safe? | unknown | |
d15806 | val | There is no direct way, however two ideas came to my mind.
First:
private boolean isApplicationClosed() {
return solo.getCurrentViews().size() == 0;
}
Second (this may affect your application):
private boolean isApplicationClosed() {
try {
solo.clickOnScreen(100, 100);
} catch (AssertionFailedError e) {
if("Click can not be completed!".equals(e.getMessage().trim()) {
return true;
}
}
return false;
} | unknown | |
d15807 | val | Jacob
You need add a group by clause like this
select t.id, t.tilte, t.author, t.content, count(com.id) as comments
from tutorials as t
join tutotials_categories as cat
on t.category = cat.id
join tutorials_comments as com
on com.tutorial_id = t.id
where cat.title like'%category title'
and t.status = 1
group by com.id
order by t.id asc
I used the ansi join form
A: This should clean up your query:
SELECT t.id, t.title, t.author, t.content, c.ctitle, c.cid, com.comments
FROM tutorials AS t
LEFT JOIN (
SELECT tutorial_id, COUNT(com.id) as comments
FROM tutorial_comments AS com
GROUP BY 1
) AS com ON com.tutorial_id = t.category
LEFT JOIN (
SELECT tc.id as cid, tc.title as ctitle
FROM tutorial_categories AS tc
WHERE title LIKE '%category title'
) AS c ON t.category = c.cid
WHERE t.status = '1'
ORDER BY t.id
The LEFT JOIN prevents that tutorials disappear that don't find a match.
I made that explicit JOINs with JOIN conditions, that is easier to understand and also the proper way.
Your cardinal problem was that you had the join condition for the counted comments inside the brackets instead of outside, which cannot work that way.
A: Can you try this one:
SELECT t.`id`, t.`title`, t.`author`, t.`content`, c.title, c.cid, ct.comments
FROM `tutorials` AS `t`
LEFT OUTER JOIN (
SELECT tc.`id` as `cid`, tc.`title` as `ctitle`
FROM `tutorial_categories` AS `tc`
WHERE `title` LIKE '%category title'
) AS `c` ON t.`category` = c.`cid`
LEFT OUTER JOIN (
SELECT COUNT(com.`id`) as `comments`
FROM `tutorial_comments` AS `com`
group by com.`id`
) as `ct` on ct.`tutorial_id` = c.cid
WHERE t.`status` = '1'
ORDER BY `id` ASC | unknown | |
d15808 | val | This launch error means that something went wrong when your first kernel was launched or maybe even something before that. To work your way out of this, try checking the output of all CUDA runtime calls for errors. Also, do a cudaThreadSync followed by error check after all kernel calls. This should help you find the first place where the error occurs.
If it is indeed a launch failure, you will need to investigate the execution configuration and the code of the kernel to find the cause of your error.
Finally, note that it is highly unlikely that your action of adding in a cudaThreadSynchronize caused this error. I say this because the way you have worded the query points to the cudaThreadSynchronize as the culprit. All this call did was to catch your existing error earlier. | unknown | |
d15809 | val | Use cron job for this and send mails in chunks instead of sending all mails in one time.
A: Please see the php mail function documentation:
It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.
Also, see the related questions on serverfault: https://serverfault.com/questions/67154/sending-an-email-to-about-10k-users-not-spam, where PHPlist is mentioned, along with others. And here - https://serverfault.com/questions/68357/whats-the-best-way-to-send-bulk-email,https://stackoverflow.com/questions/1543153/is-there-a-limit-when-using-php-mail-function
A: I think there is no problem with your script but its rather an installation issue with your operating system or sending mail program is poorly configured or perhaps missing. Try all possibilities, from php side its okay.
A: Your best option is to use a cron job. Doing it like this, your server will have a lot of stress. The mail() function isn't meant for a large volume of emails. It will slow done your server if your using a large amount.
This will explain how to make a cron job on your server.
Hope it helps! | unknown | |
d15810 | val | I was receiving an error that the imgbubbles method does not exist. This means the resource wasn't being loaded into the fiddle. The solution was simple.
Rather than trying to load the file into your page from the dynamicdrive domain, copy it to your project folder and load it from there. In your fiddle, I pulled the actual source for the plugin into the JavaScript panel, which resolved the issue of the missing method.
Demo: http://jsfiddle.net/hbMzV/13/ (Tested in IE 7 to 10)
A: JSLint says to throw in some semi-colons, like so:
jQuery(document).ready(function($){
$('ul#orbs').imgbubbles({factor:3.15, speed:1500});
});
Looks like it works even without them though. | unknown | |
d15811 | val | There are very simple LINQ methods to accomplish sorting by the property of an object. One is OrderBy:
var sortedEnumerable = unsortedEnumerable.OrderBy(a => a.property);
Likewise, you can use OrderByDescending to ascertain the reverse order of the above:
var sortedEnumerable = unsortedEnumerable.OrderByDescending(a => a.property);
Note that these return a new enumerable and do not sort in place.
If you needed more complex sorting logic, or if you wanted to sort the kluczyk object itself and not any given property, you'd want to create your own object that implements IComparer and establishes less-than/equal/greater relationships between your objects.
Brad Christie included a link to List(T).Sort (IComparer<T>), which I've reproduced here unless he wants to make his own answer. | unknown | |
d15812 | val | You have to use chrome.runtime.onMessage.addListener instead of chrome.runtime.onMessageExternal.addListener to receive messages from your own content scripts.
chrome.runtime.onMessageExternal is for messages from other extensions/apps. | unknown | |
d15813 | val | Your code seems to be right. To get the UIViews on the header of each section, you can return any object that inherits from a UIView(this doesn't mean that would be nice to). So, you can return a small container with a UIImageView and a UILabel, if you want this for example.
Your code for the viewHeader would be something like this:
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
// instantiate the view to be returned and placed correctly
let commonLabel = UILabel(frame: CGRectMake(0, 0, tableWidth, 30))
commonLabel.textColor = .blackColor()
commonLabel.textAlignment = .Center
// ... other settings in the properties
if section == 0 {
commonLabel.text = "section1"
// other settings for the first section
}
if section == 1 {
commonLabel.text = "section2"
// other settings ...
}
return commonLabel
}
Notes:
Be sure to set the container view's frame,for sectionHeaders the top view in the hierarchy don't accept auto layout.
Implementing the viewForHeaderInSection method is more accessible to custom UI's, you can use the TitleForHeaderInSection if you wish, but it's limited for more complex stuffs.
EDIT:
If you're using storyboards, you still can use this code, although it's not so elegant in terms of apps that use IB for the UI. For this, you might take a look at this link: How to Implement Custom Table View Section Headers and Footers with Storyboard
. This implements only the view using storyboards, but the delegate part must to be wrote. | unknown | |
d15814 | val | Please see the following .NET Fiddle here.
Imports System
Imports System.Globalization
Public Module Module1
Public Sub Main()
Dim provider AS CultureInfo = New CultureInfo("en-US")
Dim dt AS DateTime = Convert.ToDatetime("5/2/2013 5:15:03 PM")
Console.WriteLine(dt)
Console.WriteLine(dt.ToString("d",provider))
End Sub
End Module
Output: | unknown | |
d15815 | val | Put your property files where Application/Library resources belong, i.e. in src/main/resources:
src/main/resources/mypackage/MyProperties.properties
And it will get copied properly.
A: Pascal's answer is the correct maven way of doing things.
But some developers like to keep resources next to their sources (it's standard procedure in wicket, for example).
If you're going to do that, you will have to add your source folder to the resources:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
</build> | unknown | |
d15816 | val | You can make a good use of preg_match function:
$str = '<p style="text-align:center">
<a href="#" target="_blank"><span style="color:green">Text Link</span></a>
</p>';
if(preg_match('/^(\<p.*?\>).*(\<a.*?\>).*(\<span.*?\>)([0-9a-zA-Z ]*).*$/is', $str, $regs))
{
// $regs = [
// 0 => ... (original string)
// 1 => '<p style="text-align:center">',
// 2 => '<a href="#" target="_blank">',
// 3 => '<span style="color:green">',
// 4 => 'Text Link']
$newStr = $regs[1].$regs[3].$regs[2].$regs[4].'</a></span></p>';
}
You may have to change the [0-9a-zA-Z ]* in regular expression to match your links format.
If input HTML is multiple line text then you have to use s modifier after the regular exception, I also used i as case insensitive just to be sure noone mixed <P> and <p> tag together and so on...
Note that this if fairly specific solution and for more general solution you should use something like loading HTML into DOM and working with nodes, but this is pretty simple and quick solution for this particular case. | unknown | |
d15817 | val | You can check an example in form VendTable > Design > MainTab > TabPageDetails > Tab > TabGeneral > HideShowGroup.
It contains two elements: a combobox (HideShowComboBox) and a button (HideShowButton).
By default, the button has following properties:
*
*AutoDeclaration = Yes
*Text = Show more fields
*HelpText = Show/hide fields.
*SaveRecord = No
*Border = None
*BackgroundColor = Dyn Background white
*ImageLocation = EmbeddedResource
*NormalImage = 7886
*ButtonDisplay = Text & Image left
The button also has method clicked responsible for hiding/showing the fields that need to be hidden/displayed and for changing its own look (Text, HelpText, NormalImage = 7882, etc.)
Please note that this logic is managed in class DirPartyFormHandler - you can set breakpoints there and debug the process to understand this functionality better. | unknown | |
d15818 | val | Yes, document tabs have parameters required which can be set to true or false.
They also have the parameter readOnly which can also be set to true or false
The API reference has all the parameters in it | unknown | |
d15819 | val | First of all ,a Factory should return a one dimension Object array.
And that factory method should return instances of the test class that you are trying to execute.
So the factory will run your tests, if you change to this
public class MyFactory {
@Factory
public Object[] dp() {
Object[] data = new Object[] {
new MyTest("1", "TestCase1", "Sample test 1"), new Mytest("1", "TestCase1", "Sample test 1"), new MyTest("1", "TestCase1", "Sample test 1")
};
return data;
}
}
A: As per this error : either make it static or add a no-args constructor to your class,
Your MyTest class need to have public no-args contructor, Java will not add the default constructor as you already have parametrized constructor, i.e public MyTest(String num, String name, String desc)
UPDATE
change your factory class
public class MyFactory {
@DataProvider(name = "MyData")
public static Object[][] dp(ITestContext context, Method m) throws Exception {
return new Object[][] { new Object[] { "1", "TestCase1", "Sample test 1" }};
}
@Factory(dataProvider = "MyData")
public Object[] createInstances(String num, String name, String desc) {
return new Object[] { new MyTest(num, name, desc) };
}
}
A: //Factory class supplying data to test
public class DataFactory {
@Factory
public Object[] DataSupplier(){
Object[] testData = new Object[3];
testData[0] = new FactoryTest(1);
testData[1] = new FactoryTest(2);
testData[2] = new FactoryTest(3);
return testData;
}
}
//Test class
public class FactoryTest {
int i;
public FactoryTest(int i) {
this.i = i;
}
@Test
public void f() {
System.out.println(i);
}
}
Testng.xml
<suite name="Suite">
<test name="Test">
<classes>
<class name="factorydata.DataFactory"/>
</classes>
</test> <!-- Test -->
</suite>
Datafactory class supplies the test data by creating instances of the test class and passing parameters to FactoryTest class constructor.
FactoryTest class consumes the data from the datafactory.
In the testng.xml refer the class which has factory , in this case it is DataFactory.
This explains a simple working TestNg Factory annotation usage. | unknown | |
d15820 | val | The best approach for C# projects is to install the WebDriver NuGet, because if there are any updates it will be notified. Just install NuGet Manager and search for WebDriver.
After that just use the following code:
IWebDriver driverOne = new FirefoxDriver();
IWebDriver driverTwo = new InternetExlorerDriver("C:\\PathToMyIeDriverBinaries\");
The FirefoxDriver is included in the NuGet. However, you need to download manually the ChromeDriver from here: https://code.google.com/p/selenium/wiki/ChromeDriver
You can find ten mins tutorial with images here:
http://automatetheplanet.com/getting-started-webdriver-c-10-minutes/
A: You just need to include/import driver to your project if you want to use firefox unlike for CHROME you need to store the jar file or Exe to a particular location and then then you just need to call it in your project
demo program
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Firefox {
public void returnFirefoxBrowser(){
WebDriver driver = new FirefoxDriver();
}
}
chrome
File file = new File(
"//Users//Documents//workspace//SELENIUM//chromedriver");
System.setProperty("webdriver.chrome.driver",file.getAbsolutePath());
WebDriver driver_chrome;
driver_chrome = new ChromeDriver(); | unknown | |
d15821 | val | Maybe this is what you need:
int *p, **pp, n = 2;
p = new int[n * 2];
pp = &p;
for(int i = 0;i < n;i++)
cin >> *(*pp + n*i + i) >> *(*pp + n*i + i + 1);
for(int i = 0;i < n;i++)
cout << *(*pp + n*i + i) << " " << *(*pp + n*i + i + 1) << endl;
delete []p;
return 0; | unknown | |
d15822 | val | if (idAtual == idAnterior) {
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " Coords: " + coords);
} else {
linhasCoords.put(idAnterior,coords);
idAnterior = idAtual;
coords.clear();
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " LinhasCoords: " + linhasCoords);
}
So if idAtual is equal to idAnterior it wont be added to linhasCoords, only to coords.
Replace it with this:
if (idAtual == idAnterior) {
linhasCoords.put(idAnterior,coords);
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " Coords: " + coords);
} else {
linhasCoords.put(idAnterior,coords);
idAnterior = idAtual;
coords.clear();
coords.add(new LatLong(x,y));
Log.d("TRECHOS", " LinhasCoords: " + linhasCoords);
} | unknown | |
d15823 | val | jQuery is kind of obsolete, if you don’t need to support quite old platforms. So you’re right in searching for a non-jQuery solution.
It’s not necessary to code JS yourself, as there are plenty of libraries out there that you can use for such purposes. Usually they come in so called packages, which can be installed by means of the node package manager (npm).
Learning how to integrate npm can be quite long, so you can also download libraries (aka scripts) that you might find on the web. It’s important that the download includes all dependencies.
You will need to ask yourself some questions, though, to be able to choose the right library/script:
*
*What is the UI pattern that you want to use? This will determine your search keyword
*
*Collapse column-groups into one column? This is called a collapse pattern, I would recommend it due to it’s intuitiveness.
*Have a checklist on your site to hide the step completely from the table?
*Should the solution be accessible to users with situational, temporary or permanent disabilities? Include the keyword accessible or a11y in your search
*
*The minimum should be keyboard support
*What platforms need to be supported (browser version and operating system)?
*Is there already another JavaScript framework used in the intranet, like jQuery or other?
*
*You would either like to look for a library that integrates well,
*or one that uses “vanilla” JavaScript, so no framework at all
*Are you using a build system, into which the library should integrate? Ask the architects, if you don’t know
*How much of your solution would you be willing to replace by a library?
*
*There are Data Grid libraries out there that offer your functionality, but will build the whole table based on JavaScript, instead of simply adding functionality
*or would you like to apply progressive enhancement, meaning you’re simply adding functionality on top of a already fully usable table? (I’d recommend that)
*Which licenses do you accept? There are different open source licenses, that allow you manipulating code or not, and might oblige you to publish any changes you make
Finally, the library will need a mapping between the toggle and the columns to hide somewhere. It can be done in JavaScript only, but I would recommend to use a library that makes use of HTML attributes instead, so that you don’t need to write JavaScript.
If the library is specialised in tables, it might use the already present colspan attributes to do the mapping.
Otherwise, you might have to provide the mapping with data- attributes.
So, your search might be like “Accessible collapsible column groups javascript”.
Example with Bootstrap
Here is an example based on Bootstrap’s Collapse Component. Bootstrap is a framework and supports accessibility. Some particularities concerning accessibility in tables might be missing.
Note that you cannot hide cells directly, if you keep the grouping header visible, since the table’s structure would fall apart.
If you go for the checklist solution instead of a collapse pattern, you could use the same component, and reference all cells (including those with colspan) in the data-bs-target attribute.
…
<thead>
<tr>
<th>
Step 0 - Info 1
<button class="btn btn-light" data-bs-toggle="collapse" data-bs-target=".cell-col-0" aria-expanded="false">Toggle</button>
</th>
…
<th>
Step 1 - User+Date
<button class="btn btn-light" data-bs-toggle="collapse" data-bs-target=".cell-col-1" aria-expanded="false">Toggle</button>
</th>
…
</tr>
…
<tr>
<th><div class="cell-col-0">Step 0 - Info 1</div></th>
…
<th><div class="cell-col-1">Step 1 - User+Date</div></th>
…
</tr>
</thead>
<tbody>
<tr>
<td><div class="cell-col-0">Step 0 - Info 1 - Row 1</div></td>
…
<td><div class="cell-col-1">Step 1 - User+Date - Row 1</div></td>
…
A: There is no need to use an unwieldy library. Plain "Vanilla" JavaScript will do. The following lines of code will make a col within a colgroup disappear, when you deselect its corresponding checkbox on top of the table:
/* // ===========================================================
// un-comment this section when you run this from your PHP server:
<?PHP $hidden = array(0,2); // hide steps 0 and 2 ?>
const hidden=<?PHP echo json_encode($hidden); ?>;
// ============================================================*/
// stackoverflow mockup of PHP input:
const hidden=[0,2];
const cols = document.querySelectorAll("table col:nth-child(n+4)"),
ttls= [...document.querySelectorAll("table tr.ttl th:nth-child(n+4)")].map(t=>t.textContent),
div = document.querySelector("div");
div.innerHTML=ttls.map(t=>`<label><input type="checkbox" checked>${t}</label>`).join(" ");
const cbs = div.querySelectorAll("input[type=checkbox]");
hidden.forEach(h=>{cols[h].classList.add("hidden");cbs[h].checked=false});
cbs.forEach((cb,i)=>{
cb.addEventListener("change",ev=>cols[i].classList.toggle("hidden",!cb.checked))
});
// enter a few lines of data into the table ... (to make it look more impressive)
document.getElementById("tbd").innerHTML = [...Array(5)].map((_, i) =>
`<tr>${[...Array(25)].map((_,j)=>
`<td>${(i+1)*100+j}</td>`).join("")}</tr>`).join("\n");
td,
th {
border: 1px solid grey
}
.hidden {
visibility: collapse
}
<div></div>
<table>
<thead>
<colgroup>
<col>
<col>
<col>
<col span='11' class='step0'>
<col span='2' class='step1'>
<col span='3' class='step2'>
<col span='3' class='step3'>
<col span='3' class='step4'>
</colgroup>
<tr class="ttl">
<th rowspan='2'>ID</th>
<th rowspan='2'>Name</th>
<th rowspan='2'>State</th>
<th colspan='11'>Step 0</th>
<th colspan='2'>Step 1</th>
<th colspan='3'>Step 2</th>
<th colspan='3'>Step 3</th>
<th colspan='3'>Step 4</th>
</tr>
<tr>
<th>Step 0 - Info 1</th>
<th>Step 0 - Info 2</th>
<th>Step 0 - Info 3</th>
<th>Step 0 - Info 4</th>
<th>Step 0 - Info 5</th>
<th>Step 0 - Info 6</th>
<th>Step 0 - Info 7</th>
<th>Step 0 - Info 8</th>
<th>Step 0 - Info 9</th>
<th>Step 0 - User+Date</th>
<th>Step 0 - Notes</th>
<th>Step 1 - User+Date</th>
<th>Step 1 - Notes</th>
<th>Step 2 - Info</th>
<th>Step 2 - User+Date</th>
<th>Step 2 - Notes</th>
<th>Step 3 - Info</th>
<th>Step 3 - User+Date</th>
<th>Step 3 - Notes</th>
<th>Step 4 - Info</th>
<th>Step 4 - User+Date</th>
<th>Step 4 - Notes</th>
</tr>
</thead>
<tbody id="tbd"></tbody>
</table>
I am not sure whether this will work on all browsers, but I tested it successfully on Chrome, Edge and Firefox. | unknown | |
d15824 | val | str is a reserved word in Python, and you overwrote it by naming rearrange() second parameter str as well. Changing the name of rearrange() second parameter will do the trick.
A: You have named your variable str - same name as built-in function for conversion to string. You need to rename it, try this:
import re
class Solution:
def rearrange(self, str_in):
# Write your code here
if str_in == "":
return str_in
sum = 0
letter = []
for i in range(len(str_in)):
if re.search("([A-Z])", str_in[i]):
letter.append(str_in[i])
else:
sum += int(str_in[i])
letsort = sorted(letter)
letstr = "".join(letsort)
result = letstr + str(sum)
return result | unknown | |
d15825 | val | What about simple
public Tor(int size)
{
elements = new T[size];
}
A: public class Tor<T> where T : new()
{
public Tor(int size)
{
elements = new T[size];
for (int i = 0; i < size; i++)
{
elements[i] = new T();
}
}
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
}
or
public class Tor<T> where T : new()
{
public Tor(int size)
{
elements = Enumerable.Range(1,size).Select (e => new T()).ToArray();
}
...
}
A: public class Tor<T>
{
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
public Tor(int capacity)
{
elements = new T[capacity];
}
}
should do it.
A: public class Tor<T>
{
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
public Tor(int size)
{
if (size < 0)
throw new ArgumentOutOfRangeException("Size cannot be less then zero");
elements = new T[size];
next = 0;
}
}
A: Consider using existing classes
*
*derive from Queue if needed events like suggested in C#: Triggering an Event when an object is added to a Queue
*or if you want to build your own use List which will allow to grow array as needed/preallocate if you want to. | unknown | |
d15826 | val | The compiler is allowed to choose whatever order it wants, in order to provide more optimal code, or even just random because it's easier to implement. One thing you might try is -O0 flag which disables all optimizations.
A: Compilers are free to rearrange variables as they feel is best. I believe that the only restriction in the order of struct members. Those must be in memory in the same order as declared in the struct.
A: I found this thread quite interesting:
http://www.mail-archive.com/[email protected]/msg05043.html
Quote: In theory it can be done
-fdata-section
A: Apple has a security feature to prevent just the type of hacking you are talking about - There is a degree of randomization to where everything is stored in memory, so you can't for example find the memory allocated for a certain program, and go to the 1502nd byte where the function to open the high security vault locks sits, cause it isn't always in the same place in memory.
See http://en.wikipedia.org/wiki/Address_space_layout_randomization for details on how this works.
Funny coincidence that you would encounter this, and that Matt Joiner would stumble on the answer while trying to burn apple. | unknown | |
d15827 | val | No, they are not the same. If you lock against a different object than an already existing lock, then both code paths will be allowed. So, in the case of Process2 curtype == 'b' the lock is using the _LockerB object. If one of the other locks using the _LockerA object is attempted, then they will be allowed to enter the LongProcess.
A: Process1 and Process2 have the potential to lock the same object, but they are definitely not the same. Locks on the same object are however allowed (I think, rarely if ever had to do it) within the same call stack (also referred to as recursive locking in the case where Process1 invokes Process2). This could likely be better described as dependent locking.
Your question is however fairly vague so you'll have to elaborate on what you mean by the same... | unknown | |
d15828 | val | Try checking the SOAP response against the following XSD file. I added elements for the outer <soap:Envelope> and <soap:Body> tags which are present in the SOAP response.
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org"
xmlns:tns="http://www.w3.org/2003/05/soap-envelope">
<xs:element name="Envelope" type="tns:envType">
<xs:complexType name="envType">
<xs:sequence>
<xs:element name="Body" type="tns:bodyType">
<xs:complexType name="bodyType">
<xs:sequence>
<xs:element name="GetHTMLResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="GetHTMLResult" minOccurs="0"
maxOccurs="1" type="xs:string">
<xs:simpleType>
<xs:restriction base="xs:string">
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema> | unknown | |
d15829 | val | In a comment you mentioned:
This is a web-site rather than web app.
"Web site" vs. "web app" seems like a moot distinction at this point. There's enough complexity in the code that it's an "application" by pretty much any definition of the word. To that point, if the application host doesn't meaningfully manage thread faults for you (and I wouldn't expect a web application host to do so) then you have to manage them manually.
In this case I see that as one of two options:
Option 1: Don't let your threads end in a faulted state. Whatever your top-level worker item for any given thread is (a method invoked at the start of the thread, a loop repeating operations, etc.), that needs to be essentially fault-proof. No exception should get past that. Which means it needs to be dead simple (so as to not throw exceptions of its own) and needs to catch any and all exceptions from the operation(s) it invokes.
Once caught, do with them as you please. Roll back a unit of work, notify someone of the error, etc.
Option 2: Move the long-running thread operations out of the web application, since web applications aren't really suited for ongoing background processes. A Windows Service or scheduled Console Application is a much more suited application host for that logic.
Yes, bit of a re-write there though.
Is it? It shouldn't be. That's really a matter of how the code was originally architected, not related to the application hosts themselves. Invoking a business operation from one application host is the same as invoking it from another. If the logic is tightly coupled to the application technology, that's a separate problem. And there's no quick fix to that problem. The good news is that once you fix that problem, other problems (like the one which prompted this question) are quick fixes. | unknown | |
d15830 | val | 1) Install socket.io-client
npm install socket.io-client --save
2) Install socket.io-client typings
npm install @types/socket.io-client --save-dev
3) Import socket.io-client in your app/code
import * as io from "socket.io-client";
A: Is this file present node_modules/socket.io-client/socket.io.js.
Check dts file is present in typings folder for socket-io.
Since you already specified the extension in map no need to specify it again in defaultExtension of package.
Try adding format: 'cjs' OR format: 'amd' based on library in the package -> socket.io-client
A: system-config.ts
/** Map relative paths to URLs. */
const map: any = {
"socket.io-client": "vendor/socket.io-client/"
};
/** User packages configuration. */
const packages: any = {
"socket.io-client": {
format: 'cjs',
defaultExtension: 'js',
main: 'socket.io.js'
}
};
angular-cli-build.js
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'socket.io*/**/*.js'
]
});
};
Working like a charm angular-cli: "1.0.0-beta.10"
A: This works for me:
npm install --save @types/socket.io-client | unknown | |
d15831 | val | Neither mapply nor lapply pass the names of the items in their data objects to the "working functions". What you see after the function completion is that they add back the names to the results. Even if you use the deparse(substitute)) strategy you end up with a useless name like "dots[[1L]][[1L]]". So you are condemned to either index by the names themselves or by a numeric index into the names(dataframe) values.
A: Consider passing column names to fit your column assignment and ylab character requirement. And as @alistaire comments, you are only passing one vector into your function. Mapply (informally as multivariate apply) is designed to iterate elementwise through more than one equal-length or multiple-length vectors. This would be akin to passing in Sepal.Length 1 or 3 times:
plotfct <- function(ii, jj)
plot(x = iris[[ii]], y = iris[[jj]],
xlab = paste(ii), ylab = paste(ii))
mapply(plotfct, c("Sepal.Length", "Sepal.Length", "Sepal.Length"),
c("Sepal.Width", "Petal.Length", "Petal.Width"))
But since Sepal.Length does not change, repeating its value to meet the length of longer is redundant. Simply use lapply or its simplified wrapper, sapply:
plotfct <- function(ii)
plot(x = iris[["Sepal.Length"]], y = iris[[ii]],
xlab = "Sepal Length", ylab = paste(ii))
lapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)
# EQUIVALENTLY:
# sapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct) | unknown | |
d15832 | val | Based on the comments discussion, the problem turned out to be the configuration file sequence. Recommend approach of removing the Kernel Ports, then binding with dpdk compatible driver works
ovs-vsctl del-port br-eth6 eth6
ovs-vsctl del-port br-eth9 eth9
dpdk-devbind –s
dpdk-devbind --force --bind=ixgbe 0000:81:00.0
dpdk-devbind --force --bind=ixgbe 0000:81:00.1
dpdk-devbind --force --bind=igb_uio 0000:81:00.0
dpdk-devbind --force --bind=igb_uio 0000:81:00.1
ovs-vsctl -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1
ovs-vsctl -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1
ovs-vsctl -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1 | unknown | |
d15833 | val | There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
*
*Split the other into its own function
*Try to use more accurate variable names
*As much as you can - avoid having multiple for loops happening at the same time
*Have a look at list comprehension it would help a lot in this case
*Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
A: The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises. | unknown | |
d15834 | val | Do you have a non-breaking space, or some other Unicode space character, somewhere in either your date string or format mask?
I was able to reproduce your error if I replaced one of the spaces in the second of your date strings with a non-breaking space, such as Unicode character 160. | unknown | |
d15835 | val | Lowest Time for Style 0 ZoneGroup 0
Lowest Time for Style 0 ZoneGroup 1
Lowest Time for Style 0 ZoneGroup 2
Lowest Time for Style 1 ZoneGroup 0
Lowest Time for Style 2 ZoneGroup 0
...
I could have multiple queries sent through my plugin, but I would like to know if this could be firstly eliminated with a GROUP_CONCAT function, and if so -how.
Here's what I could do, but I'ld like to know if this could be converted into one line.
for (int i = 0; i < MAX_STYLES; i++) {
for (int x = 0; x < MAX_ZONEGROUPS; x++) {
Transaction.AddQuery("SELECT * FROM `t_records` WHERE mapname = 'de_dust2' AND style = i AND zonegroup = x ORDER BY time ASC LIMIT 1;");
}
}
Thanks.
A: You don't need group_concat(). You want to filter records, so use WHERE . . . in this case with a correlated subquery:
select r.*
from t_records r
where r.mapname = 'de_dust2' and
r.timestamp = (select min(r2.timestamp)
from t_records r2
where r2.mapname = r.mapname and
r2.style = r.style and
r2.zonegroup = r.zonegroup
); | unknown | |
d15836 | val | When you open your streamwriter, you are not telling it to append, so it overwrites:
Dim writer As New IO.StreamWriter("log.txt", True)
Also, you dont need a new stream for each activity:
Dim msg as string= Environment.NewLine & "File " & e.FullPath & " "
Select case e.ChangeType
case IO.WatcherChangeTypes.Created
msg &= "has been created"
case IO.WatcherChangeTypes.Deleted
msg &= "has been deleted"
...etc
End Select
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msg)
writer.Close()
..you could also leave the stream open until the watcher ends
You probably should exempt logging changes to log.txt, so test e.FullPath:
If System.Io.Path.GetFileName(e.FullPath).ToLower = "log.text" Then Exit Sub
A: Now the program in working! Thank you MPelletier and Plutonix for the amazing help! Here is the complete code:
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Public watchfolder As FileSystemWatcher
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
watchfolder = New System.IO.FileSystemWatcher()
watchfolder.IncludeSubdirectories = True
watchfolder.Path = TextBox1.Text
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
AddHandler watchfolder.Renamed, AddressOf logrename
watchfolder.EnableRaisingEvents = True
Button1.Enabled = False
Button2.Enabled = True
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If System.IO.Path.GetFileName(e.FullPath).ToLower = "log.txt" Then Exit Sub
Dim msg As String = Environment.NewLine & "File " & e.FullPath & " "
Select Case e.ChangeType
Case IO.WatcherChangeTypes.Created
msg &= "has been created" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Deleted
msg &= "has been deleted" + " " + "Time:" + " " + Format(TimeOfDay)
Case IO.WatcherChangeTypes.Changed
msg &= "has been modified" + " " + "Time:" + " " + Format(TimeOfDay)
End Select
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msg)
writer.Close()
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
Select e.ChangeType
Case IO.WatcherChangeTypes.Created
Exit Sub
Case IO.WatcherChangeTypes.Changed
Exit Sub
Case IO.WatcherChangeTypes.Deleted
Exit Sub
Case Else
Dim msgrn As String = Environment.NewLine & "File " + e.OldName + " "
msgrn &= "has been renamed to" + " " + e.Name + " " + "Time:" + " " + Format(TimeOfDay)
Dim writer As New IO.StreamWriter("log.txt", True)
writer.WriteLine(msgrn)
writer.Close()
End Select
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
watchfolder.EnableRaisingEvents = False
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Hide()
MsgBox("To close it later, don't open the program again, press CTRL+ALT+DELETE and press Start Task Manager or something like that, and go to processes and kill FolderMonitor.exe or what you have named the file", 0 + 64, "FolderMonitor")
End Sub
End Class | unknown | |
d15837 | val | This is an Array<any>:
[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]
You need to convert it to a Array<Country>, Example:
result.forEach((e) => { countries.push(new Country(e.name, e.code))
That, or you can change the return of the function that reads the txt to Array<Country>
A: finally got it via below code...
let elements: Array<Country> = JSON.parse(JSON.stringify(response))
.map((item:Country) =>
{
console.log(item.name + ' < - >' + item.code);
})
Thanks All :) | unknown | |
d15838 | val | Does not fully use Linq, but works for what you need.
public class Limits
{
public string LowerWarningLimit = "";
public string UpperWarningLimit = "";
public string LowerAcceptanceLimit = "";
public string UpperAcceptanceLimit = "";
}
public static void GetLimits(string nameFile)
{
XDocument document = XDocument.Load(nameFile);
if (document == null)
{
Console.WriteLine("Document not found.");
return;
}
XElement root = document.Descendants("ControlItems").FirstOrDefault();
if (root == null)
{
Console.WriteLine("Could not find ControlItems.");
return;
}
Console.WriteLine("Inserisci lelemento chimico da modificare:");
var chimical = Console.ReadLine();
XElement nameSearch = root.Descendants("ControlItem").FirstOrDefault(x => x.Attribute("Name") != null && x.Attribute("Name").Value.ToLower() == chimical.ToLower());
if (nameSearch == null)
{
Console.WriteLine("Name not found.");
return;
}
Limits limits = new Limits();
foreach (XElement elements in nameSearch.Descendants())
{
string typeResult = elements.Attribute("Type").Value;
if (typeResult == null)
{
continue;
}
switch (typeResult)
{
case "LowerWarningLimit":
limits.LowerWarningLimit = elements.Value;
break;
case "UpperWarningLimit":
limits.UpperWarningLimit = elements.Value;
break;
case "LowerAcceptanceLimit":
limits.LowerAcceptanceLimit = elements.Value;
break;
case "UpperAcceptanceLimit":
limits.UpperAcceptanceLimit = elements.Value;
break;
}
}
Console.WriteLine(limits.LowerWarningLimit);
Console.WriteLine(limits.UpperWarningLimit);
Console.WriteLine(limits.LowerAcceptanceLimit);
Console.WriteLine(limits.UpperAcceptanceLimit);
}
A: static void Main(string[] args)
{
string xmlFilePath = @"C:\Users\vincenzo.lanera\Desktop\test.xml";
XmlDocument document = new XmlDocument();
document.Load(xmlFilePath);
Console.WriteLine("Inserisci l'elemento chimico da modificare:");
var chimical = Console.ReadLine();
//Searches the limit values of the selected element
XmlNodeList limitValues = document.SelectNodes($"//ControlItem[@Name='{chimical}']/LimitValue");
//Prints all limit values
Console.WriteLine($"Limit values of {chimical}:");
foreach (XmlNode limVal in limitValues)
{
Console.WriteLine($"{limVal.Attributes["Type"].Value} {limVal.InnerText}");
};
//Ask the user wich limit value wants to edit
Console.WriteLine("Inserisci il limit value da modificare:");
var limitValueToEdit = Console.ReadLine();
//Ask the user the new value
Console.WriteLine("Inserisci il nuovo valore:");
var newVal = Console.ReadLine();
//Edit the limit value
var nodeToEdit = document.SelectSingleNode($"//ControlItem[@Name='{chimical}']/LimitValue[@Type='{limitValueToEdit}']");
nodeToEdit.InnerText = newVal;
//Save the changes to the xml file
document.Save(xmlFilePath);
}
}
You should also handle the errors if the user inserts an invalid text. | unknown | |
d15839 | val | Twilio developer evangelist here.
You can use a URL that responds with an empty <Response> TwiML element. If you don't have a server to host that on, you could use http://twimlets.com. This link ought to do the trick:
http://twimlets.com/echo?Twiml=%3CResponse%3E%3C%2FResponse%3E& | unknown | |
d15840 | val | To set the session cookie path to a fixed location you don't need any calculation:
session_set_cookie_params($cookie_lifetime , '/index.php', $ssl, true);
It's worth noting that the default value is /. | unknown | |
d15841 | val | This is mentioned in the documentation @ https://docs.snowflake.com/en/sql-reference/constructs/order-by.html
All data is sorted according to the numeric byte value of each character in the ASCII table. UTF-8 encoding is supported.
For numeric values, leading zeros before the decimal point and trailing zeros (0) after the decimal point have no effect on sort order.
Unless specified otherwise, NULL values are considered to be higher than any non-NULL values. As a result, the ordering for NULLS depends on the sort order:
If the sort order is ASC, NULLS are returned last; to force NULLS to be first, use NULLS FIRST.
If the sort order is DESC, NULLS are returned first; to force NULLS to be last, use NULLS LAST.
An ORDER BY can be used at different levels in a query, for example in a subquery or inside an OVER() subclause. An ORDER BY inside a subquery or subclause applies only within that subquery or subclause. For example, the ORDER BY in the following query orders results only within the subquery, not the outermost level of the query: | unknown | |
d15842 | val | How did you test the balance ?, the doc says :
The source IP address is hashed and divided by the total
weight of the running servers to designate which server will
receive the request. This ensures that the same client IP
address will always reach the same server as long as no
server goes down or up. If the hash result changes due to the
number of running servers changing, many clients will be
directed to a different server. This algorithm is generally
used in TCP mode where no cookie may be inserted. It may also
be used on the Internet to provide a best-effort stickiness
to clients which refuse session cookies. This algorithm is
static by default, which means that changing a server's
weight on the fly will have no effect, but this can be
changed using "hash-type"
If you tested with just 2 different IP source you maybe fall in a particular case. | unknown | |
d15843 | val | For Chrome version >= 50, Geolocation API requires secured origin. But, it should work fine on your localhost.
Secured origins are origins that match the following (scheme, host, port) patterns:
*
*(https, *, *)
*(wss, *, *)
*(*, localhost, *)
*(*, 127/8, *)
*(*, ::1/128, *)
*(file, *, —)
*(chrome-extension, *, —)
You can read more about it here.
Update: Firefox, iOS Safari, Chrome Android, and Samsung Internet now also require secured contexts. | unknown | |
d15844 | val | I believe that your problem is dilation process. I understand that you wish to normalize image sizes, but you shouldn't break the proportions, you should resize to maximum desired by one axis (the one that allows largest re-scale without letting another axis dimension to exceed the maximum size) and fill with background color the rest of the image.
It's not that "standard MNIST just hasn't seen the number one which looks like your test cases", you make your images look like different trained numbers (the ones that are recognized)
If you maintained the correct aspect ration of your images (source and post-processed), you can see that you did not just resize the image but "distorted" it. It can be the result of either non-homogeneous dilation or incorrect resizing
A: There are already some answers posted but neither of them answers your actual question about image preprocessing.
In my turn I don't see any significant problems with your implementation as long as it's a study project, well done.
But one thing to notice you may miss.
There are basic operations in mathematical morphology: erosion and dilation (used by you). And there complex operations: various combinations of basic ones (eg. opening and closing).
Wikipedia link is not the best CV reference, but you may start with it to get the idea.
Usually in its better to use opening instead of erosion and closing instead of dilation since in this case original binary image changes much less (but the desired effect of cleaning sharp edges or filling gaps is reached).
So in your case you should check closing (image dilation followed by erosion with the same kernel).
In case extra-small image 8*8 is greatly modified when you dilate even with 1*1 kernel (1 pixel is more than 16% of image) which is less on larger images).
To visualize the idea see the following pics (from OpenCV tutorials: 1, 2):
dilation:
closing:
Hope it helps.
A: So, you need a complex approach cause every step of your computing cascade based on the previous results. In your algorithm you have the next features:
*
*Image preprocessing
As mentioned earlier, if you apply the resizing, then you lose information about the aspect ratios of the image. You have to do the same reprocessing of digits images to get the same results that was implied in the training process.
Better way if you just crop the image by fixed size pictures. In that variant you won't need in contours finding and resizing digit image before training process. Then you could make a little change in your crop algorithm for better recognizing: simple find the contour and put your digit without resizing at the center of relevant image frame for recognition.
Also you should pay more attention to the binarization algorithm. I have had experience studying the effect of binarization threshold values on learning error: I can say that this is a very significant factor. You may try another algorithms of binarization to check this idea. For example you may use this library for testing alternate binarization algorithms.
*Learning algorithm
To improve the quality of recognition you use cross-validation at the training process. This helps you to avoid the problem of overfitting for your training data. For example you may read this article where explained how to use it with Keras.
Sometimes higher rates of accuracy measure doesn't say anything about the real recognition quality cause trained ANN not found the pattern in the training data. It may be connected with the training process or the input dataset as explained above, or it may cause by the ANN architecture choose.
*ANN architecture
It's a big problem. How to define the better ANN architecture to solve the task? There are no common ways to do that thing. But there are a few ways to get closer to the ideal. For example you could read this book. It helps you to make a better vision for your problem. Also you may find here some heuristics formulas to fit the number of hidden layers/elements for your ANN. Also here you will find a little overview for this.
I hope this will helps.
A: After some research and experiments, I came to a conclusion that the image preprocessing itself was not the problem (I did change some suggested parameters, like e.g. dilation size and shape but they were not crucial to the results). What did help, however, were 2 following things:
*
*As @f4f noticed, I needed to collect my own dataset with real-world data. This already helped tremendously.
*I made important changes to my segmentation preprocessing. After getting individual contours, I first size-normalize the images to fit into a 20x20 pixel box (as they are in MNIST). After that I center the box in the middle of 28x28 image using the center of mass (which for binary images is the mean value across both dimensions).
Of course, there are still difficult segmentation cases, such as overlapping or connected digits, but the above changes answered my initial question and improved my classification performance. | unknown | |
d15845 | val | I would use PUT to change the order of the songs on the playlist:
GET /playlist/{id}/songs
{
{
"id" : "1",
"self" : "http://my.server/song/1",
"name" : "The Little Old Lady From Pasadena"
},
{
"id" : "2",
"self" : "http://my.server/song/2",
"name" : "Love Potion #9"
}
}
PUT /playlist/{id}/songs
{
{
"id" : "2",
"self" : "http://my.server/song/2",
"name" : "Love Potion #9"
},
{
"id" : "1",
"self" : "http://my.server/song/1",
"name" : "The Little Old Lady From Pasadena"
}
} | unknown | |
d15846 | val | You are almost there - your code was missing a parameter name for the image in the first block:
[AFImageRequestOperation imageRequestOperationWithRequest:nil imageProcessingBlock:^UIImage * (UIImage *image) { // <<== HERE
} cacheName:@"nsurl" success:^(NSURLRequest *request, NSHTTPURLResponse * response, UIImage * image){
}failure:^(NSURLRequest *request, NSHTTPURLResponse * response, NSError * error){
}];
I think this is a bug in Xcode, because it expanded the signature into precisely what you posted, without the parameter name. | unknown | |
d15847 | val | With the help of @jeb I managed to resolve this FIND issue on jenkins by placing the absolute path for (find) in the shell script - initially it was using the windows FIND cmd, so i needed to point to cygwin find cmd
before: for path in $(find dist/renew -name "*.js"); do
and after: for path in $(/usr/bin/find dist/renew -name "*.js"); do
Thaks to all that commented | unknown | |
d15848 | val | #You can try this
#So, you have to make left and right shifts down at the same time to activate this feature which is wired.
pyautogui.keyDown('shiftleft')
pyautogui.keyDown('shiftright')
pyautogui.hotkey('right','right','ctrl','up')
pyautogui.keyUp('shiftleft')
pyautogui.keyUp('shiftright')
#credits:Tian Chu
#https://stackoverflow.com/users/13967128/tian-chu
A: Previous answer is good. I was able to successfully highlight a whole Excel column using:
pyautogui.hotkey('ctrl','shiftright','shiftleft','down')
I tried using both shiftright and shiftleft on their own and it wouldn't work unless they were both used together.
A: Thanks, I lost almost 1 hour to find this answer cause on the documentation this is not specified, for me worked example:
py.keyDown('shiftleft')
py.keyDown('shiftright')
py.press('down', presses=253)
py.keyUp('shiftleft')
py.keyUp('shiftright')
Again, Thanks. | unknown | |
d15849 | val | You can copy paste run full code below
modified code of package https://pub.dev/packages/flutter_custom_clippers 's
StarClipper https://github.com/lohanidamodar/flutter_custom_clippers/blob/master/lib/src/star_clipper.dart
code snippet
class StarClipper extends CustomClipper<Path>
@override
Path getClip(Size size) {
...
double radius = halfWidth / 1.3;
...
Container(
height: 200,
width: 200,
child: ClipPath(
clipper: StarClipper(14),
child: Container(
height: 150,
color: Colors.green[500],
child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
),
),
),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:math' as math;
class StarClipper extends CustomClipper<Path> {
StarClipper(this.numberOfPoints);
/// The number of points of the star
final int numberOfPoints;
@override
Path getClip(Size size) {
double width = size.width;
print(width);
double halfWidth = width / 2;
double bigRadius = halfWidth;
double radius = halfWidth / 1.3;
double degreesPerStep = _degToRad(360 / numberOfPoints);
double halfDegreesPerStep = degreesPerStep / 2;
var path = Path();
double max = 2 * math.pi;
path.moveTo(width, halfWidth);
for (double step = 0; step < max; step += degreesPerStep) {
path.lineTo(halfWidth + bigRadius * math.cos(step),
halfWidth + bigRadius * math.sin(step));
path.lineTo(halfWidth + radius * math.cos(step + halfDegreesPerStep),
halfWidth + radius * math.sin(step + halfDegreesPerStep));
}
path.close();
return path;
}
num _degToRad(num deg) => deg * (math.pi / 180.0);
@override
bool shouldReclip(CustomClipper<Path> oldClipper) {
StarClipper oldie = oldClipper as StarClipper;
return numberOfPoints != oldie.numberOfPoints;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
width: 200,
child: ClipPath(
clipper: StarClipper(14),
child: Container(
height: 150,
color: Colors.green[500],
child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
A: I was trying to create Turkish flag for fun. Creating crescent was easy but creating star is not look easy. so I just tried to use my geometric and trigonometric knowledge to draw but no success. while continuing searching I encountered this link . Yeess I found what I look for. of course it was about different topic but functions was useful. so I reach my goal at the end of night.
So creating custom stars are possible with CustomPainter since now. Because I m sleepy and tired of being awake whole night I share all of code block with no further explanation. You can adjust offsetts according to your need. if any question. I m ready to answer. Enjoy coding.
class TurkishFlagPaint extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// x and y coordinates of starting point
final bx = 95;
final by = 0;
final paint = Paint();
paint.color = Colors.white;
final innerCirclePoints = 5; //how many edges you need?
final innerRadius = 80 / innerCirclePoints;
final innerOuterRadiusRatio = 2.5;
final outerRadius = innerRadius * innerOuterRadiusRatio;
List<Map> points =
calcStarPoints(bx, by, innerCirclePoints, innerRadius, outerRadius);
var star = Path()..moveTo(points[0]['x'], points[0]['y']);
points.forEach((point) {
star.lineTo(point['x'], point['y']);
});
canvas.drawPath(
Path.combine(
PathOperation.union,
//this combine for crescent
Path.combine(
PathOperation.difference,
Path()..addOval(Rect.fromCircle(center: Offset(-20, 0), radius: 80)),
Path()
..addOval(Rect.fromCircle(center: Offset(2, 0), radius: 60))
..close(),
),
star,// I also combine cresscent with star
),
paint,
);
}
//This function is life saver.
//it produces points for star edges inner and outer. if you need to //rotation of star edges.
// just play with - 0.3 value in currX and currY equations.
List<Map> calcStarPoints(
centerX, centerY, innerCirclePoints, innerRadius, outerRadius) {
final angle = ((math.pi) / innerCirclePoints);
var angleOffsetToCenterStar = 0;
var totalPoints = innerCirclePoints * 2; // 10 in a 5-points star
List<Map> points = [];
for (int i = 0; i < totalPoints; i++) {
bool isEvenIndex = i % 2 == 0;
var r = isEvenIndex ? outerRadius : innerRadius;
var currY =
centerY + math.cos(i * angle + angleOffsetToCenterStar - 0.3) * r;
var currX =
centerX + math.sin(i * angle + angleOffsetToCenterStar - 0.3) * r;
points.add({'x': currX, 'y': currY});
}
return points;
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
now you can use painter in a widget;
Center(
child: CustomPaint(
painter: TurkishFlagPaint(),
),
),
and the result will be like this :
A: Yes, CustomPaint is the right solution. You can calculate the Path (series of points around the Container) and then paint it with the drawPath method of the canvas.
For example, the path of a triangle would look like this:
return Path()
..moveTo(0, y)
..lineTo(x / 2, 0)
..lineTo(x, y)
..lineTo(0, y);
The Path starts at (0,y) (top-left), then a line to (x/2,0) (bottom-center) gets added and so on. This snipped was taken from this answer.
A: This code will help you build a centered star, to use it you just have to instantiate it in a ClipPath
import 'package:flutter/material.dart';
import 'dart:math' as math;
const STAR_POINTS = 5;
class StarClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
var centerX = size.width / 2;
var centerY = size.height / 2;
var path = Path();
var radius = size.width / 2;
var inner = radius / 2;
var rotation = math.pi / 2 * 3;
var step = math.pi / STAR_POINTS;
path.lineTo(centerX, centerY - radius);
for (var i = 0; i < STAR_POINTS; i++) {
var x = centerX + math.cos(rotation) * radius;
var y = centerY + math.sin(rotation) * radius;
path.lineTo(x, y);
rotation += step;
x = centerX + math.cos(rotation) * inner;
y = centerY + math.sin(rotation) * inner;
path.lineTo(x, y);
rotation += step;
}
path.lineTo(centerX, centerY - radius);
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
/// Instance
ClipPath(
clipper: StarClipper(),
child: Container(
color: Colors.red,
width: 80,
height: 80,
),
) | unknown | |
d15850 | val | Basically Spring and JEE stack are "competing" with each other. From what you've stated: EJB3 + JPA clearly belong to JEE stack, on the other hand SpringMVC is obviously from Spring universe + spring boot is obviously in a Spring camp.
Now, web.xml is kind of a bootstrap point for regular spring application (excluding spring boot of course). So, in general you should specify a web listener that will load up the spring. When you've tagged a spring boot in the question everything has mixed up. In two words, spring boot indeed alows to configure everything with annotation but it still "assumes" you're using spring under the hood.
Regarding the resources,
If you are working with DAO layer, you should define beans for those, but bottom line they will be managed by spring then.
But in this case there is no need for EJB. Of course you can still use JPA out of spring DAO (people tend to use Hibernate directly IMO this day if they really need ORM, and Hibernate implements JPA these days) if you wish, but in any case its again will be used by spring.
On the other hand if you need a JEE stack I doubt spring boot can really fit you.
JEE stack is a kind of "all-in-one" bundle which is supported by various application servers, and spring from this point of view is "take parts and combine by yourself" solution. So for spring project you can use tomcat/jetty which are not by any means fully compliant JEE servers. BTW this is exactly what spring boot does.
So I think for the sake of the project you should decide in which camp do you want to be, JEE or Spring. Both technologies look appealing these days, each of them has its benefits/drawbacks, but bottom line it boils down to:
*
*Spring is more flexible and innovative, you get changes faster
*Spring is more complicated to bootstrap (although if there are seasoned developers familiar with spring, it should not be an issue)
*JEE is standardized
A: Use Spring Boot - no need for xml there.
Spring Boot embeds Tomcat (or optionally Jetty), and so does not support EJB.
I'd rewrite the EJB' 's functionality as a "plain old Java" class, using spring features where needed.
For the external config file, Spring has several ways of providing configuration options at runtime / external to the deployment, so no need for JNDI. | unknown | |
d15851 | val | I don't quite understand your suggestion/explanation, but I feel like things are much simpler than you make it appear.
You don't need the newValue === oldValue test, because your watch-action is idempotent and cheap. But even if you do, it only means you need to initialize the value yourself (e.g. by calling toString() manually), which you seem to be doing and thus your directive should work as expected. (In fact, I couldn't reproduce the problem you mention with your code.)
Anyway, here is a (much simpler) working version:
.directive('test', function testDirective() {
return {
restrict: 'E',
template: '<p>{{ strVal }}</p>',
scope: {
val: '='
},
link: function testPostLink(scope) {
scope.$watch('val', function prettify(newVal) {
scope.strVal = (!newVal || (newVal < 1000)) ?
newVal :
(newVal / 1000) + 'K';
});
}
};
})
BTW, since you are only trying to "format" some value for display, it seems like a filter is more appropriate (and clear imo), than a $watch (see the above demo):
.filter('prettyNum', prettyNumFilter)
.directive('test', testDirective)
function prettyNumFilter() {
return function prettyNum(input) {
return (!input || (input < 1000)) ? input : (input / 1000) + 'K';
};
}
function testDirective() {
return {
template: '<p>{{ val | prettyNum }}</p>',
scope: {val: '='}
};
} | unknown | |
d15852 | val | You change type of input to "submit"
<input class="gradient-button" type="submit" value="JOIN NOW" onclick="checkPassword()" />
Moreover, remove onClick and add onSubmit event with checkPassword function on form tag | unknown | |
d15853 | val | I would suggest using a right-hand-side vector obtained from a predefined 'goal' solution x:
b = A*x
Then you have a goal solution, x, and a resulting solution, x, from the solver.
This means you can compare the error (difference of the goal and resulting solutions) as well as the residuals (A*x - b).
Note that for careful evaluation of an iterative solver you'll also need to consider what to use for the initial x.
The online collections of matrices primarily contain the left-hand-side matrix, but some do include right-hand-sides and also some have solution vectors too.:
http://www.cise.ufl.edu/research/sparse/matrices/rhs.txt
By the way, for the UF sparse matrix collection I'd suggest this link instead:
http://www.cise.ufl.edu/research/sparse/matrices/
A: I haven't used it yet, I'm about to, but GiNAC seems like the best thing I've found for C++. It is the library used behind Maple for CAS, I don't know the performance it has for .
http://www.ginac.de/
A: it would do well to specify which kind of problems are you solving...
different problems will require different RHS to be of any use to check validity..... what i'll suggest is get some example code from some projects like DUNE Numerics (i'm working on this right now), FENICS, deal.ii which are already using the solvers to solve matrices... generally they'll have some functionality to output your matrix in some kind of file (DUNE Numerics has functionality to output matrices and RHS in a matlab-compliant files).
This you can then feed to your solvers..
and then again use their the libraries functionality to create output data
(like DUNE Numerics uses a VTK format)... That was, you'll get to analyse data using powerful tools.....
you may have to learn a little bit about compiling and using those libraries...
but it is not much... and i believe the functionality you'll get would be worth the time invested......
i guess even a single well-defined and reasonably complex problem should be good enough for testing your libraries.... well actually two
one for Ax=B problems and another for Ax=cBx (eigenvalue problems) .... | unknown | |
d15854 | val | The cookies object is an instance ApplicationController::CookieJar. It's almost like a Hash but the behavior of the [] and []= methods are not symmetric. The setter sets the cookie value for sending to the browser. The getter retrieves the value which comes back form the browser. Hence when you access it in your code having just set the outgoing value the incoming value will be unset. There some more info on this here
Also did you intentionally mean to say cookie[:auth_token].keys or did you mean cookie.keys? | unknown | |
d15855 | val | Out of the box mod_pagespeed will optimize all javascript files referenced in the html, but with requirejs most scripts are going to be pulled in dynamically. To optimize those files, turn on InPlaceResourceOptimization (IPRO). IPRO is also enabled by default in versions 1.9 and newer.
You might also want to check out the optimization docs for requirejs. | unknown | |
d15856 | val | You shouldn't have any significant issues between Java 1.7 for testing and Java 1.8 for production. Problems exist beyond the 1.9 transition, but 1.7 and 1.8 are compatible.
What you might find is that combinations of start-up flags for the JVM itself (which GC you're using, any additional flags) are different between the two versions. So if you're using a start-up script to set JAVA_OPTIONS then there may be differences in the way that they are launched.
Finally, if you're doing any kind of performance testing then the tests won't be valid between the two JVMs. Even if you're using the same GC configuration, the performance differences in Java 1.7 are likely to be slightly different from Java 1.8. | unknown | |
d15857 | val | The Unix command for clearing the terminal is clear.
Alternatively, send the terminal codes for doing same (this varies by terminal, but this sequence works for most):
cout << "\033[H\033[2J";
(I got the sequence by simply running clear | less on my system. Try it and see if you get the same result.) | unknown | |
d15858 | val | Something looks weird in your MessagingCenter implementation, you're subscribing every time the Save button is clicked, which is wrong. You usually only subscribe once and unsubscribe when you're not interested in receiving messages anymore.
Also, I assume you're converting to json because you taught we can only pass string as message? If so, this is not the case, we can pass any object as message.
I'm not sure I understand your implementation, I've created a simple implementation that shows how to pass a InspectionSchemeChecks object between two classes.
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<SomeOtherClass, InspectionSchemeChecks>(this, "InspectionSchemeChecks", OnNewMessage);
}
protected override void OnDisappearing()
{
MessagingCenter.Unsubscribe<SomeOtherClass, InspectionSchemeChecks>(this, "InspectionSchemeChecks");
base.OnDisappearing();
}
private void OnNewMessage(SomeOtherClass sender, InspectionSchemeChecks schemeChecks)
{
// Do what you want
}
}
public class SomeOtherClass
{
public void SaveButton_Clicked(object sender, EventArgs e)
{
var SchemeChecks = new InspectionSchemeChecks();
var InspectionList = new List<InsScheme>();
//...
SchemeChecks.InsScheme = InspectionList;
MessagingCenter.Send<SomeOtherClass, InspectionSchemeChecks>(this, "InspectionSchemeChecks", SchemeChecks);
}
}
You can easily modify this example to send a string instead of InspectionSchemeChecks object as argument if you prefer to send the json as message. | unknown | |
d15859 | val | You need to target the immediate children of the navigation list. Use this selector:
#main-nav > ul > li:last-child > a
A: I'm going to post this, but please accept Chris' answer as his is right, except he did not have the correct Id name for the navigation.
#navigation > ul > li:last-child > a{
color:Red;
}
Here is a JSFiddle demonstrating that the 'Donate' is the only thing being turned red. | unknown | |
d15860 | val | One of ways to pull it off, is to make another coroutine, something like that:
IEnumerator UnlockSequence()
{
while (animInfo.normalizedTime < 1.0f)
{
yield return null;
}
anim.enabled = false;
sr.sprite = unlockSprite;
yield return new WaitForSeconds(1.0f);
yield return StartCoroutine(FadeTo(0.0f, 2.0f));
// everything else
} | unknown | |
d15861 | val | dismissing the keyboard is animated and this is enough for us to know that it happens async-ly, on main thread. In other words - you code block starts, dismissing the keyboard being added to main thread runloop, the thread sleeps for 2 seconds because you said so (Terrible thing to do if you ask me), and only than it's the keyboard's turn to get animated down and be dismissed.
A nice trick can be
[UIView animateWithDuration:0 animations: ^{
[self.usernameField resignFirstResponder];
[self.passwordField resignFirstResponder];
} completion: ^(BOOL finished) {
// Do whatever needed...
[NSThread sleepForTimeInterval:2.0f];
}];
BUT - I highly recommend finding a better solution than freezing the main thread.
Also - no what you asked for, but, assuming all your text fields are subviews of self.view you can just call [self.view endEditing:YES]; and you don't need to care about which text field is corrently the responder. | unknown | |
d15862 | val | First of all, the outer route has got to exist, in some routing.module
// app-routing.module.ts
const routes: Routes = [
{ path: 'getMeOut', component: OutComponent },
..
]
Four things are needed then
*
*Import Router from @angular/router.
*Create a private router in your constructor private router: Router.
*Call navigateByUrl() with the desired route.
*Identify your context menu with the nbContextMenuTag property.
Then, in the module that holds the context menu, we create the router to handle the navigation like
// awesome.component.ts
import { Router } from '@angular/router'
import { NbMenuService } from '@nebular/theme';
@Component({
selector: 'awesome',
styleUrls: ['./awesome.component.scss'],
templateUrl: './awesome.component.html',
})
ngOnInit() {
this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
)
.subscribe(title => {
if (title === 'Log out') this.router.navigateByUrl('/getMeOut');
console.error(`${title} was clicked!`)
});
}
constructor(
private menuService: NbMenuService,
private router: Router) {
}
See the simple use of navigateByUrl from @angular/router.
Just add nbContextMenuTag="my-context-menu" to the html template
<nb-action *nbIsGranted="['view', 'user']" >
<nb-user nbContextMenuTag="my-context-menu"></nb-user>
</nb-action>
I hope it's not a dupe. I found this answer but it meant more about nested routers. | unknown | |
d15863 | val | You can do it using the below CSS setting:
CSS:
.t-widget, .t-widget ~ * { /* The ~ * selects all elements following it */
color: red; /* Added just for illustration */
-webkit-box-sizing : content-box;
-moz-box-sizing : content-box;
-o-box-sizing : content-box;
box-sizing : content-box;
}
HTML:
<div>Your code goes here</div> <!-- Style will not be applied to this -->
<div class="t-widget t-window">Your code goes here</div> <!-- Style will be applied from this point on -->
<div>Your code goes here</div>
<div>Your code goes here</div>
<div>Your code goes here</div>
Demo
Edit: Just now saw your comment that you want for child elements. For that use the below CSS.
.t-widget, .t-widget * {
color: red;
-webkit-box-sizing : content-box;
-moz-box-sizing : content-box;
-o-box-sizing : content-box;
box-sizing : content-box;
}
Updated Demo
Here you can have a look at the comprehensive list of CSS3 Selectors. | unknown | |
d15864 | val | You have:
declare module BB {
}
Probably BB has been minified to something else. That would make module BB.MyModule be different from BB.
Solution: Your code is already safe for minification if the point where you bootstrap angular https://docs.angularjs.org/api/ng/function/angular.bootstrap is minified through the same pipeline as BB.module is passed through. | unknown | |
d15865 | val | As I have solved this issue by clearing a small confusion which can cause lot of stress to anyother like me.
Apple says : For iOS apps, bitcode is the default, but optional. For watchOS and tvOS apps, bitcode is required. If you provide bitcode, all apps and frameworks in the app bundle (all targets in the project) need to include bitcode.
So if your app does not having targets for WatchOS(in my case watchOS4 version) then it is ok to enable or disable bitcode settings as per your requirement. But in any case if you have watchOS targets in your app then you don't have any other option rather than enabling the bitcode for whole app targets and then only apple can accept your build for Appstore.
If you enable the bitcode for watchOS targets and disable the bitcode setting for other targets then the build can archive but the bitcode setting inside the build will always show "NOT INCLUDED" and apple rejects it.
And after enabling bitcode if you are using old third party libraries then you have to update each library to the version which support bitcode, it include pods as well. So beware of it because it is not easy task if your app is old and toooooo vast. | unknown | |
d15866 | val | Remove the dependency to spring-ibatis - this is for Spring v 2 and you are using version 5! Look at the release date, this is from 2008.
mybatis-spring is enough for spring integration of mybats (see here) | unknown | |
d15867 | val | Check below code.
val spark = SparkSession.builder().master("local").appName("xml").getOrCreate()
import com.databricks.spark.xml._
import org.apache.spark.sql.functions._
import spark.implicits._
val xmlDF = spark.read
.option("rowTag", "TABLE")
.xml(xmlPath)
.select(explode_outer($"ROWDATA.ROW").as("row"),$"_attrname".as("attrname"))
.select(
$"row._Type".as("type"),
$"row._VALUE".as("value"),
$"row._Unit".as("unit"),
$"row._track".as("track"),
$"attrname"
)
xmlDF.printSchema()
xmlDF.show(false)
Schema
root
|-- type: string (nullable = true)
|-- value: string (nullable = true)
|-- unit: long (nullable = true)
|-- track: long (nullable = true)
|-- attrname: string (nullable = true)
Sample Data
+-----+-----+----+-----+--------+
|type |value|unit|track|attrname|
+-----+-----+----+-----+--------+
|solid|null |0 |0 |Red |
|light|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
+-----+-----+----+-----+--------+ | unknown | |
d15868 | val | (?s)Start(?:(?!Start|End).)*<Word>(?:(?!End).)*End
(?!Start|End). matches any one character (including \n, thanks to the (?s) modifier) unless it's the first character of Start or End. That makes sure that you're only matching the innermost set of Start and End delimiters.
I used . in Singleline mode (via the inline (?s) modifier) to match any character including linefeed because you mentioned MatchCollection, indicating that you're using the .NET regex flavor. That [\s\S] hack is usually only needed in JavaScript.
CORRECTION: I had assumed you were talking about the class System.Text.RegularExpressions.MatchCollection from the .NET framework, but I've just learned that VBScript also contains a class called MatchCollection. It's probably the VBScript flavor you're using (via ActiveX or COM), so the regex should be:
Start(?:(?!Start|End)[\S\s])*<Word>(?:(?!End)[\S\s])*End
Sorry about the confusion. More info available here.
A: Two problems:
*
*You are using a "greedy" match - just add a ? to make it non-greedy. Without this, it will match a Start and End that spans two pairs - the first Start and the second End - and put it at both the start and the end of <Word>
*The expression [\s\S] matches everything - it's the same as a dot .. You want just white space [\s]
Try this (you can remove the redundant outer brackets too):
Start(.*?<Word>.*?)End
A: [\s\S] doesn't make much sense. \s matches whitespaces and \S does the exact opposite - it matches non-whitespaces. So [\s\S] is pretty much equivalent to ..
I am also unsure what you want to achieve with the .* after <Word>. That would just match the whitespaces after <Word>.
(Start[\s]+(<Word>)[\s]+End)
As far as I can tell, it works on your test case in http://regexpal.com/. | unknown | |
d15869 | val | You're probably looking for the \u{1f4c80} escape sequence, which allows arbitrary codepoints not just 4-digit charcodes like \u1234. | unknown | |
d15870 | val | Iterative approach:
search_item = "Item3 Item4"
with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
block = ''
for line in f_in:
if block:
block += line
if line.strip() == 'End':
if search_item not in block: f_out.write(block + '\n')
block = ''
elif line.startswith('Monitor'):
block = line
output.txt contents:
Monitor 1
Monitor 2
Item1 Item2
End
Monitor 6
Item4 Item5
End
A: You could accumulate the lines to write in a separate string that corresponds to the content of one block. Wait until you reach the end of the block ("end" line) before writing the accumulated lines. If along the way, you find the text pattern that indicates suppression of the block, set a flag that will prevent writing to the file when the end is reached.
For example (not tested):
with open(longStr1) as old_file:
lines = old_file.readlines()
lineBlock = ""
excluded = False
with open(endfile1, "w") as new_file:
for line in lines:
lineBlock += line
if line == "End":
if not excluded:
new_file.write(lineBlock)
lineBlock = ""
excluded = False
if "Item3 Item4" in line:
excluded = True | unknown | |
d15871 | val | You could try something like that:
#set ($columns = $allLegs.keySet().toArray())
#set ($maxCols = 3)
#set ($groups = ($columns.size() + $maxCols - 1)/$maxCols)
#set ($lastGroup = $groups - 1)
#foreach ($group in [0..$lastGroup])
<table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0">
#set ($firstCol = $maxCols*$group )
#set ($lastCol = $firstCol + $maxCols - 1)
#if ($lastCol >= $columns.size())
#set ($lastCol = $columns.size() - 1)
#end
<tr>
<th></th>
#foreach ($col in [$firstCol..$lastCol])
<th>$columns[$col]</th>
#end
</tr>
#set ($rows = $allLegs.get($columns[$firstCol]).keySet())
#foreach($row in $rows)
<tr>
<th>$row</th>
#foreach ($col in [$firstCol..$lastCol])
#set ($legMap = $allLegs.get($columns[$col]))
<td>$legMap.get($row)</td>
#end
</tr>
#end
</table>
#end
A: #set ($allLegs = $ConfirmationObject.getAllLegs())
#set ($columns = $allLegs.keySet())
#set ($maxCols = 3)
#set ($groups = ($columns.size() + $maxCols - 1)/$maxCols)
#set ($lastGroup = $groups - 1)
#foreach ($group in [0..$lastGroup])
#if($group >0 )
<br>
<br>
#end
<table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0">
#set ($allLegs = $ConfirmationObject.getAllLegs())
#set ($i = (($group*$maxCols)+1))
#set ($groupLegs = $ConfirmationObject.getGrouplLegSet($group, $maxCols))
<tr>
<td valign="top" width="30%"> </td>
#foreach($legSzie in $groupLegs.keySet())
<td valign="top" width="30%" align="left"><b>Leg $i</b></td>
#set ($i=$i+1)
#end
<td></td>
<td valign="top" width="10%" align="right"> </td>
</tr>
<td colspan="1">
<table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0">
#set ($map = $ConfirmationObject.getLegMap(1))
#foreach($key in $map.keySet())
<tr>
<td valign="top" width="60%">$key </td>
</tr>
#end
</table>
</td>
#foreach($legString in $groupLegs.keySet())
<td colspan="1">
<table style="font-family:Arial;font-size:xx-small;color:black" width="100%" border="0" cellspacing="0" cellpadding="0">
#set ($legMap = $allLegs.get($legString))
#foreach($legKey in $legMap.keySet())
<tr>
<td >$legMap.get($legKey)</td>
</tr>
#end
</table>
</td>
#end
</table>
#end
Here we wrote a java method getGrouplLegSet($group, $maxCols). The method would just return sub-set of hashmap based on the group and maxCols. So for example if the group is 0 then values from 0 till 2 will be returned, if group value is 1 then sub map from 3 till 5 will be returned and so on.. | unknown | |
d15872 | val | I think you should try
-[keysSortedByValueUsingSelector:] in NSDictionary, it is sorted by value and get the key results. | unknown | |
d15873 | val | Edit:
Taking a closer look at the Go repository, the releases are actually just tags and not Github releases, that's why it's returning an empty array. Try this:
// https://api.github.com/repos/jp9000/obs-studio/releases
releases, rsp, err := client.Repositories.ListReleases("jp9000", "obs-studio", opt)
This should correctly return all releases for jp9000's obs-studio repository.
Original Answer:
Looking at the docs, the code looks good but this might be an issue with Github's API though. For instance, if you go to https://api.github.com/repos/golang/go/releases you get an empty array, but if you search for the tags using https://api.github.com/repos/golang/go/tags it lists all tasks without any problem.
And if you go to https://api.github.com/repos/golang/go/releases/1 you get a 404. I took these addresses from the Github Developer's page: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository | unknown | |
d15874 | val | You need to use target on the sections that you want to show not the links
section:target {...}
See updated jsfiddle
nav {
height: 60px;
border-bottom: 1px solid #eaeaea;
}
.nav-item {
display: block;
float: left;
margin-right: 20px;
height: 60px;
font-size: 26px;
line-height: 60px;
text-align: center;
overflow: hidden;
color: #666;
text-decoration: none;
border-bottom: 3px solid transparent;
outline: none;
}
.nav-item:last-child {
margin-right: 0;
}
.nav-item:hover {
color: #333;
}
.nav-item.active,
.nav-item.active:hover {
color: #333;
border-bottom-color: #b39095;
}
section:target {
visibility: visible;
opacity: 1;
}
/* -------------------------------- SECTIONS -------------------------------- */
#sections {
float: left;
width: 1200px;
height: 400px;
}
section {
position: fixed;
width: 630px;
height: 400px;
float: left;
opacity: 0;
visibility: hidden;
transition: opacity 0.5s linear;
}
section p {
padding-top: 5px;
line-height: 1.6em;
}
section a {
color: #b39095;
text-decoration: none;
}
section a:hover {
color: #7b618a;
}
/* --------------------------------- OPTIONS -------------------------------- */
fieldset {
margin: 26px 0 15px 0;
border: 1px solid #ccc;
border-radius: 3px;
padding: 10px;
}
input {
padding-left: 2px;
}
#oxford-app-id {
width: 80px;
}
#oxford-app-key {
width: 290px;
}
label {
padding-left: 5px;
}
<div id="container">
<header>
<nav>
<a id="options" class="nav-item active" href="#section-options">options<br>saved</a>
<a id="about" class="nav-item" href="#section-about">about</a>
</nav>
</header>
<div id="sections">
<section id="section-options">
<p>
Options
</p>
</section>
<section id="section-about">
<p>
About
</p>
</section>
</div>
</div>
A: try this
:target {
visibility: visible;
opacity: 1;
}
A: From w3school:
URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
The :target selector can be used to style the current active target element.
:target selector is useful when within an URL is specified (using an anchor for example) an element in your HTML.
In your case you can use:
:target {
visibility: visible;
opacity: 1;
} | unknown | |
d15875 | val | Stylebot is a chrome extension that does the very thing. Use this link or if it doesn't work, just go to chrome://extensions then get more extensions and search for Stylebot
But still it won't let you add your own CSS file. It would just allow you to change the CSS of the website and it will store them for you so that whenever you'll visit that site, it would show you the same styles.
A: There are several ways of doing this: 1. First, plugin as you ask for, there is one called User Stylesheet for Chrome and Stylish for Firefox
2. You can edit C:\Users*\AppData\Local\Google\Chrome\User Data\Default\User StyleSheets\Custom.css directly for Chrome
3. You can use dev tool in both Chrome and Firefox to temporary change the element styles.
Just saw you asked for custom javascript as well, you can use Greasemonkey for Firefox and Tampermonkey for Chrome. | unknown | |
d15876 | val | Recyclerview inside nested scrollview does complete layout at a single load rather than usual recyclerview behaviour, try to remove nested scrollview from layout, use recyclerview with different view types. | unknown | |
d15877 | val | Found solution here:
https://answers.microsoft.com/en-us/msoffice/forum/all/ms-access-2016-system-resource-exceeded/df80f64a-f233-467e-89df-f05a8d58bc77
In short:
task manager/processes tab, find msaccess, right click and select set affinity.... option. I had 6 CPUs ticked (0 to 5). I un-ticked them all and just ticked the 0 CPU.
A: Not sure if this will help you, but I've managed to resolve this error by wrapping fields referenced in the WHERE clause with Nz e.g.
instead of
WHERE ReportDate = Date
use
WHERE Nz(ReportDate,ReportDate) = Date
It's strange but it seems to work for me, I've found the issue is often related to indexed fields, so I always add it to those fields first
A: Since currently there is no hot fix for 2016 version you have to merge either to 2010 or 2013. Then you can try merging to 2016.
Please check this link:
https://social.technet.microsoft.com/Forums/en-US/aedecca8-aa7d-417f-9f03-6e63e36f0c5d/access-2016-system-resources-exceeded?forum=Office2016setupdeploy&prof=required | unknown | |
d15878 | val | This happens when chrome tries to load a large number of images/resources in a short period of time.Have a look at this.
Try disabling the chrome plugin adblock plus and try.Still it may take long time to load | unknown | |
d15879 | val | Probably guessing a bit here but I think you need to emit SQL statements to set character_set_client and collation_connection before or when you create the trigger. Your C code client probably is using some kind of default | unknown | |
d15880 | val | If I read this correctly, the memory allocation failure is happening on the non-managed side, not the managed side. It seems strange then to blame WPF. I recognize that you are drawing your conclusion based on the fact that "it worked in WinForms", but there are likely more changes than just that. You can use a tool like the .NET Memory Profiler to see the differences between how the WPF application and the WinForms application are treating memory. You might find that your application is doing something you don't expect. :)
Per comment: Yup, I understand. If you're confident that you've ruled out things like environment changes, I think you have to grab a copy of BoundsChecker and Memory Profiler (or DevPartner Studio) and dig in and see what's messing up your memory allocation.
A: I'm guessing that the GC is moving your memory. Try pinning the memory in unmanaged land as long as you have a raw pointer to the array, and unpin it as soon as possible. It's possible that WPF causes the GC to run more often, which would explain why it happens more often with it, and if it's the GC, then that would explain why it happens at random places in your code.
Edit: Out of curiosity, could you also pre-allocate all of your memory up front (I don't see the code, so don't know if this is possible), and make sure all of your pointers are non-null, so you can verify that it's actually happening in the memory allocation, rather than some other problem?
A: It sounds like you want to be more careful about your memory management in general; ie: either run the processing engine in a separate address space which carefully manages memory, or pre-allocate a sufficiently large chunk before memory gets too fragmented and manage images in that area only. If you're sharing address space with the .NET runtime in a long-running process, and you need large contiguous areas, it's always going to potentially fail at some point. Just my 2c.
A: This post might be useful
http://blogs.msdn.com/tess/archive/2009/02/03/net-memory-leak-to-dispose-or-not-to-dispose-that-s-the-1-gb-question.aspx | unknown | |
d15881 | val | Very rarely.
I'd say only at the top level of a thread in order to ATTEMPT to issue a message with the reason for a thread dying.
If you are in a framework that does this sort of thing for you, leave it to the framework.
A: Almost never. Errors are designed to be issues that applications generally can't do anything about. The only exception might be to handle the presentation of the error but even that might not go as planned depending on the error.
A: An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.
From the Java API Specification for the Error class:
An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not try
to catch. Most such errors are
abnormal conditions. [...]
A method is not required to declare in
its throws clause any subclasses of
Error that might be thrown during the
execution of the method but not
caught, since these errors are
abnormal conditions that should never
occur.
As the specification mentions, an Error is only thrown in circumstances that are
Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)
Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.
There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.
A: If you are crazy enough to be creating a new unit test framework, your test runner will probably need to catch java.lang.AssertionError thrown by any test cases.
Otherwise, see other answers.
A: Never. You can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.
http://pmd.sourceforge.net/rules/strictexception.html
A: And there are a couple of other cases where if you catch an Error, you have to rethrow it. For example ThreadDeath should never be caught, it can cause big problem is you catch it in a contained environment (eg. an application server) :
An application should catch instances of this class only if it must clean up
after being terminated asynchronously. If ThreadDeath is caught by a method,
it is important that it be rethrown so that the thread actually dies.
A: Very, very rarely.
I did it only for one very very specific known cases.
For example, java.lang.UnsatisfiedLinkError could be throw if two independence ClassLoader load same DLL. (I agree that I should move the JAR to a shared classloader)
But most common case is that you needed logging in order to know what happened when user come to complain. You want a message or a popup to user, rather then silently dead.
Even programmer in C/C++, they pop an error and tell something people don't understand before it exit (e.g. memory failure).
A: In an Android application I am catching a java.lang.VerifyError. A library that I am using won't work in devices with an old version of the OS and the library code will throw such an error. I could of course avoid the error by checking the version of OS at runtime, but:
*
*The oldest supported SDK may change in future for the specific library
*The try-catch error block is part of a bigger falling back mechanism. Some specific devices, although they are supposed to support the library, throw exceptions. I catch VerifyError and all Exceptions to use a fall back solution.
A: it's quite handy to catch java.lang.AssertionError in a test environment...
A: Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.
A: Generally you should always catch java.lang.Error and write it to a log or display it to the user. I work in support and see daily that programmers cannot tell what has happened in a program.
If you have a daemon thread then you must prevent it being terminated. In other cases your application will work correctly.
You should only catch java.lang.Error at the highest level.
If you look at the list of errors you will see that most can be handled. For example a ZipError occurs on reading corrupt zip files.
The most common errors are OutOfMemoryError and NoClassDefFoundError, which are both in most cases runtime problems.
For example:
int length = Integer.parseInt(xyz);
byte[] buffer = new byte[length];
can produce an OutOfMemoryError but it is a runtime problem and no reason to terminate your program.
NoClassDefFoundError occur mostly if a library is not present or if you work with another Java version. If it is an optional part of your program then you should not terminate your program.
I can give many more examples of why it is a good idea to catch Throwable at the top level and produce a helpful error message.
A: In multithreaded environment, you most often want to catch it! When you catch it, log it, and terminate whole application! If you don't do that, some thread that might be doing some crucial part would be dead, and rest of the application will think that everything is normal. Out of that, many unwanted situations can happen.
One smallest problem is that you wouldn't be able to easily find root of the problem, if other threads start throwing some exceptions because of one thread not working.
For example, usually loop should be:
try {
while (shouldRun()) {
doSomething();
}
}
catch (Throwable t) {
log(t);
stop();
System.exit(1);
}
Even in some cases, you would want to handle different Errors differently, for example, on OutOfMemoryError you would be able to close application regularly (even maybe free some memory, and continue), on some others, there is not much you can do.
A: Generally, never.
However, sometimes you need to catch specific errors.
If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageError (no class def found, unsatisfied link, incompatible class change).
I've also seen some stupid 3rd-party code throwing subclasses of Error, so you'll have to handle those as well.
By the way, I'm not sure it isn't possible to recover from OutOfMemoryError.
A: ideally we should never catch Error in our Java application as it is an abnormal condition. The application would be in abnormal state and could result in carshing or giving some seriously wrong result.
A: It might be appropriate to catch error within unit tests that check an assertion is made. If someone disables assertions or otherwise deletes the assertion you would want to know
A: There is an Error when the JVM is no more working as expected, or is on the verge to. If you catch an error, there is no guarantee that the catch block will run, and even less that it will run till the end.
It will also depend on the running computer, the current memory state, so there is no way to test, try and do your best. You will only have an hasardous result.
You will also downgrade the readability of your code. | unknown | |
d15882 | val | When you delete a node, you call deleteAll(temp) which deletes temp, but it doesn't remove the pointer value from the l or r of temp's parent node.
This leaves you with a invalid pointer, causing garbage printing and crashing.
Unfortunately, the way your find works currently, you don't know what the current temp node's parent is when you get around to checking its value.
One way to fix it is to have a different type of find (called something like remove) that looks in l and r at each iteration for the value and sets l or r to NULL before returning the pointer. You might have to have a special case for when the value is found in the root.
Edit (sample code added):
I am assuming you are not using recursion for some reason, so my code uses your existing queue based code. I only changed enough to get it working.
findAndUnlink find the node with the value given and "unlinks" it from the tree. It returns the node found, giving you a completely separate tree. Note: it is up to the caller to free up the returned tree, otherwise you will leak memory.
This is a drop in replacement for find in your existing code, as your existing code then calls deleteAll on the returned node.
link findAndUnlink(int x) {
if (head == 0) {
cout << "\nEmpty Tree\n";
return 0;
}
link temp = head;
if (temp->item == x) {
// remove whole tree
head = NULL;
return temp;
}
// To find the node with the value x and remove it from the tree and return its link
QUEUE q(100);
q.put(temp);
while (!q.empty()) {
temp = q.get();
if (temp->l != NULL) {
if (temp->l->item == x) {
link returnLink = temp->l;
temp->l = NULL;
return returnLink;
}
q.put(temp->l);
}
if (temp->r != NULL) {
if (temp->r->item == x) {
link returnLink = temp->r;
temp->r = NULL;
return returnLink;
}
q.put(temp->r);
}
}
return 0;
}
A: Try the recursive function:
void Delete(link h)
{
if(h)
{
if(h->l) Delete(h->l);
if(h->r) Delete(h->r);
delete(h);
}
} | unknown | |
d15883 | val | You can store the "seed data" any way you like, text files, plists etc. and even in a database (presumably sqlite).
Then when starting up your app, check if the data already exists in your core data store. If not, import the file into your database.
You could also have a preconfigured database and copy that to the application documents directory to make it writable. This is a somewhat more involved approach, as you will have to regenerate this seed database each time your seed data or model changes.
A: In my apps I have a DB which I only use to read from (no writing), I include it in my bundle that is distributed. I then update the AppDelegate->persistentStoreCoordinator method to point to the correct location for my DB.
If I needed to write to the DB, then I would need to move it to the Documents directory prior to accessing it. And the changes to AppDelegate->persistentStoreCoordinator would not be needed. | unknown | |
d15884 | val | First of all, this code as posted doesn't work for me:
blocks = Keyword('#start') + block
Changing to this:
blocks = Keyword('#start') + MatchFirst(block)
at least runs against your sample text.
Rather than hard-code all the keywords, you can try using one of pyparsing's adaptive expressions, matchPreviousLiteral:
(EDITED)
def grammar():
import pyparsing as pp
comment = pp.cStyleComment
start = pp.Keyword("#start")
end = pp.Keyword('#end')
ident = pp.Word(pp.alphas + "_", pp.printables)
integer = pp.Word(pp.nums)
inner_ident = ident.copy()
inner_start = start + inner_ident
inner_end = end + pp.matchPreviousLiteral(inner_ident)
inner_block = pp.Group(inner_start + pp.SkipTo(inner_end) + inner_end)
VERSION, PROJECT, SECTION = map(pp.Keyword, "VERSION PROJECT SECTION".split())
version = VERSION - pp.Group(integer('major_version') + integer('minor_version'))
project = (start - PROJECT + ident('project_name') + pp.dblQuotedString
+ start + SECTION + ident('section_name') + pp.dblQuotedString
+ pp.OneOrMore(inner_block)('blocks')
+ end + SECTION
+ end + PROJECT)
grammar = version + project
grammar.ignore(comment)
return grammar
It is only necessary to call ignore() on the topmost expression in your grammar - it will propagate down to all internal expressions. Also, it should be unnecessary to sprinkle ZeroOrMore(comment)s in your grammar, if you have already called ignore().
I parsed a 2MB input string (containing 10,000 inner blocks) in about 16 seconds, so a 2K file should only take about 1/1000th as long. | unknown | |
d15885 | val | You can probably accomplish what you want using the sessionStorage object. In that object, you can track which pages have been visited in the current session.
The issue you can run into with JavaScript (and the reason I said it may not be the best approach) is that, when using a library, there is always a finite amount of time that passes while the library is loaded, parsed, and executed. This makes your "only appear on the first visit" requirement somewhat difficult to accomplish in JavaScript. If you show it by default and hide it with library code, it will show briefly each time you go to the page. If you hide it by default and show it with library code, it will be briefly hidden the first time you go to the page.
One way to handle this is to use embedded JavaScript that is executed immediately after the DOM for the preloader is defined. The downside to this is that you have to know how to write cross-browser JavaScript without assistance from a library like jQuery. In your case, the JavaScript required to simply hide the preloader is simple enough that it shouldn't have any cross-browser issues.
I created a simple page that demonstrates the technique. The source for this page is:
<html>
<head>
<style>
#preloader {
position: fixed;
left: 0;
top: 0;
z-index: 1000;
width: 100%;
height: 100%;
overflow: visible;
color: white;
background-color: #202020;
}
</style>
</head>
<body>
<div id="preloader">Preloader</div>
<script>
if (sessionStorage[location.href]) {
document.getElementById('preloader').style.display = 'none';
}
sessionStorage[location.href] = true;
</script>
<p>This is the text of the body</p>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function () {
setTimeout(function(){
$('#preloader').fadeOut(1500);
}, 5000);
});
</script>
</body>
</html>
I also created a fiddle for it: http://jsfiddle.net/cdvhvwmm/ | unknown | |
d15886 | val | I do believe you are getting that error because "File-rZVgZNpNuB" is an invalid key. Remember that keys can only start with a lowercase letter. | unknown | |
d15887 | val | Your SASS is quiet complex and nested quite a lot so it looks like you've missed a level out somewhere.
Using CSS (converted the SASS via SASSMeister) it was possible to see that the hover effect had not been applied to the first level li.
Also, 999em is a lot, you might want to consider reducing that or speeding up the transtion.
Reduced CSS using available classes.
.main-navigation {
clear: both;
display: block;
float: left;
width: 100%;
}
.main-navigation ul {
list-style: none;
margin: 0;
padding-left: 0;
}
.sub-menu {
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
float: left;
position: absolute;
top: 1.5em;
left: -999em;
z-index: 99999;
transition: left .25s ease;
}
.main-navigation ul li:hover > .sub-menu {
left:0;
}
.main-navigation ul ul a {
width: 200px;
padding: 1em;
}
.main-navigation li {
float: left;
position: relative;
}
.main-navigation a {
display: block;
text-decoration: none;
margin-right: 1em;
}
JSfiddle Demo | unknown | |
d15888 | val | Mistake:
You are on right track but just printing in case its even wont help. You actually need to add that number to the total sum so far as:
n = 10
total = 0
i = 0
while i < n:
if i % 2 == 0:
total+=i
else:
print(i)
i+=2
print(total)
Or simply:
print(sum([i for i in range(n) if i%2==0]))
A: n = 10
sum = 0
for i in range(0, n):
if i % 2 == 0:
sum += i
print (sum)
A: n = 10
total = 0
for i in range(10):
if i % 2 == 0:
total = total + i
print("Total of even numbers is " + total) | unknown | |
d15889 | val | Change the following functions in JQuery-ui resizable plugin
_mouseStart: function(event) {
var curleft, curtop, cursor,
o = this.options,
iniPos = this.element.position(),
el = this.element;
this.resizing = true;
// bugfix for http://dev.jquery.com/ticket/1749
if ( (/absolute/).test( el.css("position") ) ) {
el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
} else if (el.is(".ui-draggable")) {
el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
}
this._renderProxy();
curleft = num(this.helper.css("left"));
curtop = num(this.helper.css("top"));
if (o.containment) {
curleft += $(o.containment).scrollLeft() || 0;
curtop += $(o.containment).scrollTop() || 0;
}
//Store needed variables
this.offset = this.helper.offset();
this.position = { left: curleft, top: curtop };
this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalPosition = { left: curleft, top: curtop };
this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
this.originalMousePosition = { left: event.pageX, top: event.pageY };
var angle=0;
var matrix = $(el).css("-webkit-transform") ||
$(el).css("-moz-transform") ||
$(el).css("-ms-transform") ||
$(el).css("-o-transform") ||
$(el).css("transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
}
else {
var angle = 0;
}
if(angle < 0)
angle +=360;
this.angle = angle;
thi.rad = this.angle*Math.PI/180;
//Aspect Ratio
this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
cursor = $(el).find(".ui-resizable-" + this.axis).css("cursor");
$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
var cornerItem = 0;
if(this.axis == 'ne')
cornerItem = 3;
else if(this.axis == 'nw')
cornerItem = 2;
else if(this.axis == 'sw')
cornerItem = 1;
else if(this.axis == 'se')
cornerItem = 0;
this.cornerItem = cornerItem;
var t1 = this.position.top;
var l1 = this.position.left;
var w1 = this.size.width;
var h1 = this.size.height;
var midX = l1 + w1/2;
var midY = t1 + h1/2;
var cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX];
var cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY];
var newX = 1e10;
var newY = 1e10;
for (var i=0; i<4; i++) {
if(i == this.cornerItem){
this.prevX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX;
this.prevY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY;
}
}
el.addClass("ui-resizable-resizing");
this._propagate("start", event);
return true;
},
_mouseDrag: function(event) {
//Increase performance, avoid regex
var data,
el = this.helper, props = {},
smp = this.originalMousePosition,
a = this.axis,
prevTop = this.position.top,
prevLeft = this.position.left,
prevWidth = this.size.width,
prevHeight = this.size.height;
dx1 = (event.pageX-smp.left)||0,
dy1 = (event.pageY-smp.top)||0;
dx = ((dx1)*Math.cos(this.rad) + (dy1)*Math.sin(this.rad));
dy =((dx1)*Math.sin(this.rad) - (dy1)*Math.cos(this.rad));
el = this.element;
var t1 = this.position.top;
var l1 = this.position.left;
var w1 = this.size.width;
var h1 = this.size.height;
var midX = l1 + w1/2;
var midY = t1 + h1/2;
var cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX];
var cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY];
var newX = 1e10 , newY = 1e10 , curX =0, curY=0;
for (var i=0; i<4; i++) {
if(i == this.cornerItem){
newX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX;
newY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY;
curX = newX - this.prevX;
curY = newY - this.prevY;
}
}
trigger = this._change[a];
if (!trigger) {
return false;
}
// Calculate the attrs that will be change
data = trigger.apply(this, [event, dx, dy]);
// Put this in the mouseDrag handler since the user can start pressing shift while resizing
this._updateVirtualBoundaries(event.shiftKey);
if (this._aspectRatio || event.shiftKey) {
data = this._updateRatio(data, event);
}
data = this._respectSize(data, event);
this._updateCache(data);
// plugins callbacks need to be called first
this._propagate("resize", event);
this.position.left = this.position.left - curX;
this.position.top = this.position.top - curY;
if (this.position.top !== prevTop) {
props.top = this.position.top + "px";
}
if (this.position.left !== prevLeft) {
props.left = this.position.left + "px";
}
if (this.size.width !== prevWidth) {
props.width = this.size.width + "px";
}
if (this.size.height !== prevHeight) {
props.height = this.size.height + "px";
}
el.css(props);
if (!this._helper && this._proportionallyResizeElements.length) {
this._proportionallyResize();
}
// Call the user callback if the element was resized
if ( ! $.isEmptyObject(props) ) {
this._trigger("resize", event, this.ui());
}
return false;
},
_mouseStop: function(event) {
this.resizing = false;
var pr, ista, soffseth, soffsetw, s, left, top,
o = this.options, that = this;
if(this._helper) {
pr = this._proportionallyResizeElements;
ista = pr.length && (/textarea/i).test(pr[0].nodeName);
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
soffsetw = ista ? 0 : that.sizeDiff.width;
s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
if (!o.animate) {
this.element.css($.extend(s, { top: top, left: left }));
}
that.helper.height(that.size.height);
that.helper.width(that.size.width);
if (this._helper && !o.animate) {
this._proportionallyResize();
}
}
$("body").css("cursor", "auto");
this.element.removeClass("ui-resizable-resizing");
this._propagate("stop", event);
if (this._helper) {
this.helper.remove();
}
return false;
},
_change: {
e: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;
if(this.axis == 'se'){
elwidth = this.originalSize.width + dx;
elheight = this.originalSize.height - dy;
return { height: elheight , width: elwidth };
}
else{
elwidth = this.originalSize.width + dx;
elheight = this.originalSize.height + dy;
return { height: elheight , width: elwidth };
}
},
w: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;
if(this.axis == 'nw'){
elwidth = cs.width - dx;
elheight = this.originalSize.height + dy;
return { height: elheight , width: elwidth };
}
else{
elwidth = cs.width - dx;
elheight = this.originalSize.height - dy;
return { height: elheight , width: elwidth };
}
},
n: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;
if(this.axis == 'nw'){
elwidth = this.originalSize.width - dx;
elheight = cs.height + dy;
return { height: elheight , width: elwidth };
}
else{
elwidth = this.originalSize.width + dx;
elheight = cs.height + dy;
return { height: elheight , width: elwidth };
}
},
s: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;
if(this.axis == 'se'){
elwidth = this.originalSize.width + dx;
elheight = this.originalSize.height - dy;
return { height: elheight , width: elwidth };
}
else {
elwidth = this.originalSize.width - dx;
elheight = this.originalSize.height - dy;
return { height: elheight , width: elwidth };
}
},
se: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
sw: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
},
ne: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
nw: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
}
},
A: The mouse movements for the handles have not been rotated with the element.
If you select the right handle (which will be near the bottom if you use rotate(77deg), moving it left will shrink the width of the element, (which will appear similar to the height due to the rotation.)
To adjust the element size relative to its center, you will most probably have to update the code that resizes the element by vectoring the mouse movements to adjust the width/height. | unknown | |
d15890 | val | use following way,
DriverManager.getConnection("jdbc:ucanaccess://path_to_your_db_file", your_user, your_password);
or
DriverManager.getConnection("jdbc:ucanaccess://path_to_your_db_file;password=your_password"); | unknown | |
d15891 | val | This is what you need to do; replace Typography with your component
<ListItemText
disableTypography
primary={
<Typography>Pedroview</Typography>
}
/> | unknown | |
d15892 | val | $.fn.incromentor.defaults = {} will overwrite your default options, so something else such as more_text, less_text is turned to undefined. Your Users should pass their options into the constructor such as
$('#myel').Incrementor({ max : 65355, min : 0});
--
$this to $(this) http://jsfiddle.net/KDXa6/1/ | unknown | |
d15893 | val | The concept of destructor is applicable only to objects (i.e. entities defined with class or struct), not to plain types, like a pointer is. A pointer lives just like a int variable does.
A: The pointer it self doesn't been destructed by the delete statement. but as any scope variable it's been destroyed when the scope ends.
Example:
void Function()
{
string * str=new string;
delete str; // <-- here the string is destructed
} // <-- here the pointer is "destructed", which is mean it's memory freed from the stuck but no actual destruction function is called..
A: delete just causes the object that the given pointer is pointing at to be destroyed (in this case, the string object. The pointer itself, denoted by str, has automatic storage duration and will be destroyed when it goes out of scope like any other local variable.
Note, however, that non-class types do not have destructors. So even when you use delete with non-class types, no destructor is called, but when the pointer goes out of scope, it gets destroyed as normally happens with any other automatic variable (means the pointer just reaches the end of its lifetime, though the memory pointed to by the pointer is not deallocated until you use delete to explicitly deallocate it.).
A:
when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?
No. delete takes a pointer argument. It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to. You must previously have used new to allocate the memory and create the object there.
The pointer itself is not affected; but it no longer points to a valid object, so you mustn't do anything with it. This is sometimes known as a "dangling pointer".
What would the pointer's destructor do?
Nothing. Only class types have destructors.
A: The destructor for a raw pointer, like your example of std::string*, is trivial (just like the destructors for other primitive types: int, double, etc.)
Smart pointer classes have non-trivial destructors that do things like free resources, adjust reference counts, etc.
A: I like the simplification you get from the notion that every type has a destructor. That way you don't have a mental glitch with a template that explicitly destroys a stored value, even if the type of that stored value is an int or a pointer:
template <class T> struct wrapper {
unsigned char data[sizeof(T)];
wrapper(T t) { ptr = new (data) T; }
~wrapper() { (T*)&data->~T(); } // ignore possible alignment problem
wrapper<int> i(3);
However, the destructors for ints and pointers are utterly trivial: they don't do anything, and there is no place you can go to see the definition of the destructor, because the definition doesn't exist. So it's also reasonable to say that they don't have destructors.
Either way, when a pointer goes out of scope it simply disappears; no special code runs. | unknown | |
d15894 | val | If you are not scraping a large set of data. I will suggest to you to use selenium. With selenium actually you can click the button. You can begin with scraping with R programming and selenium.
You can also use PhantomJS. It is also like selenium but no browser required.
I hope one of them will help. | unknown | |
d15895 | val | It looks like the issue may be related to they way that your user variable is not a piece of reactive stateful data. There isn't quite enough code in your question for us to determine that for sure, but it looks like you are close to grasping the right way to do it in Vue.
I think my solution would be something like this...
export default {
data() {
return {
user: null,
}
},
methods: {
loadUser() {
let user = null;
if (localStorage.getItem("user")) {
const obj_user = localStorage.getItem("user");
user = JSON.parse(obj_user);
}
this.user = user;
}
},
created() {
this.loadUser();
}
}
I save the user in the data area so that the template will react to it when the value changes.
The loadUser method is separated so that it can be called from different places, like from a user login event, however I'm making sure to call it from the component's created event.
In reality, I would tend to put the user into a Vuex store and the loadUser method in an action so that it could be more globally available. | unknown | |
d15896 | val | As with many usage analytics solutions, there is a large body of features/capabilities that are common (at least from 10K feet), and have many smaller differences when examined closely.
However, there are few fundamental differences in approaches between App Insights and Preemptive:
*
*AI is SaaS offering, Preemptive is a "box" product (I believe they are also offer cloud-hosted version). This also assumes different pricing models
*Main instrumentation model for Preemptive is through code injection (potentially as part of obfuscation process). AI offers a sophisticated SDK and tight integration into Visual Studio IDE. Preemptive also has an SDK
*AI offers Usage Analytics as part of the broader Application Performance and Analytics offering. AI is capable of capturing a wider range of telemetry information, including traces, exceptions (Preemptive does it too), metrics, dependencies, etc. and also enables both metric and log analyst. Preemptive is more focused | unknown | |
d15897 | val | It looks like you are loading the jquery library in three places in your document?
Why not add it to the asset pipeline?
In app/assets/javascripts/application.js:
//= require jquery
This should speed up pageloads and you won't have to include the script tags on every page.
A: OK, here's what I did to get it working: removed the line:
<%= javascript_include_tag "jquery" %>
which generates the offending line, from [appdir]/app/views/shared/_bootstrap2.html.erb (which generates the lines in the footer)
and put it into [appdir]/app/views/shared/_bootstrap.html.erb (which generates the lines in the header).
This isn't ideal since it means we're loading jquery before loading the rest of the page, so I'm still interested in a slicker solution. | unknown | |
d15898 | val | Forget about "mocking the for loop", that makes no sense since it is part of the functionality you want to test; specifically, when you unit test class XQ, you never mock any portion of class XQ.
you need to mock the following:
*
*Individual.getId for the patient.
*Individual.getId for the doctor.
*whatever methods on the Individual class that are used by getPatientInfo method, for the patient.
*whatever methods on the Individual class that are used by the getDoctorInfo method, for the doctor.
*caseDetailDao.fetchCaseIDs
*caseDetailDao.fetchServiceHistory
*caseHistory.getCreateDate, if you return a list of mock objects from fetchCaseIds.
*caseHistory.getEventId, if you return a list of mock objects from fetchCaseIds.
You have some terrible code:
*
*caseHsitory.fetchCaseIds is clearly not returning caseIDs, it is returning case details. | unknown | |
d15899 | val | mysql_real_escape_string only escapes values so that your queries don't break, it also protects against SQL injection if used correctly.
If you don't want certain characters you will need to use additional functions to strip them before you apply mysql_real_escape_string.
[insert obligatory "use prepared statements" comment]
Ex:
$string = "My name is
John";
$filtered_string = str_replace("\n", " ", $string); // filter
$escaped = mysql_real_escape_string($filtered_string); // sql escape
mysql_query("INSERT INTO `messages` SET `message` = '" . $escaped . "'");
A: You should be able to use str_replace to help with this:
mysql_real_escape_string(str_replace(array("\n", "\r\n", "\x00", '"', '\''), '', $input));
Having said that, it is a good idea to switch to mysqli or PDO for database read / write. Both of these allow prepared statements, which reduce the risk of SQL injections.
Here's an example of PDO:
$stmt = $PDOConnection->prepare('INSERT INTO example_table (input_field) VALUES (:input_field)');
$stmt->bindParam(':input_field', $input);
$stmt->execute(); | unknown | |
d15900 | val | Quoting from the docs here
When an API is integrated with an AWS service (for example, AWS
Lambda) in the back end, API Gateway must also have permissions to
access integrated AWS resources (for example, invoking a Lambda
function) on behalf of the API caller. To grant these permissions,
create an IAM role of the AWS service for API Gateway type. When you
create this role in the IAM Management console, this resulting role
contains the following IAM trust policy that declares API Gateway as a
trusted entity permitted to assume the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "apigateway.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
} | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.