_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d13701 | train | I think the function you are looking for is b2Body::GetLinearVelocityFromWorldPoint
https://code.google.com/p/box2d/source/browse/trunk/Box2D/Box2D/Dynamics/b2Body.h#273
You can get the 'world point' of the end of the gun barrel with b2Body::GetWorldPoint.
To find the direction of the gun in world coordinates, b2Body::GetWorldVector might be useful.
A: I'm answering my own question after some research.
*
*If a body is used without any fixtures, be sure to set some mass to it manually, otherwise it'll behave unexpected. After doing so, the muzzle body's paramaters were exactly I was about using them. Here's how to set mass to a body without any fixtures.
b2MassData md;
md.center = b2Vec2(0,0);
md.I = 0.000001f;
md.mass = 0.000001f;
body->SetMassData(&md);
*An other solution might be the one iforce2d posted. Thanks for that, I'll check it out! | unknown | |
d13702 | train | Proguard is either removing or renaming the field, since it doesn't know about any access done via reflection. That's why it fails at runtime.
You should probably add a -keep (or -keepnames) rule to prevent this.
A: I stumbled across the same issue but the provided proguard changes did not do it for me. I guess because I use the new play services ('com.google.android.gms:play-services-maps:7.0.0') and they probably have a different internal structure
What worked for me was:
-keep class com.google.android.gms.** { *; } | unknown | |
d13703 | train | Since I have found answer. I thought I will post it here. May be someone will find it useful -
import subprocess
from subprocess import PIPE
from subprocess import Popen
amount = ['23.5', '12.5', '56.0', '176.1']
invoice_no = ['11290', '12892', '12802', '23489']
date = ['2/3/19', '12/30/17', '04/21/2018', '8/12/17', '12/21/18']
for i in range (0, len(invoice_no)):
proc = subprocess.Popen(['java', '-jar', '/data/python/xyz.jar', invoice_no[i], date[i], amount[i]],stdin=PIPE,stdout=PIPE, stderr=PIPE)
output = proc.communicate()[0] ## this will capture the output of script called in the parent script. | unknown | |
d13704 | train | There is no equivalent, but you could use socketpair to create a Unix socket instead.
A: If your ultimate goal is to avoid signals altogeather, you can use init and cleanup functions as described here
Also see good example here:
Automatically executed functions when loading shared libraries
Just write an init function that handles the signals you wish to avoid and every program that loads your library will automatically have your handlers
I must say this is a strange necessity though, can you be more specific about the actual problem you're trying to solve? | unknown | |
d13705 | train | Late answer but hopefully someone will find it useful.
One way to run it is to download DOSBox, it is an emulator of old-timer DOS. Since you are mentioning Code View, I am guessing that you are using MASM as well so short instructions how to run it would be as follows:
*
*Run DOSBox
*In the console, write something like 'mount D C:/masm' where 'masm' is a folder where you have stored your compiler and Code View (cv.exe)
*Next is command 'D:' which will make you inside your 'masm' folder
*Compile it - 'masm myfile.asm'
*Link it - 'link myfile'
*Finally, debug in the Code View 'cv myfile.exe' | unknown | |
d13706 | train | IIUC, using diff + cumsum create the groupkey , then do agg
m1=df.Size.diff().ne(0)
m2=df.Size.ne(0)
df.groupby((m1|m2).cumsum()).agg({'Account':['first','last'],'Size':'first'})
Out[97]:
Size Account
first first last
Size
1 0 11120011 11130212
2 1 21023123 21023123
3 2 22109832 22109832
4 2 28891902 28891902
5 0 33390909 34490909
A: Late to the party but I think this also works.
df['Account End'] = df.shift(-1)[(df.Size == 0)]['Account']
Still in the learning phase for pandas, if this is bad for any reason let me know. Thanks. | unknown | |
d13707 | train | See my answer to a similar question. Instead of -webViewDidFinishLoad you should consider calling this using a timer (and checking whether something has been loaded, first).
If the HTML is under your control, you might wanna call it using a JavaScipt onLoad handler that tries to fetch a custom URL that you can intercept in -webView:shouldStartLoadWithRequest:navigationType:. | unknown | |
d13708 | train | Here is my Dockerfile:
FROM couchbase
COPY configure-cluster.sh /opt/couchbase
CMD ["/opt/couchbase/configure-cluster.sh"]
and configure-cluster.sh
/entrypoint.sh couchbase-server &
sleep 10
curl -v -X POST http://127.0.0.1:8091/pools/default -d memoryQuota=300 -d indexMemoryQuota=300
curl -v http://127.0.0.1:8091/node/controller/setupServices -d services=kv%2Cn1ql%2Cindex
curl -v http://127.0.0.1:8091/settings/web -d port=8091 -d username=Administrator -d password=password
curl -v -u Administrator:password -X POST http://127.0.0.1:8091/sampleBuckets/install -d '["travel-sample"]'
This configures the Couchbase server but still debugging how to bring Couchbase back in foreground.
Complete details at: https://github.com/arun-gupta/docker-images/tree/master/couchbase
A: It turns out that if I do the curls after restarting the server, those work. Go figure! That said, note that the REST API for installing sample buckets is undocumented as far as I know. arun-gupta's blog and his answer here are the only places where I saw any mention of a REST call for installing sample buckets. There's a python script available but that requires installing python-httplib2.
That said, arun-gupta's last curl statement may be improved upon as follows:
if [ -n "$SAMPLE_BUCKETS" ]; then
IFS=',' read -ra BUCKETS <<< "$SAMPLE_BUCKETS"
for bucket in "${BUCKETS[@]}"; do
printf "\n[INFO] Installing %s.\n" "$bucket"
curl -sSL -w "%{http_code} %{url_effective}\\n" -u $CB_USERNAME:$CB_PASSWORD --data-ascii '["'"$bucket"'"]' $ENDPOINT/sampleBuckets/install
done
fi
where SAMPLE_BUCKETS can be a comma-separated environment variable, possible values being combinations of gamesim-sample, beer-sample and travel-sample. The --data-ascii option keeps curl from choking on the dynamically created JSON.
Now if only there was an easy way to start the server in the foreground. :) | unknown | |
d13709 | train | jsonObj is an array thus you first have to iterate this array
jsonObj.forEach(o => {...});
o is now an object. You have to iterate the keys/values of it
for(let k in o)
k is a key in the object. You can now alter the value
o[k] = 'WhateverYouNeed'
var jsonObj = [{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}];
jsonObj.forEach(o => {
for(let k in o)
o[k] = 'ChangedValue'
});
console.log(jsonObj);
References:
As stated, your structure is an array of objects and not JSON: Javascript object Vs JSON
Now breaking you problem into parts, you need to
*
*Update property of an object: How to set a Javascript object values dynamically?
*But you need to update them all: How do I loop through or enumerate a JavaScript object?
*But these objects are inside an array: Loop through an array in JavaScript
*But why do I have different mechanism to loop for Objects and Arrays? for cannot get keys but we can use for..in over arrays. Right? No, you should not. Why is using "for...in" with array iteration a bad idea?
ReadMe links:
Please refer following link and check browser compatibility as the solution will not work in older browsers. There are other ways to loop which are highlighted in above link. Refer compatibility for them as well before using them.
*
*Arrow functions
*Array.forEach
A: You might want to use a mixture of forEach and Object.keys
const jsonObj = [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
];
jsonObj.forEach( obj => {
Object.keys( obj ).forEach( key => {
const value = obj[ key ];
console.log( key, value );
} );
} );
A: Here you go with a solution https://jsfiddle.net/Lha8xk34/
var jsonObj = [{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}];
$.each(jsonObj, function(i) {
$.each(jsonObj[i], function(key) {
jsonObj[i][key] = "changed" + key;
});
});
console.log(jsonObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A: Try pinch
in your Case :
var jsonObj = [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
];
pinch(data, "/key1/", function(path, key, value) {
return (value === "value1") ? "updatedValue" : value;
}); | unknown | |
d13710 | train | I suggest:
while [[ $(wmctrl -l | grep "Mozilla Firefox" 2>&1 | wc -l) -eq 0 ]]; do | unknown | |
d13711 | train | No, there is no way to test the admob code in the desktop version. There are some platform specific things that are not available on the desktop version. This includes the admob view and other Android specific dependencies. I recommend to either try to get the emulator up running, or to find some way to test on a phone. The best is probably to do both. | unknown | |
d13712 | train | Hiding and showing the tabs (ie a tab for an open access object - ie a form, query, report, etc) is a setting for the current database project, that only takes effect once the database file is closed and re-opened. Although the value can be set by code, it is not practical as it would apply to all users who then open the the file. (and you would need to set it, close, repoen ...)
You might like to have two copies of the database front end file held on a server with windows file permissions such that admin opens a different file to plebs, the admin file shows the tabs and other users open a file that doesn't. | unknown | |
d13713 | train | Is a parent directive in a pom definitely preventing a project from being used as a maven module
No. In the end a parent is simply used to inherit stuff and it can refer to any parent. In a multimodule project parents and children point to each other (child refers to a parent, parent defines child as a module).
On the other hand: you might wonder why it is a problem that any project is used as a module. The writer of the aggregator pom probably had a reason for it.
Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored?
It shouldn't be ignored, it must be set correctly, i.e. use <relativePath></relativePath> (empty String) in the parent. | unknown | |
d13714 | train | That wasn't a "problem". It was only a "message" and not even a particularly dangerous message. It was telling you that the vegan package had a function of the same name as another function in the pls package. If you know that you will be using the scores function with the syntax of the pls::scores function at a later time, then you will need to use it with that form. If you just use scores you will get the function as it exists in pkg:vegan.
I'm being mute about the second part (although it may be premised incorrectly on your anxiety about the message, in which case the question is moot). Multipart questions are discouraged on SO.
A: To answer your question about Rcmdr plugin for NMDS: check BiodiversityR package that provides an Rcmdr GUI to a part of vegan (plus more). | unknown | |
d13715 | train | What about...
*
*Regex to match : class=\"[A-Za-z0-9_\-]+\"
*Replace with : class=\"\"
This way, we ignore the first part (id="Specs", etc) and
just replace the class name... with nothing.
A: Looks like another case of http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html. What happens to the following valid tags with a Regex?
<div class="reversed" id="Specs">
<div id="Specs" class="additionalSpaces" >
<div id="Specs" class="additionalAttributes" style="" >
I don't see a how using Linq2Xml wouldn't work with any combination:
XElement root = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
var specsDivs = root.Descendants()
.Where(e => e.Name == "div"
&& e.Attributes.Any(a => a.Name == "id")
&& e.Attributes.First(a => a.Name == "id").Value == "Specs"
&& e.Attributes.Any(a => a.Name == "class"));
foreach(var div in specsDivs)
{
div.Attributes.First(a => a.Name == "class").value = string.Empty;
}
string newXml = root.ToString()
A: If your input isn't XML compliant, which most HTML isn't, then you can use the HTML Agility Pack to parse the HTML and manipulate the contents. With the HTML Agility PAck, combined with Linq or Xpath, the order of your attributes no longer matters (which it does when you use Regex) and the overall stability of your solution increases a lot.
Using the HTML Agility Pack (project page, nuget), this does the trick:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("your html here");
// or doc.Load(stream);
var nodes = doc.DocumentNode.DescendantNodes("div").Where(div => div.Id == "Specs");
foreach (var node in nodes)
{
var classAttribute = node.Attributes["class"];
if (classAttribute != null)
{
classAttribute.Value = string.Empty;
}
}
var fixedText = doc.DocumentNode.OuterHtml;
//doc.Save(/* stream */); | unknown | |
d13716 | train | The following code will give you the pattern for the locale:
final String pattern1 = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale)).toPattern();
System.out.println(pattern1);
A: Java 8 provides some useful features out of the box for working with and formatting/parsing date and time, including handling locales. Here is a brief introduction.
Basic Patterns
In the simplest case to format/parse a date you would use the following code with a String pattern:
DateTimeFormatter.ofPattern("MM/dd/yyyy")
The standard is then to use this with the date object directly for formatting:
return LocalDate.now().format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
And then using the factory pattern to parse a date:
return LocalDate.parse(dateString, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
The pattern itself has a large number of options that will cover the majority of usecases, a full rundown can be found at the javadoc location here.
Locales
Inclusion of a Locale is fairly simple, for the default locale you have the following options that can then be applied to the format/parse options demonstrated above:
DateTimeFormatter.ofLocalizedDate(dateStyle);
The 'dateStyle' above is a FormatStyle option Enum to represent the full, long, medium and short versions of the localized Date when working with the DateTimeFormatter. Using FormatStyle you also have the following options:
DateTimeFormatter.ofLocalizedTime(timeStyle);
DateTimeFormatter.ofLocalizedDateTime(dateTimeStyle);
DateTimeFormatter.ofLocalizedDateTime(dateTimeStyle, timeStyle);
The last option allows you to specify a different FormatStyle for the date and the time. If you are not working with the default Locale the return of each of the Localized methods can be adjusted using the .withLocale option e.g
DateTimeFormatter.ofLocalizedTime(timeStyle).withLocale(Locale.ENGLISH);
Alternatively the ofPattern has an overloaded version to specify the locale too
DateTimeFormatter.ofPattern("MM/dd/yyyy",Locale.ENGLISH);
I Need More!
DateTimeFormatter will meet the majority of use cases, however it is built on the DateTimeFormatterBuilder which provides a massive range of options to the user of the builder. Use DateTimeFormatter to start with and if you need these extensive formatting features fall back to the builder.
A: Please find in the below code which accepts the locale instance and returns the locale specific data format/pattern.
public static String getLocaleDatePattern(Locale locale) {
// Validating if Locale instance is null
if (locale == null || locale.getLanguage() == null) {
return "MM/dd/yyyy";
}
// Fetching the locale specific date pattern
String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
DateFormat.SHORT, locale)).toPattern();
// Validating if locale type is having language code for Chinese and country
// code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
if (locale.toString().equalsIgnoreCase("zh_hk")) {
// Expected application Date Format for Chinese (Hong Kong) locale type
return "yyyy'MM'dd";
}
// Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd").replaceAll(
"M{1,2}", "MM").replaceAll("y{1,4}|Gy", "yyyy");
// Replacing all blank spaces in the locale date pattern
localeDatePattern = localeDatePattern.replace(" ", "");
// Validating the date pattern length to remove any extract characters
if (localeDatePattern.length() > 10) {
// Keeping the standard length as expected by the application
localeDatePattern = localeDatePattern.substring(0, 10);
}
return localeDatePattern;
}
A: For SimpleDateFormat, You call toLocalizedPattern()
EDIT:
For Java 8 users:
The Java 8 Date Time API is similar to Joda-time. To gain a localized pattern we can use class
DateTimeFormatter
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
Note that when you call toString() on LocalDate, you will get date in format ISO-8601
Note that Date Time API in Java 8 is inspired by Joda Time and most solution can be based on questions related to time.
A: For those still using Java 7 and older:
You can use something like this:
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String pattern = ((SimpleDateFormat)formatter).toPattern();
String localPattern = ((SimpleDateFormat)formatter).toLocalizedPattern();
Since the DateFormat returned From getDateInstance() is instance of SimpleDateFormat.
Those two methods should really be in the DateFormat too for this to be less hacky, but they currently are not.
A: It may be strange, that I am answering my own question, but I believe, I can add something to the picture.
ICU implementation
Obviously, Java 8 gives you a lot, but there is also something else: ICU4J. This is actually the source of Java original implementation of things like Calendar, DateFormat and SimpleDateFormat, to name a few.
Therefore, it should not be a surprise that ICU's SimpleDateFormat also contains methods like toPattern() or toLocalizedPattern(). You can see them in action here:
DateFormat fmt = DateFormat.getPatternInstance(
DateFormat.YEAR_MONTH,
Locale.forLanguageTag("pl-PL"));
if (fmt instanceof SimpleDateFormat) {
SimpleDateFormat sfmt = (SimpleDateFormat) fmt;
String pattern = sfmt.toPattern();
String localizedPattern = sfmt.toLocalizedPattern();
System.out.println(pattern);
System.out.println(localizedPattern);
}
ICU enhancements
This is nothing new, but what I really wanted to point out is this:
DateFormat.getPatternInstance(String pattern, Locale locale);
This is a method that can return a whole bunch of locale specific patterns, such as:
*
*ABBR_QUARTER
*QUARTER
*YEAR
*YEAR_ABBR_QUARTER
*YEAR_QUARTER
*YEAR_ABBR_MONTH
*YEAR_MONTH
*YEAR_NUM_MONTH
*YEAR_ABBR_MONTH_DAY
*YEAR_NUM_MONTH_DAY
*YEAR_MONTH_DAY
*YEAR_ABBR_MONTH_WEEKDAY_DAY
*YEAR_MONTH_WEEKDAY_DAY
*YEAR_NUM_MONTH_WEEKDAY_DAY
*ABBR_MONTH
*MONTH
*NUM_MONTH
*ABBR_STANDALONE_MONTH
*STANDALONE_MONTH
*ABBR_MONTH_DAY
*MONTH_DAY
*NUM_MONTH_DAY
*ABBR_MONTH_WEEKDAY_DAY
*MONTH_WEEKDAY_DAY
*NUM_MONTH_WEEKDAY_DAY
*DAY
*ABBR_WEEKDAY
*WEEKDAY
*HOUR
*HOUR24
*HOUR_MINUTE
*HOUR_MINUTE_SECOND
*HOUR24_MINUTE
*HOUR24_MINUTE_SECOND
*HOUR_TZ
*HOUR_GENERIC_TZ
*HOUR_MINUTE_TZ
*HOUR_MINUTE_GENERIC_TZ
*MINUTE
*MINUTE_SECOND
*SECOND
*ABBR_UTC_TZ
*ABBR_SPECIFIC_TZ
*SPECIFIC_TZ
*ABBR_GENERIC_TZ
*GENERIC_TZ
*LOCATION_TZ
Sure, there are quite a few. What is good about them, is that these patterns are actually strings (as in java.lang.String), that is if you use English pattern "MM/d", you'll get locale-specific pattern in return. It might be useful in some corner cases. Usually you would just use DateFormat instance, and won't care about the pattern itself.
Locale-specific pattern vs. localized pattern
The question intention was to get localized, and not the locale-specific pattern. What's the difference?
In theory, toPattern() will give you locale-specific pattern (depending on Locale you used to instantiate (Simple)DateFormat). That is, no matter what target language/country you put, you'll get the pattern composed of symbols like y, M, d, h, H, M, etc.
On the other hand, toLocalizedPattern() should return localized pattern, that is something that is suitable for end users to read and understand. For instance, German middle (default) date pattern would be:
*
*toPattern(): dd.MM.yyyy
*toLocalizedPattern(): tt.MM.jjjj (day = Tag, month = Monat, year = Jahr)
The intention of the question was: "how to find the localized pattern that could serve as hint as to what the date/time format is". That is, say we have a date field that user can fill-out using the locale-specific pattern, but I want to display a format hint in the localized form.
Sadly, so far there is no good solution. The ICU I mentioned earlier in this post, partially works. That's because, the data that ICU uses come from CLDR, which is unfortunately partially translated/partially correct. In case of my mother's tongue, at the time of writing, neither patterns, nor their localized forms are correctly translated. And every time I correct them, I got outvoted by other people, who do not necessary live in Poland, nor speak Polish language...
The moral of this story: do not fully rely on CLDR. You still need to have local auditors/linguistic reviewers.
A: You can use DateTimeFormatterBuilder in Java 8. Following example returns localized date only pattern e.g. "d.M.yyyy".
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null, IsoChronology.INSTANCE,
Locale.GERMANY); // or whatever Locale
A: Since it's just the locale information you're after, I think what you'll have to do is locate the file which the JVM (OpenJDK or Harmony) actually uses as input to the whole Locale thing and figure out how to parse it. Or just use another source on the web (surely there's a list somewhere). That'll save those poor translators.
A: Im not sure about what you want, but...
SimpleDateFormat example:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
Date date = sdf.parse("12/31/10");
String str = sdf.format(new Date());
A: You can try something like :
LocalDate fromCustomPattern = LocalDate.parse("20.01.2014", DateTimeFormatter.ofPattern("MM/dd/yy")) | unknown | |
d13717 | train | If you don't need to keep the data in those tables, you can run the following which will reset the table (THIS WILL REMOVE ANY DATA THERE) and restart the tables id to start at 1. THIS IS ONLY VIABLE IF YOU DON"T NEED THE DATA IN THAT TABLE!
ActiveRecord::Base.connection.execute("TRUNCATE TABLE table_name_here RESTART IDENTITY")
As far as why your tables are starting at that id value I would start by checking your migrations. Maybe somewhere in the code there is an "Alter Sequence" sql statement but again not sure. | unknown | |
d13718 | train | You don't need to change the table and its pojo. To get the hidden fields values those are not available to be bind in your ModelAttribute object, you can just simply declare that hidden field in the jsp inside your form with html input tag and make it hidden with required value.
Now in the controller function you need to have a parameter HttpServletRequest request and get the value of your hidden field say with name hdParam with request.getParameter("hdParam").
I hope this helps you. Cheers. | unknown | |
d13719 | train | You need a LEFT OUTER JOIN to accomplish this:
SELECT customers.customerID, customers.fName
FROM customers LEFT OUTER JOIN orders on customers.customerID = orders.customerID
WHERE orders.customerID IS NULL | unknown | |
d13720 | train | The simplest approach would be simply using signals, do note however that there is no way to actually guarantee that the processes will indeed run in parallel.
That's for the OS to decide. | unknown | |
d13721 | train | Ok. First, you must process your file with a huge line into shorter lines via the solution posted at this answer, that create the fields.txtfile.
After that, run this Batch file:
@echo off
setlocal EnableDelayedExpansion
rem Create a "NewLine" value
for %%n in (^"^
%Do NOT remove this line%
^") do (
rem Process fields.txt file
(for /F "delims=" %%a in (fields.txt) do (
set "field=%%a"
rem Remove closing ">"
set "field=!field:~0,-1!"
rem Split field into lines ending in quote-space
for /F "delims=" %%b in (^"!field:" ="%%~n!^") do echo %%b
)) > lines.txt
)
rem Process lines
set "data="
for /F "skip=2 delims=" %%a in (lines.txt) do (
set "tag=%%a"
if "!tag:~0,5!" equ "<node" (
rem Start of new node: show data of previous one, if any
if defined data (
echo text=!text!^|bounds=!bounds!
)
rem Define the data in the same line of "<node"
set !tag:* =!
set "data=1"
) else if "!tag:~0,6!" equ "</node" (
rem Show data of last node
echo text=!text!^|bounds=!bounds!
) else (
rem Define data
2> NUL set %%a
)
)
Output sample:
text=""|bounds="[0,0][1080,2076]"
text=""|bounds="[0,0][1080,2076]"
text=""|bounds="[0,108][1080,2076]"
text=""|bounds="[0,108][1080,2076]"
text=""|bounds="[0,108][1080,276]"
text=""|bounds="[0,108][168,276]"
A: Assuming file.xml is this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.facebook.katana" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[0,0][1080,2076]" />
<node index="0" text="Create account" resource-id="com.facebook.katana:id/(name removed)" class="android.widget.TextView" package="com.facebook.katana" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[168,108][533,264]" />
</hierarchy>
Do
[xml]$xml = get-content file.xml
$xml.hierarchy.node | select text,bounds
text bounds
---- ------
[0,0][1080,2076]
Create account [168,108][533,264]
Dumping out every "node" in that other file:
Select-Xml //node file2.xml | % node | select text,bounds
A: @Aacini . This is the content of the file lines.txt
<?xml version='1.0' encoding='UTF-8' standalone='yes'
<hierarchy rotation="0
<node index="0
text="
resource-id="
class="android.widget.FrameLayout
package="com.facebook.katana
content-desc="
checkable="false
checked="false
clickable="false
enabled="true
focusable="false
focused="false
scrollable="false
long-clickable="false
password="false
selected="false
bounds="[0,0][1080,2076]
A: You can give a try for this batch file :
@echo off
If exist output.txt Del output.txt
Powershell -C "$regex = [regex]'(text=\x22[\s\S]+?\x22)|(bounds=\x22[\s\S]+?\x22)';$data = GC "test.txt";ForEach ($m in $regex.Matches($data)) {$m.Value>>output.txt};"
If exist output.txt Start "" output.txt | unknown | |
d13722 | train | jsonobj = json.loads(text)
print jsonobj['data']
Will print the list in the data section of your JSON.
If you want to open each as a link after google.com, you could try this:
def processlinks(text):
output = urllib.urlopen('http://google.com/' % text)
print output.geturl()
print output.read()
map(processlinks, jsonobj['data'])
A: info = json.loads(text)
json_text = json.dumps(info["data"])
Using json.dumps converts the python data structure gotten from json.loads back to regular json text.
So, you could then use json_text wherever you were using text before and it should only have the selected key, in your case: "data".
A: Perhaps something like this where result is your JSON data:
from itertools import product
base_domains = ['http://www.google.com', 'http://www.example.com']
result = {"success":True,"code":200,"data":["Confidential","L1","Secret","Secret123","foobar","maret1","maret2","posted","rontest"],"errs":[],"debugs":[]}
for path in product(base_domains, result['data']):
print '/'.join(path) # do whatever
http://www.google.com/Confidential
http://www.google.com/L1
http://www.google.com/Secret
http://www.google.com/Secret123
http://www.google.com/foobar
http://www.google.com/maret1
http://www.google.com/maret2
http://www.google.com/posted
http://www.google.com/rontest
http://www.example.com/Confidential
http://www.example.com/L1
http://www.example.com/Secret
http://www.example.com/Secret123
http://www.example.com/foobar
http://www.example.com/maret1
http://www.example.com/maret2
http://www.example.com/posted
http://www.example.com/rontest | unknown | |
d13723 | train | Corrently I have solved the task by cutting last } from response text and adding ,"fieldname":"value"} to the end of it. Till someone would not share a better idea, it could help somebody else. | unknown | |
d13724 | train | My understanding of your problem is that you're using an Entity Field Type for $formnoseller and $formnobuyer (or you don't specify the type). Giving the choice to select any élément from the underlying table is the expected behaviour for the Entity Field Type (Used by default for OneToMany relationships)
If you don't whant a select list of all the elements of your table for those Fields, you should use an other form field type. You should also have a look at data transformers in the documentation.
A: If it were me, I would write a stored procedure and do an inner or outer join as appropriate.
Once upon a time, they called this "client server" code. About 15 years ago, it created such a mess the whole industry moved to n-tier development. I'd like to know how the table joins got placed back into the presentation tier again? ORMs and LINQ-to-SQL are a return to client/server".
If you have to do it this way, do the join in LINQ on the Models. Do not do it with the ORM language. | unknown | |
d13725 | train | The Winform controls with AutoComplete support are using IE's AutoComplete APIs, which does not support ACO_NOPREFIXFILTERING until Windows Vista. Since WinForm needs to support earlier systems, ACO_NOPREFIXFILTERING is not supported in .Net.
If you want to use this feature when it is available, you can skip Windows Form's AutoComplete support and call the API directly. | unknown | |
d13726 | train | Looks to me like you need an additional set of quotes around the argument for the parameter -l:
& "$scpath$script" -p "Error Logging into GFR" -l "`"$onepath$onefile`"" -c 1
Or try splatting the arguments:
$params = '-p', 'Error Logging into GFR',
'-l', "$onepath$onefile",
'-c', 1
& "$scpath$script" @params | unknown | |
d13727 | train | The reason why your elements aren't aligning is because the div element containing your heart animation is a block-level element (versus the i elements with the font-awesome icons, which are inline).
To fix that part, you just have to add display: inline-block to the heart element. The height of your heart element is also 70px, so to align the other elements, you'll also need to add height: 70px and line-height: 70px; to your post-footer. Finally, to adjust for the fact that the heart element is much wider than the other elements, you can wrap the heart counts in a span and give it a negative margin.
/* when a user clicks, toggle the 'is-animating' class */
$(".heart").on('click touchstart', function(){
$(this).toggleClass('is_animating');
});
/*when the animation is over, remove the class*/
$(".heart").on('animationend', function(){
$(this).toggleClass('is_animating');
});
.postfooter {
display: flex;
justify-content: flex-start;
color: #b3b3b3;
margin-top: 30px;
font-size: 25px;
height: 70px;
line-height: 70px;
}
.postfooter .fa {
margin-left: 40px;
}
.heart {
display: inline-block;
cursor: pointer;
height: 70px;
width: 70px;
background-image:url( 'https://abs.twimg.com/a/1446542199/img/t1/web_heart_animation.png');
background-position: left;
background-repeat:no-repeat;
background-size:2900%;
}
.heart-text {
margin-left: -20px;
}
.heart:hover {
background-position:right;
}
.is_animating {
animation: heart-burst .8s steps(28) 1;
}
@keyframes heart-burst {
from {background-position:left;}
to { background-position:right;}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<!-- Font-Awesome CDN -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div class="postfooter">
<div><i class="fa fa-reply" aria-hidden="true"> 2</i></div>
<div><i class="fa fa-retweet" aria-hidden="true"> 30</i></div>
<div class="heart"></div><span class="heart-text">16</span>
</div>
</body>
</html> | unknown | |
d13728 | train | I don't see any contradiction.
The property is made true by any Buchi automaton s.t.
*
*P is always false [because the premise of the implication is false], or
*At some point in the future P becomes true, yet for some time P may be false until R becomes true.
i.e.
In natural language, one would express that property as follows: "If, by any chance, sooner or later P becomes true, then it must be the case that the 'event' R fired first".
For instance, you can imagine P be "sending answer message" and R be "received input message" and the whole property be "no unsolicited answer message is ever sent". | unknown | |
d13729 | train | You will need to update you plugins to latest version, since as I assume you must have added ios as platform more recently and plugins would have been added 1.5 years ago.
So those plugins must have already been fetched into plugins directory 1.5 years ago and must be of lower version to whats recently available.
Also you must update your cordova version to latest. You update it by below command
npm install -g cordova@latest
You can fire below command inside you app directory from command line, to get names of plugins.
cordova plugins ls
Note down all plugins names. (e.g. cordova-plugin-splashscreen)
Remove each one of them by below command.
cordova plugin rm cordova-plugin-splashscreen
After all of them have been removed add them again using below command.
cordova plugin add cordova-plugin-splashscreen | unknown | |
d13730 | train | Implementation of the 2 step processes @sln mentioned in VBScript:
Option Explicit
Dim rCmt : Set rCmt = New RegExp
rCmt.Global = True
rCmt.Pattern = "<!-- @[\s\S]+?@-->"
Dim rKVP : Set rKVP = New RegExp
rKVP.Global = True
rKVP.Pattern = "(\w+)=""([^""]*)"""
Dim sInp : sInp = Join(Array( _
"<td class=""creditapp heading"">{*}Street Address:</td>" _
, "<td colspan=2 class=""tdaddressblock"">" _
, "<!-- @template=""addressBlock"" for=""buyer"" prev="""" @-->" _
, "</td>" _
, "<!-- @ pipapo=""i dont care""" _
, "rof=""abracadabra"" prev="""" @-->" _
), vbCrLf)
WScript.Echo sInp
WScript.Echo "-----------------"
WScript.Echo rCmt.Replace(sInp, GetRef("fnRepl"))
WScript.Quit 0
Function fnRepl(sMatch, nPos, sSrc)
Dim d : Set d = CreateObject("Scripting.Dictionary")
Dim ms : Set ms = rKVP.Execute(sMatch)
Dim m
For Each m In ms
d(m.SubMatches(0)) = m.SubMatches(1)
Next
fnRepl = "a comment containing " & Join(d.Keys)
End Function
output:
cscript 45200777-2.vbs
<td class="creditapp heading">{*}Street Address:</td>
<td colspan=2 class="tdaddressblock">
<!-- @template="addressBlock" for="buyer" prev="" @-->
</td>
<!-- @ pipapo="i dont care"
rof="abracadabra" prev="" @-->
-----------------
<td class="creditapp heading">{*}Street Address:</td>
<td colspan=2 class="tdaddressblock">
a comment containing template for prev
</td>
a comment containing pipapo rof prev
As Mr. Gates Doc for the .Replace method sucks, see 1, 2, 3. | unknown | |
d13731 | train | Found it!
In the AndroidManifest.xml there is a ReplaceMe tag in:
<meta-data android:name="com.google.android.gms.games.APP_ID"
android:value="ReplaceMe" />
There in strings.xml there is a string resource:
<string name="app_id">ReplaceMe</string>
Should replace the ReplaceMe :) with the app ID from the google play console.
Good luck!
A: If you do not want to pay google play console, you can set <string name="app_id">1</string> in strings.xml | unknown | |
d13732 | train | self.object does not make any sense in ListView.
If you want to get stay_time then you can do it in your model and access in template using object.stay_time and even you can calculate the amount in template by multiplying. But I You can even do it in detailview. Create a method in that model like
@property
def stay_time(self):
return (self.departure_date-self.allotment_date)
A: I was able to fix it by calling on form_valid function. I used the function on my BedDischarge class in my views. And was able to use self.object. Then made a template call in my templates.
@method_decorator(login_required, name='dispatch')
class BedDischarge(UpdateView):
model = BedAllotment
template_name = 'room/bed_discharge.html'
form_class = BedAllotmentUpdateForm
pk_url_kwarg = 'allotment_id'
success_url = reverse_lazy('patient_bed_list')
def get_context_data(self, **kwargs):
context = super(BedDischarge, self).get_context_data(**kwargs)
context['account_type'] = AccountUser.objects.get(user_id=self.request.user.id)
return context
def form_valid(self, form):
get_allot_id = self.object.id
bed_allot = BedAllotment.objects.get(id=get_allot_id)
start_time = bed_allot.allotment_date
end_time = form.instance.departure_date
cost = BedCreate.objects.get(id=self.object.bed_id).cost
days_spent = (end_time - start_time).days
amount = cost * days_spent
form.instance.days = days_spent
form.instance.amount = amount
return super(BedDischarge, self).form_valid(form) | unknown | |
d13733 | train | When returning the disposable objects, it should be the responsibility of the caller code to Dispose the object. Had the Disposed been called inside the method itself, the disposed object will return to the caller method, (wont be of any use).
In that case it is safe to supress the warning.
BUT what if the exception occurred in this method?
If a disposable object is not explicitly disposed before all
references to it are out of scope, the object will be disposed at some
indeterminate time when the garbage collector runs the finalizer of
the object. Because an exceptional event might occur that will prevent
the finalizer of the object from running, the object should be
explicitly disposed instead. MSDN
So, if you anticipate any exception in the method, you should have this code in try...catch block and in catch block you should call Dispose() checking if the object is not null.
And when you are not returning IDisposable you can use using statement or try...finally and call dispose in finally
A: Why are you keeping items in to different list variables? It may have something to do with your issue. Keep it DRY Store them in one list and safely cast to what you are looking for.
IDisposable myDispType = myEnumarableType as IDisposable;
If (myDispType != null)
{//your logic here} | unknown | |
d13734 | train | This seems to depend on the system, probably the python version. On my system, the difference is is about 13%:
python sum.py
208
208
('Version 1 time: ', 0.6371259689331055)
('Version 2 time: ', 0.7342419624328613)
The two version are not measuring sum versus manual looping because the loop "bodies" are not identical. ver2 does more work because it creates the generator expression 100000 times, while ver1's loop body is almost trivial, but it creates a list with 40 elements for every iteration. You can change the example to be identical, and then you see the effect of sum:
def ver1():
r = [Score[j][a[j]] for j in range(40)]
for i in xrange(100000):
total = 0
for j in r:
total+=j
print (total)
def ver2():
r = [Score[j][a[j]] for j in xrange(40)]
for i in xrange(100000):
total = sum(r)
print (total)
I've moved everything out of the inner loop body and out of the sum call to make sure that we are measuring only the overhead of hand-crafted loops. Using xrange instead of range further improves the overall runtime, but this applies to both versions and thus does not change the comparison. The results of the modified code on my system is:
python sum.py
208
208
('Version 1 time: ', 0.2034609317779541)
('Version 2 time: ', 0.04234910011291504)
ver2 is five times faster than ver1. This is the pure performance gain of using sum instead of a hand-crafted loop.
Inspired by ShadowRanger's comment on the question about lookups, I have modified the example to compare the original code and check if the lookup of bound symbols:
def gen(s,b):
for j in xrange(40):
yield s[j][b[j]]
def ver2():
for i in range(100000):
total = sum(gen(Score, a))
print (total)
I create a small custom generator which locally binds Score and a to prevent expensive lookups in parent scopes. Executing this:
python sum.py
208
208
('Version 1 time: ', 0.6167840957641602)
('Version 2 time: ', 0.6198039054870605)
The symbol lookups alone account for ~12% of the runtime.
A: Since j is iterating over both lists, I thought I'd see if zip worked any better:
def ver3():
for i in range(100000):
total = sum(s[i] for s,i in zip(Score,a))
print (total)
On Py2 this runs about 30% slower than version 2, but on Py3 about 20% faster than version 1. If I change zip to izip (imported from itertools), this cuts the time down to between versions 1 and 2. | unknown | |
d13735 | train | That's happening because you are trying to send a response to the client when you already closed the connection.
Hard to tell by the way you are showing us your code but it seems like you are redirecting to options and then in the same request you are redirecting to dashboard/it/model
A: I pull your code from github.
I think the error message was clear. in your getDefault() middleware you are rendering a response so the server start sending data to your client and just after you try to redirect him to another url. Thats why when your comment out that middleware all work nicely. | unknown | |
d13736 | train | TL;DR: (int)double always rounds towards zero. printf("%0.0lf", double) actually rounds to closest integer.
When you convert the double to int, then the result is rounded towards zero. E.g. (int)14.9999 is 14, not 15. Therefore your first example with pow() must have given you the result slightly below 15, therefore direct cast to int gives 14.
Now, when you use printf(), then other rules are used. Printf, when asked to print a double using smallest number of digits possible (%0.0lf) rounds it to the closest integer, therefore printf("%0.0lf", 14.666) prints 15. | unknown | |
d13737 | train | You have to assign the delegate in your first view controller.
Also, you have to change let delegate: modalViewControllerDelegate? to a var, or else you can't change it.
Right now your delegate is empty.
It's unclear how you're accessing ModalViewController. If you're using segues:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "modalViewControllerSegue" {
var destination = segue.destinationViewController as CategoryViewController
destination.delegate = self
}
}
Or if you're doing it programmatically:
var modalViewController = ModalViewController(parameters)
modalViewController.delegate = self
presentViewController(modalViewController, animated: true, completion: nil)
Storyboard identifier:
let destination = UIStoryboard.mainStoryboard().instantiateViewControllerWithIdentifier("ModalViewController") as ModalViewController
delegate = self
showViewController(destination, sender: nil)
EDIT:
If you want to access ModalViewController by selecting a cell you need the tableView: didSelectRowAtIndexPath method:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("modalViewControllerSegue", sender: self)
}
Using this, you'll need the method prepareForSegue to set the delegate.
A: You have to set your modalViewController's delegate property before presenting it. If you're using segues, you can do this in prepareForSegue(_:).
Also, class names should begin with uppercase letters (modalViewController should be ModalViewController). Only instances should begin with lowercase letters.
A: Another option, instead of using delegation, is to use an unwind segue. Here's a tutorial: http://www.cocoanetics.com/2014/04/unwinding/
In your case, in your presenting view controller you could have the method:
func returnFromModalView(segue: UIStoryboardSegue) {
// This is called when returning from the modal view controller.
if let modalVC = segue.sourceViewController as? ModalViewController
where segue.identifier == "mySegueID" {
let text = modalVC.textField.text
// Now do stuff with the text.
}
}
And then just link up everything in the Interface Builder as shown in the tutorial. | unknown | |
d13738 | train | This realizes the differential equation
angle''(t)+k*sin(angle(t))=0
Since they use the Euler forward method for integration, the system will actually increase its energy , measured as
E = 0.5*angle'(t)^2+k*(1-cos(angle)).
To add damping to the equation, you can simulate some air friction by setting
acceleration = -k*sin(angle)-c*velocity | unknown | |
d13739 | train | do you get the expected output when you set mapred.reduce.tasks=0? What if you specify -reducer 'cat' with mapred.reduce.tasks=1? One of the neat things about streaming is that you can test it pretty effectively from the command-line using pipes:
cat input | python mapper.py | sort | python reducer.py
but it seems like your app is not producing any output.
A: Not sure about the exact answer, but for me, once I ran it on cluster with machines having better storage, it just worked fine :) | unknown | |
d13740 | train | The following should work (please note that this also returns a promise that resolves to an array of movies).
const loadedTrendingMovies = await Promise.all(
trendingMovies.results
.slice(0, 5) // use slice instead of a loop
.map((trendingMovie) => // map movie to [language,movie]
getLanguageNamefromCode(// get async language
trendingMovie.original_language
// resolve to [language,movie]
).then((language) => [language, trendingMovie])
) // sorry, forgot to return here
).then((results) => // results is [[language,movie],[language,movie]]
results.map(
([language, trendingMovie]) =>
new Movie( // create new Movie
trendingMovie.id.toString(),
trendingMovie.media_type === 'movie'
? trendingMovie.title
: trendingMovie.name,
posterBaseUrl + trendingMovie.poster_path,
trendingMovie.media_type === 'movie'
? trendingMovie.release_date
: trendingMovie.first_air_date,
[],
trendingMovie.overview,
trendingMovie.vote_average,
language,
getState().UserMovies.userMovies.find(
(userMovie) =>
userMovie.id === trendingMovie.id.toString()
// if you don't have optional chaining you can get location
// first the way you did before
)?.location || ''
)
)
);
Working example
const trendingMovies = {
results: [
{
original_language: 1,
id: 1,
},
{
original_language: 2,
id: 2,
},
],
};
const getLanguageNamefromCode = (lang) =>
Promise.resolve(`language is: ${lang}`);
function Movie(id, language, location) {
this.id = id;
this.language = language;
this.location = location;
}
const getState = () => ({
UserMovies: {
userMovies: [{ id: '1', location: 'location 1' }],
},
});
Promise.all(
trendingMovies.results
.slice(0, 5) // use slice instead of a loop
.map((trendingMovie) =>
// map movie to [language,movie]
getLanguageNamefromCode(
// get async language
trendingMovie.original_language
// resolve to [language,movie]
).then((language) => [language, trendingMovie])
)
)
.then((
results // results is [[language,movie],[language,movie]]
) =>
results.map(([language, trendingMovie]) => {
const userMovie = getState().UserMovies.userMovies.find(
(userMovie) =>
userMovie.id === trendingMovie.id.toString()
// snippet does not have conditional chaining
);
return new Movie( // create new Movie
trendingMovie.id.toString(),
language,
userMovie ? userMovie.location : ''
);
})
)
.then((movies) => console.log('movies:', movies)); | unknown | |
d13741 | train | The answers to all of your questions are clearly stated in Microsoft's documentation.
CancelIoEx():
The CancelIoEx function allows you to cancel requests in threads other than the calling thread. The CancelIo function only cancels requests in the same thread that called the CancelIo function. CancelIoEx cancels only outstanding I/O on the handle, it does not change the state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the operation was completed successfully or canceled.
If there are any pending I/O operations in progress for the specified file handle, the CancelIoEx function marks them for cancellation. Most types of operations can be canceled immediately; other operations can continue toward completion before they are actually canceled and the caller is notified. The CancelIoEx function does not wait for all canceled operations to complete.
If the file handle is associated with a completion port, an I/O completion packet is not queued to the port if a synchronous operation is successfully canceled. For asynchronous operations still pending, the cancel operation will queue an I/O completion packet.
The operation being canceled is completed with one of three statuses; you must check the completion status to determine the completion state. The three statuses are:
*
*The operation completed normally. This can occur even if the operation was canceled, because the cancel request might not have been submitted in time to cancel the operation.
*The operation was canceled. The GetLastError function returns ERROR_OPERATION_ABORTED.
*The operation failed with another error. The GetLastError function returns the relevant error code.
GetQueuedCompletionStatus():
If the GetQueuedCompletionStatus function succeeds, it dequeued a completion packet for a successful I/O operation from the completion port and has stored information in the variables pointed to by the following parameters: lpNumberOfBytes, lpCompletionKey, and lpOverlapped. Upon failure (the return value is FALSE), those same parameters can contain particular value combinations as follows:
*
*If *lpOverlapped is NULL, the function did not dequeue a completion packet from the completion port. In this case, the function does not store information in the variables pointed to by the lpNumberOfBytes and lpCompletionKey parameters, and their values are indeterminate.
*If *lpOverlapped is not NULL and the function dequeues a completion packet for a failed I/O operation from the completion port, the function stores information about the failed operation in the variables pointed to by lpNumberOfBytes, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.
So, this means that CancelIoEx() will simply mark existing asynchronous operations for cancellation, and IF THE DRIVER ACTUALLY CANCELS THEM then completion statuses WILL be posted back to you indicating the operations were cancelled.
If GetQueuedCompletionStatus() returns TRUE, that means an I/O packet with a success status was dequeued.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NON-NULL OVERLAPPED* pointer, that means an I/O packet with a failure status was dequeued, so all of the output values are valid, and you can use GetLastError() to get the error code for that packet.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NULL OVERLAPPED* pointer, that means GetQueuedCompletionStatus() itself failed, so all of the output values are indeterminate and should be ignored, and you can use GetLastError() to get the error code for the failure.
A: GetQueuedCompletionStatus return when I/O finished. if initial code of I/O operation was ERROR_IO_PENDING and file bind to IOCP -when I/O finished - packet will be queued to IOCP and GetQueuedCompletionStatus return (for this I/O operation).
so question better be next:
Will I/O will be completed immediately if we call CancelIoEx on file ?
this already depend from concrete diver: are it registered cancel routine (IoSetCancelRoutine) on IRP for which he return STATUS_PENDING.
are this driver immediately IofCompleteRequest when it CancelRoutine called for IRP. any good designed driver must do both. so if you do I/O request on say some built-in windows driver - answer - yes - I/O will be completed immediately.
about error code - usually (almost always) this will be STATUS_CANCELLED - with this status driver complete canceled IRP. the GetQueuedCompletionStatus conver error NTSTATUS to win32 errors. so STATUS_CANCELLED will be converted to ERROR_OPERATION_ABORTED.
so if in short
Will GetQueuedCompletionStatus return immediately
yes (almost always, but depend from driver, from this api - nothing depend)
is there an appropropate error-code ?
yes - almost always this will be ERROR_OPERATION_ABORTED(but again depend from driver and not depend from this api) | unknown | |
d13742 | train | Add this to the control which triggers the redirect. I know this works for Buttons/LinkButtons, not sure if it will work on a checkbox though.
OnClientClick="aspnetForm.target ='_blank';"
A: One method you might consider:
Instead of doing the Redirect to each report inside the code behind - dynamically generate some JavaScript that has uses window.open for each report. The javascript would look similar to this:
<script type="text/javascript">
window.open("<report1URL>", "_blank");
window.open("<report2URL>", "_blank");
...
window.open("<reportNURL>", "_blank");
</script>
Then, instead of doing a Response.Redirect, you should be able to do a Respone.Write() to get the browser to execute the code.
string myJavaScript= <dynamicallyGenerateJavascript>;
Response.Write(myJavaScript); | unknown | |
d13743 | train | I joined StackOverflow just to reply to this question as I've also wasted time on this exact issue.
The fix is to update to the latest alpha01 version of ViewPager2.
implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"
See: https://developer.android.com/jetpack/androidx/releases/viewpager2#1.1.0-alpha01
Fixed FragmentStateAdapter issue with initial fragment menu visibility when adding a fragment to the FragmentManager. (I9d2ff, b/144442240)
A: I tried updating to the latest viewpager2 alpha as suggested in the currently accepted answer, but it didn't help.
I have seen answers to similar questions where they say to clear the entire menu first. That should work, too, but I have some menu items that are loaded in the Activity, which do not duplicate, and some that load in the fragment, which do duplicate. I want to keep the ones inflated in the Activity and remove only all the ones from all fragments (not just the current fragment, just in case).
My work-around, therefore, is to each time remove only the items added in all fragments, checking to make sure each is actually there (not null) before removing each one. Then, once those have been removed, I inflate the menu(s) needed for all/each fragment.
Note that the existing menu is removed item by item (R.id...) while the inflated one is added by menu (R.menu...) as usual.
In the below sample, the search menu will always be inflated, while the second menu to be inflated will depend on which fragment it currently active.
@Override public void onCreateOptionsMenu (@NonNull Menu menu, @NonNull MenuInflater
inflater)
{
super.onCreateOptionsMenu (menu, inflater);
removeMenuItemIfPresent (menu, R.id.menu_search);
removeMenuItemIfPresent (menu, R.id.menu_sample_filter1);
removeMenuItemIfPresent (menu, R.id.menu_sample_filter2);
inflater.inflate (R.menu.menu_search_menu, menu);
inflater.inflate (mCurrentSection == 0 ? R.menu.menu_frag0 : R.menu.menu_frag1, menu);
}
private void removeMenuItemIfPresent (@NonNull Menu menu, int resourceIDToRemove)
{
MenuItem menuItemToRemove = menu.findItem (resourceIDToRemove);
if (menuItemToRemove != null) {
menu.removeItem (menuItemToRemove.getItemId ());
}
}
A: I am not sure if it worked before but now im having issues with ViewPager2. When, I add fragments, each with different menuitems, the menuitem does not reflect on the first fragment added.
It works when offscreenpagelimit is not set. However, its performance is bad. Didnt have issues with ViewPager. | unknown | |
d13744 | train | You can make use of std::vector in the following manner:
std::vector<Student> my_students;
for (std::size_t i = 0; i < 3; i++) {
Student tmp;
in >> tmp;
my_students.push_back(tmp);
}
A: std::vector<Student> aVectOfStudents;
aVectOfStudents.emplace_back("","Jack", "4445554455");
aVectOfStudents.emplace_back("","Riti", "4445511111");
aVectOfStudents.emplace_back("","Aadi", "4040404011");
ofstream out("students.txt");
for(auto studIter = aVectOfStudents.begin(); studIter != aVectOfStudents.end(); ++studIter)
{
std::cout << "Insert Id for student: " << studIter->mName << "\n";
std::cin >> studIter->mId;
out<<*studIter;
}
out.close();
A: You could use the std::vector, to store the Student s and iterate through them to file out/inputs.
#include <vector>
int main()
{
// open the File
std::fstream file{ "students.txt" };
// vector of students
std::vector<Student> students{
{"1", "Jack", "4445554455"},
{ "4", "Riti", "4445511111"},
{"6", "Aadi", "4040404011"}
};
// iterate throut the objects and write objects(i.e. students) to the file
for(const auto& student: students)
file << student;
// reset the stream to the file begin
file.clear();
file.seekg(0, ios::beg);
// clear the vector and resize to the number of objects in the file
students.clear();
students.resize(3);
// read objects from file and fill in vector
for (Student& student : students)
file >> student;
file.close();
return 0;
} | unknown | |
d13745 | train | There is no limitation on the number of topics or subscriptions. There was a limitation of 1 million subscriptions for the first year after topics was initially launched but that restriction was removed at this year's (2016) Google I/O. FCM now supports unlimited topics and subscribers per app. See the docs for confirmation.
A: Topic messaging supports unlimited subscriptions for each topic. However, FCM enforces limits in these areas:
*
*One app instance can be subscribed to no more than 2000 topics.
*If you are using batch import to subscribe app instances, each request is limited to 1000 app instances.
*The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.
Check this
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging | unknown | |
d13746 | train | You can find the conflicting macro definitions by searching for differences between the preprocessed code generated for token.h with and without the #include <windows.h>.
For example, for "token.h", the errors occur at the definition of the enum Value so you have to look at the preprocessed definition of that enum in both cases. So with
#include <windows.h>
#include <token.h>
you get:
enum Value {
...
INSTANCEOF, , NOT, BIT_NOT, (0x00010000L), TYPEOF, void, BREAK,
...
SWITCH, void, THROW,
...
FUTURE_STRICT_RESERVED_WORD, const, EXPORT,
...
};
instead of:
enum Value {
...
INSTANCEOF, IN, NOT, BIT_NOT, DELETE, TYPEOF, VOID, BREAK,
...
SWITCH, THIS, THROW,
...
FUTURE_STRICT_RESERVED_WORD, CONST, EXPORT,
...
};
with only #include <token.h>. | unknown | |
d13747 | train | I want the other components to connect
to the GUI that's already running,
rather than start a new instance of
the exe.
The trick is to remember that in a ActiveX EXE it can be setup so that there is only one instance of the LIBRARY running. It is correct that you can't reach and just pluck a given instance of a class across process boundary. However the ActiveX EXE can be setup so that the GLOBAL variables are accessible by ANY instance of classes.
How to exactly to do this gets a little complex. You can use a ActiveX EXE as a normal EXE the main difference is that you HAVE to use Sub Main. You can also check to see if it run standalone or not. Now I am assuming this is the case with MarkJ's application.
If this is the case what you need to is create a application class and set it up so that that when it is created (by using Class_Initialize) that it is populated with the current running instances of forms and collections.
I strongly recommend that you create an ActiveX DLL (not EXE) that has nothing but classes to implemented as interfaces. Instead going of going
'Class ThisGUIApp
Public MainForm as Form
You create an interface that has all the properties and methods needed to access the elements of the mainform. Then you go
'Class ThisGUIApp
Public MainForm as IMainForm
Private Sub Class_Initialize
Set MainForm = frmMyMainForm
End Sub
'Form frmMyMainForm
Implements IMainForm
You do this because while you can send a Form across application process things get wonky when you try to access it members and controls. If you assigned via an interface then the connection is a lot more solid. Plus it better documents the type of things you are trying to do.
A: The documentation is confusing, but correct. The MSDN page you reference helps to explain why your GetObject call doesn't throw an error:
If pathname [the first argument] is a zero-length string
(""), GetObject returns a new object
instance of the specified type. If the
pathname argument is omitted,
GetObject returns a currently active
object of the specified type. If no
object of the specified type exists,
an error occurs.
It's subtle, but the implication is that
GetObject "", "ProjectName.ClassName
is actually equivalent to
CreateObject "ProjectName.ClassName"
That is to say, passing an empty string to the first parameter of GetObject makes it operate exactly like CreateObject, which means it will create a new instance of the class, rather than returning a reference to an already-running instance.
Going back to the MSDN excerpt, it mentions that omitting the first argument to GetObject altogether will cause GetObject to return a reference to an already-running instance, if one exists. Such a call would look like this:
GetObject , "ProjectName.ClassName" 'Note nothing at all is passed for the first argument'
However, if you try to do this, you will immediately get a run-time error. This is the use-case that the documentation is referring to when it says that GetObject doesn't work with classes created with VB6.
The reason this doesn't work is due to how GetObject performs its magic. When the first parameter is omitted, it tries to return an existing object instance by consulting the Running Object Table (ROT), a machine-wide lookup table that contains running COM objects. The problem is that objects have to be explicitly registered in the Running Object Table by the process that creates them in order to be accessible to other processes - the VB6 runtime doesn't register ActiveX EXE classes in the ROT, so GetObject has no way to retrieve a reference to an already-running instance. | unknown | |
d13748 | train | If you're favouring ASP.NET MVC (and I would suggest you should be) then Nerd Dinner (source) is one of the best examples on structuring an application.
Personally I feel that rather than focus on n-Tier/3-Tier architectures you should focus your efforts on responsibly designing web applications using principles like SOLID.
A: KiGG is a nice application to use for reference.
Source code can be found on codeplex: http://kigg.codeplex.com/ | unknown | |
d13749 | train | sorry guys for bad language and meaning in the question!!, what i had in mind was this!!
public function action_X_single($action, $table, $where = array()) {
$Xn = count($where)/3;
$operators = array('=', '>', '<', '>=', '<=');
for($i=1; $i<=$Xn; $i++){
$field[] = array( 'field' => $where[(3*$i)-3] );
$operator[] = array( 'operator' => $where[(3*$i)-2] );
$value[] = array( 'value' => $where[(3*$i)-1] );
}
$sql .= "{$action} FROM {$table} WHERE " ;
for($i=0;$i<$Xn;$i++)
{
if(($i)==0)
{
$sql .= implode(' ', $field[0]) . " " . implode(' ', $operator[0])." ?";
}
else
{
$sql .= " AND ".implode(' ', $field[$i]) . " " . implode(' ', $operator[$i])." ?";
}
}
for($i=0;$i<$Xn;$i++) {
if($i==0) {
$values .= implode(' ', $value[0]);
}else {
$values .= " ".implode(' ', $value[$i]);
}
}
if(!$this->query($sql, explode(' ', $values))->error()) {
return $this;
}
return false;
}
and so to get the values from my table i used this:
public function get_X_single($table, $where) {
return $this->action_X_single('SELECT *', $table, $where);
} | unknown | |
d13750 | train | Assuming you are using Java, yes. Everything is an Object in Java and Arrays take Objects. Good luck getting them back out though. | unknown | |
d13751 | train | Give this a try
Your data
df <- read.table(text="UserID Quiz_answers Quiz_Date
1 `a1,a2,a3`Positive 26-01-2017
1 `a1,a4,a3`Positive 26-01-2017
1 `a1,a2,a4`Negative 28-02-2017
1 `a1,a2,a3`Neutral 30-10-2017
1 `a1,a2,a4`Positive 30-11-2017
1 `a1,a2,a4`Negative 28-02-2018
2 `a1,a2,a3`Negative 27-01-2017
2 `a1,a7,a3`Neutral 28-08-2017
2 `a1,a2,a5`Negative 28-01-2017", header = TRUE, stringsAsFactors=FALSE)
Solution & output
library(dplyr)
ans <- df %>%
mutate(grp = sub(".*`(\\D+)$", "\\1", Quiz_answers)) %>%
group_by(grp, UserID, Quiz_Date) %>%
slice(1) %>%
ungroup() %>%
select(-grp) %>%
arrange(UserID, Quiz_Date)
# A tibble: 8 x 3
# UserID Quiz_answers Quiz_Date
# <int> <chr> <chr>
# 1 1 `a1,a2,a3`Positive 26-01-2017
# 2 1 `a1,a2,a4`Negative 28-02-2017
# 3 1 `a1,a2,a4`Negative 28-02-2018
# 4 1 `a1,a2,a3`Neutral 30-10-2017
# 5 1 `a1,a2,a4`Positive 30-11-2017
# 6 2 `a1,a2,a3`Negative 27-01-2017
# 7 2 `a1,a2,a5`Negative 28-01-2017
# 8 2 `a1,a7,a3`Neutral 28-08-2017
A: You can use sqldf package likes the following. First, find the group of Positive, Negative, and Neutral. Then, filter the duplicate using group by:
require("sqldf")
result <- sqldf("SELECT * FROM df WHERE Quiz_answers LIKE '%`Positive' GROUP BY UserID, Quiz_Date
UNION
SELECT * FROM df WHERE Quiz_answers LIKE '%`Negative' GROUP BY UserID, Quiz_Date
UNION
SELECT * FROM df WHERE Quiz_answers LIKE '%`Neutral' GROUP BY UserID, Quiz_Date")
The result after running is:
UserID Quiz_answers Quiz_Date
1 1 `a1,a2,a3`Neutral 30-10-2017
2 1 `a1,a2,a4`Negative 28-02-2017
3 1 `a1,a2,a4`Negative 28-02-2018
4 1 `a1,a2,a4`Positive 30-11-2017
5 1 `a1,a4,a3`Positive 26-01-2017
6 2 `a1,a2,a3`Negative 27-01-2017
7 2 `a1,a2,a5`Negative 28-01-2017
8 2 `a1,a7,a3`Neutral 28-08-2017
A: Here's a two line solution, using only base R:
data[,"group"] <- with(data, sub(".*`", "", Quiz_answers))
data <- data[as.integer(rownames(unique(data[, !(names(data) %in% "Quiz_answers") ]))), !(names(data) %in% "group")] | unknown | |
d13752 | train | The redirect URI you're providing is not what you have defined in your client settings.
1) Go to http://instagram.com/developer/clients/manage/
2) For your desired client/application, look for REDIRECT URI.
3) Make sure you provide the same redirect uri in your request as it is defined in your client/application settings. In your case, https://api.instagram.com/oauth/authorize/?response_type=token&redirect_uri=REDIRECT-URI&client_id=CLIENT-ID
Note: You may provide an optional scope parameter to request additional permissions outside of the “basic” permissions scope.
Note: You may provide an optional state parameter to carry through any server-specific state you need to, for example, protect against CSRF issues.
At this point, we present the user with a login screen and then a confirmation screen where they approve your app’s access to his/her Instagram data.
4) Once a user successfully authenticates and authorizes your application, instagram will redirect the user to your redirect_uri with a code parameter that you’ll use to request the access_token like http://your-redirect-uri?code=CODE.
For more information to learn about authentication process [Link]
tl;dr. The Redirect URI you send to /authorized must be same as the registered URI in your app. | unknown | |
d13753 | train | In Swift 3 a String itself is not a collection, so you have to
sort or reverse its characters view:
extension String {
func isAnagramOf(_ s: String) -> Bool {
let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "")
let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "")
return lowerSelf.characters.sorted() == lowerOther.characters.sorted()
}
func isPalindrome() -> Bool {
let f = self.lowercased().replacingOccurrences(of: " ", with: "")
return f == String(f.characters.reversed())
}
}
A slightly more efficient method to check for a palindrome is
extension String {
func isPalindrome() -> Bool {
let f = self.lowercased().replacingOccurrences(of: " ", with: "")
return !zip(f.characters, f.characters.reversed()).contains(where: { $0 != $1 })
}
}
because no new String is created, and the function "short-circuits",
i.e. returns as soon as a non-match is found.
In Swift 4 a String is collection of its characters, and
the code simplifies to
extension String {
func isAnagramOf(_ s: String) -> Bool {
let lowerSelf = self.lowercased().replacingOccurrences(of: " ", with: "")
let lowerOther = s.lowercased().replacingOccurrences(of: " ", with: "")
return lowerSelf.sorted() == lowerOther.sorted()
}
func isPalindrome() -> Bool {
let f = self.lowercased().replacingOccurrences(of: " ", with: "")
return !zip(f, f.reversed()).contains(where: { $0 != $1 })
}
}
Note also that
let f = self.lowercased().replacingOccurrences(of: " ", with: "")
returns a string with all space characters removed. If you want
to remove all whitespace (spaces, tabulators, newlines, ...) then use
for example
let f = self.lowercased().replacingOccurrences(of: "\\s", with: "", options: .regularExpression) | unknown | |
d13754 | train | Try removing items/controls from the xaml until the issue no longer manifests itself. By doing that you can divine the origination of the issue and possibly resolve or at least provide StackOverflow with a specific situation which we can help resolve.
A: I've found two buttons in the <Window.Style> tag that (seem to) cause the designer to crash:
<Button Command="{x:Static local:MainWindow.Maximize}" Loaded="MaximizeLoaded" Content="" ToolTip="{lex:Loc Bukkit Manager:UI:maximize}" Style="{StaticResource CaptionButton}" shell:WindowChrome.IsHitTestVisibleInChrome="True"/>
<Button Command="{x:Static local:MainWindow.Minimize}" Content="" ToolTip="{lex:Loc Bukkit Manager:UI:minimize}" Style="{StaticResource CaptionButton}" shell:WindowChrome.IsHitTestVisibleInChrome="True"/>
But a strange thing is, that every control's Command= attribute is marked as error. Although the commands (and their bindings) exist. On mouse over it shows a tooltip saying
Could not load file or assembly 'System.ComponentModel.Composition.CodePlex, Version=4.1.2.0, Culture=neutral, PublicKeyToken=13e5ffd4e05db186' or one of its dependencies. The specified module could not be found.
That only happens, when the designer is running, but I can still debug (and run) the application. When I terminate the designer procces, the errors are gone.
A: I've noticed that the System.ComponentModel.Composition.CodePlex.dll in the bin\debug folder has a different version than the one that Visual Studio is searching for. VS tries to find a file with version 4.1.2.0 but the one in the directory is 1.1.0.0.
A: Open the file System.ComponentModel.Composition.CodePlex.dll from the referenced location in Visual Studio as file type 'Resource Files'. Change the FILEVERSION and PRODUCTVERSION to 4,1,2,0 and rebuild the projects. This is a workaround to get the designer working. The clean fix is to request the CodePlex dll to have proper product & file version for these assemblies.
A: You can simply remove this error by setting CopyLocal=true for the mentioned dll.
This way it will not conflict between the existing installed one and the newly added one from the Nuget Package. | unknown | |
d13755 | train | I've done it before, but some time ago and it often changes in detail. What I would do is going to API Explorer and try to get to the first success by first reading the ads related to the Page and then creating them by leveraging existing posts there. You can create them in a paused state.
https://developers.facebook.com/docs/marketing-api/reference/adgroup
Facebook is all about experimenting, so if you don't want to experiment with your user's page you can create your own dummy page and try it there first. | unknown | |
d13756 | train | open or create file if not exist constants.php inside config folder and then add this line inside that file
define('SITE_PATH', 'http://localhost:8000/'); // write here you site url
and then use like this in view
<link rel="stylesheet" type="text/css" href="<?php echo SITE_PATH; ?>css/custom.css">
it will search for custom.css inside public/css folder so create css folder inside public folder and the create your custom.css or create directly inside you public folder | unknown | |
d13757 | train | You need to decide yourself what is the username and password you want Apple to use for review. When you submit the app or update the app, there is a section where you can supply those information, under App Review Information: | unknown | |
d13758 | train | There's nothing special about git to help with this kind of thing: Files have to be on disk somewhere so they can be dished out by a web server.
This question basically boils down to workflow. If you want to be able to look at the code you're working on independent of the code your coworker is working on the general solution is to have multiple sites (either separate web servers or just different virtual hosts behind a server) setup with different URLs. For example at our company we each have our own dev vm, and our own username.company.com URL that we can use to refer to code hosted on our VM.
Generally people have their git repository as the document root (or virtual host root) for their web server. They edit and test on this, committing locally as they go.
When we're done with our development we merge to a central repository, and there's a web server in test that we can go to which shows what's currently merged for testing. Once that's been accepted it's merged to master and pushed to production.
A:
But how can we view our own changes on the internet?
First of all you have to upload it to the internet of course.
You will need some place to store your code (bitbucket, gthub etc).
Those cloud services has a web interface to view your changes and all your history as well.
How can we make dev_timmy-based urls resolve to the version of the page that Timmy is working on?
Using git you can use branches. Each one of you will have its own branch which will allow you 2 to work on the same code at the same time and update your local code whenever you want.
This is what branches are.
Another solution might be to use the same project as submodule or using workdir which will allow you to have the same code under different folders | unknown | |
d13759 | train | You do not need two rules. You can achieve the goal using one rewrite rule, for example,
RewriteRule ^story/single-post/id/([0-9]+)/title/([0-9a-zA-Z-]+)/?$ single-post.php?id=$1&title=$2
After that you can access with the URL like this
https://localhost/just2minute/story/single-post/id/51835322/title/create-a-htaccess-file-with-the-code-for-clean-url
Then you want to do something like explained in this article:
https://www.tinywebhut.com/remove-duplicate-urls-from-your-website-38 | unknown | |
d13760 | train | No matter how large you set the maxQueryStringLength, there's a limit in the browsers. For example some browsers support a request length of only 2048 characters. Yours is longer (2440 characters). The only thing you could do is to use POST instead of GET to send such large data because POST requests doesn't have such limitation. So you generate an HTML <form> element with method="post" and action pointing to the url and a hidden field inside it containing this data and then submit this form.
A: In fact, I was blocked by an IIS limit: the maxUrl size and max query size(which is measured in octet:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="1048576" maxQueryString="1048576" />
</requestFiltering>
</security>
</system.webServer>
This resolved my problem | unknown | |
d13761 | train | HTML
Add below code in HTML body
<body>
<canvas id="gc"></canvas>
</body>
JS
<script>
window.onload=function() {
c=document.getElementById('gc');
cc=c.getContext('2d')
setInterval(update,1000/30);
c.addEventListener('mousemove',function(e) {
p1y=e.clientY-ph/2;
});
}
</script> | unknown | |
d13762 | train | If you are trying to find rows that meet criteria based on multiple columns in the DataTable, try something like the following
string stationToFind = "ABC";
DateTime dateToFind = new DateTime(2016, 5, 26);
var result = dataTable.AsEnumerable().Where(row => row.Field<string>("station") == stationToFind
&& row.Field<datetime>("date") == dateToFind).ToList();
If you are only expecting one row, then you can use .FirstOrDefault() instead of .ToList()
A: DataTable dt = new DataTable();
dt.Columns.Add("station", typeof(string));
dt.Columns.Add("max_temp", typeof(double));
dt.Columns.Add("min_temp", typeof(double));
dt.Rows.Add("XYZ", 14.5, 3.5);
dt.Rows.Add("XYZ", 14.5, 3.5);
dt.Rows.Add("XYX", 13.5, 3.5);
dt.Rows.Add("ABC", 14.5, 5.5);
dt.Rows.Add("ABC", 12.5, 3.5);
dt.Rows.Add("ABC", 14.5, 5.5);
var maxvalue = dt.AsEnumerable().Max(s => s.Field<double>("max_temp"));
var coll = dt.AsEnumerable().Where(s => s.Field<double>("max_temp").Equals(maxvalue)).
Select(s => new { station = s.Field<string>("station"), maxtemp = s.Field<double>("max_temp"), mintemp = s.Field<double>("min_temp") }).Distinct();
foreach (var item in coll)
{
Console.WriteLine(item.station + " - " + item.maxtemp + " - " + item.mintemp);
} | unknown | |
d13763 | train | The documentation for venue search mentions the per_page argument, that limits how many items are returned for each request.
You can try using:
http://api.songkick.com/api/3.0/search/venues.json?query={venue term}&per_page=10&apikey={API KEY}
It accepts any value between 1 and 50. | unknown | |
d13764 | train | Below is an example of JNI code calling a method returning a string. Hope this helps.
int EXT_REF Java_JNITest_CallJava(
JNIEnv* i_pjenv,
jobject i_jobject
)
{
jclass jcSystem;
jmethodID jmidGetProperty;
LPWSTR wszPropName = L"java.version";
jcSystem = i_pjenv->FindClass("java/lang/System");
if(NULL == jcSystem)
{
return -1;
}
jmidGetProperty = i_pjenv->GetStaticMethodID(jcSystem,
"getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
if(NULL == jmidGetProperty)
{
return -1;
}
jstring joStringPropName = i_pjenv->NewString((const jchar*)wszPropName, wcslen(wszPropName));
jstring joStringPropVal = (jstring)i_pjenv->CallStaticObjectMethod(jcSystem,
jmidGetProperty, (jstring)joStringPropName);
const jchar* jcVal = i_pjenv->GetStringChars(joStringPropVal, JNI_FALSE);
printf("%ws = %ws\n", wszPropName, jcVal);
i_pjenv->ReleaseStringChars(joStringPropVal, jcVal);
return 0;
} | unknown | |
d13765 | train | You could mark rows to be done by your session:
UPDATE table_1
SET marked_by_connection_id = CONNECTION_ID(),
marked_time = NOW()
WHERE worktime < UNIX_TIMESTAMP() AND marked_by_connection_id IS NULL;
Then you can feel free to work on any row that has your connection id, knowing that another session will not try to claim them:
SELECT * FROM table_1 WHERE marked_by_connection_id = CONNECTION_ID();
. . .
No locking or non-autocommit transaction is needed.
At the end of your session, unmark any rows you had marked:
UPDATE table_1 SET marked_by_connection_id = NULL
WHERE marked_by_connection_id = CONNECTION_ID();
Or alternatively your app could unmark individual rows as it processes them.
But perhaps your session dies before it can unmark those rows. So some rows were marked, but never processed. Run a cron job that clears such abandoned marked rows, allowing them to get re-processed by another worker, although a bit late.
UPDATE table_1 SET marked_by_connection_id = NULL
WHERE marked_time < NOW() - INTERVAL 30 MINUTE; | unknown | |
d13766 | train | The idea is to generate two integers a and n, and then return a and c = a * n. The answerer should guess what is n and beware of division by zero!
Something like this will do:
public KeyValuePair<int, int> GenerateIntDivisibleNoPair(int p, int q) {
if (p <= 0 || q <= 0 || q <= p)
throw Exception(); //for simplification of idea
Random rand = new Random();
int a = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q
int n = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q
return new KeyValuePair<int, int>(a, a * n);
}
You use it like this:
KeyValuePair<int, int> val = GenerateIntDivisibleNoPair(1, 101);
Console.WriteLine("What is " + val.Value.ToString() + " divide by " + val.Key.ToString() + "?");
A: I would have a Random declared somewhere with global access:
public static Random Rnd { get; set; }
Then when you want a number that divides by another you keep generating a number until you get one that divides by your Divisor:
if(Rnd == null)
{
Rnd = new Random();
}
int Min = p; //Can be any number
int Max = q; //Can be any number
if(Min > Max) //Assert that Min is lower than Max
{
int Temp = Max;
Max = Min;
Min = Temp;
}
int Divisor = n; //Can be any number
int NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
while(NextRandom % Divisor != 0)
{
NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
}
The check uses the modulus function %. This function gives you the remainder of an integer divide.
This means that if the NextRandom % Divisor is 0, then the Divisor divides evenly into NextRandom.
This can be turned into a method like so:
public static int GetRandomMultiple(int divisor, int min, int max)
{
if (Rnd == null)
{
Rnd = new Random();
}
if(min > max) //Assert that min is lower than max
{
int Temp = max;
max = min;
min = Temp;
}
int NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
while (NextRandom % divisor != 0)
{
NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max.
}
return NextRandom;
}
Then you can call it with the variables you mentioned like so:
int Number = GetRandomMultiple(n, p, q);
Note: I add one to the value of Max because of the 'Next' method. I think it's a bug in .Net. The value of Max is never returned, only Min..Max - 1. Adding one compensates for this. | unknown | |
d13767 | train | As I see from
$d = $conn1->Execute($sql, $my_data[$i]);
arguments passed to Execute method are query string and array with some values.
So, in your case you can do the same:
$d = $conn1->Execute($sql, array($name, $age));
where $name, $age your variables and $sql is your query string. | unknown | |
d13768 | train | Updating @nuxtjs/style-resources to above version 1.1 and using hoistUseStatements fixed it.
I changed the styleResources object in nuxt.config.js to:
styleResources: {
scss: [
'~/assets/global-inject.scss',
],
hoistUseStatements: true,
},
and added @use "sass:math"; to the top of global-inject.scss.
A: Updated answer
What if you try this in your nuxt.config.js file?
{
build: {
loaders: {
scss: {
additionalData: `
@use "@/styles/colors.scss" as *;
@use "@/styles/overrides.scss" as *;
`,
},
},
...
}
Or you can maybe try one of the numerous solutions here: https://github.com/nuxt-community/style-resources-module/issues/143
Plenty of people do have this issue but I don't really have a project under my belt to see what is buggy. Playing with versions and adding some config to the nuxt config is probably the way to fix it yeah.
Also, if it's a warning it's not blocking so far or does it break your app somehow?
Old answer
My answer here can probably help you: https://stackoverflow.com/a/68648204/8816585
It is a matter of upgrading to the latest version and to fix those warnings. | unknown | |
d13769 | train | I don't know you tried, but there is a reporting tool on elasticsearch inside the "Stack Management > Reporting". On the other side, there are another tools which you can work from a server with crontab. Here are some of them :
*
*A little bit old but I think it can work for you. ES2CSV. YOu can check there are examples inside the docs folder. YOu can send queries via file and report to CSV.
*Another option which is my preference too. You can use pandas library of python. YOu can write a script according to this article, and you can get a csv export CSV. The article I mentioned is really explained in a great way.
*Another alternative a library written in Java. But the documentation is a little bit weak.
*Another alternative for python library can be elasticsearch-tocsv. This one is a little bit recently updated when I compare it to first alternative. But the query samples are a little bit weak. But there is a detailed article. You can check it.
*You can use elasticdump, which is written on NodeJS and a great tool to report data from elasticsearch. And there is a CSV export option. You can see examples on GitHub page.
I will try to find more and I will update this answer time by time. Thanks! | unknown | |
d13770 | train | Firebase Authentication is having problems right now. Look at the Firebase Status Dashboard here:
https://status.firebase.google.com/
A: Graph API v2.2 has reached the end of its 2-year lifetime on 27 March, 2017, so this might be connected. You should check your library and possible updates. See this chart of deprecation dates, which lists v2.2 as available until March 25, 2017. | unknown | |
d13771 | train | If you simply want to determine if there are duplicate rows, you can use unique to do this. You can check the number of unique values in the column and compare this to the total number of elements (numel) in the same column
tf = unique(t.Column) == numel(t.Column)
If you want to determine which rows are duplicates, you can again use unique but use the third output and then use accumarray to count the number of occurrences of each value and then select those values which appear more than once.
[vals, ~, inds] = unique(t.Column, 'stable');
repeats = vals(accumarray(inds, 1) > 1);
% And to print them out:
fprintf('Duplicate value: %s\n', repeats{:})
If you want a logical vector of true/false for where the duplicates exist you can do something similar to that above
[vals, ~, inds] = unique(t.Column, 'stable');
result = ismember(inds, find(accumarray(inds, 1) > 1));
Or
[vals, ~, inds] = unique(t.Column, 'stable');
result = sum(bsxfun(@eq, inds, inds.'), 2) > 1;
Update
You can combine the two approaches above to accomplish what you want.
[vals, ~, inds] = unique(t.Column, 'stable');
repeats = vals(accumarray(inds, 1) > 1);
hasDupes = numel(repeats) > 0;
if hasDupes
for k = 1:numel(repeats)
fprintf('Duplicate value: %s\n', repeats{k});
fprintf(' Found at: ');
fprintf('%d ', find(strcmp(repeats{k}, t.Column)));
fprintf('\n');
end
end | unknown | |
d13772 | train | This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests? | unknown | |
d13773 | train | The cosmos:browserify package was updated yesterday and that seems to fix it. Try updating it again.
This happened to me a few times too. I used to be able to fix it by going through the update process for meteorhacks:npm of deleting the packages/npm-container folder, removing npm-container, and starting the app. Then today that didn't work anymore, so I updated cosmos:browserify and that worked. | unknown | |
d13774 | train | I think they are misguided or naive if what you have described is truly the developers' general approach to foreign keys. Of course it is quite possible that there are good reasons why a foreign key constraint can't or shouldn't apply to some particular attributes in any given system. Maybe that is the real reasoning behind the apparent rhetoric.
My advice. If you are stakeholder in the system in question then don't talk to the developers, talk to the development manager or whoever owns the system. Back up your case with specific examples of where lack of referential integrity is having an adverse impact or poses future risks.
If you don't have a current RI-related issue then presumably your main concern is to improve the policy or development approach for future work. Talk to the database managers, DBAs or those responsible for standards and information risks. Consider investing in some training, mentoring or consultancy for the benefit of the development team.
A: I've been designing database systems for over 30 years now. Here's my take - you're probably not going to like it. When designing closed systems, your referential integrity is probably going to be built into the application's user interface. You can only add a Product entity record where Color is required - enforced by the user interface. So why have a foreign key? I don't do Open databases where anyone can do anything - so your typical back end is going have thousands of lines of front end code protecting the integrity of the data. The bolted on foreign keys just get in the way and don't provide you with any real service. It's not like the foreign key is going to throw an exception and then you're going to go trap that exception and post a message to the user. Nobody and I mean NOBODY codes that way. All us programmers love to rush in and put all that cool stuff directly in the user interface. But like I said, I work with closed systems where the developer rules. Indexes, on the other hand - EXTREMELY IMPORTANT. Deal with that first. Foreign keys - just syntactical fluff. | unknown | |
d13775 | train | If your primary motive is to learn network programming and writing daemons, then I would recommend reading Beej's Guide to Network Programming and Advanced Programming in the Unix Environment. These don't provide straight up SMTP implementations but will give a good foundation to implement any protocol.
A: If you're set on writing this in C, start with this guide on network programming and sockets. Writing such a server isn't simple and requires a lot of background knowledge.
After you're a bit comfortable with sockets, install WireShark, some open-source SMTP server and try to send it some of the standard SMTP requests - seeing how it responds. This type of "exploration" is extremely valuable when implementing protocols.
A: The simple answer would be to google for open source smtp, try and find an existing project that is in the language you want to implement your own in, or in a language you can read and understand, and then work through the code to gain the understanding you need
Sites like sourceforge, freshmeat github, bitbucket will have projects on that will range from small to large. ou can also try some of the other repositories like PHPClasses, CPAN etc. (again depending on your language of choice).
You can also try open source search such as Krugle.
Another reference would be the SMTP RFC RFC 821 which will give you the standard you are writing to regardless of language. | unknown | |
d13776 | train | There's no great security scanning support at the moment although there are some discussions. The first step would be for Google to start to track Dart vulnerabilities in their existing Open Source Vulnerability (OSV) database, you could watch or get involved here: https://github.com/google/osv/issues/62
A: I would suggest the open source framework called mobsf. It's great at scanning a mobile app. I have been using it ever since and I could start patching up my security vulnerability right away.
link : https://github.com/MobSF/Mobile-Security-Framework-MobSF
A: Mobile-Security-Framework-MobSF Great Tools For Doing Mobile Applications Security Test
A: I appreciate this might be a necropost but for anyone else who comes across this, you could look into Black Duck (https://www.blackducksoftware.com/) for licensing risks and Checkmarx CxSAST (https://checkmarx.com/) for security issues. Both support Dart/Flutter code (we've integrated into our ADO pipelines).
These would be for organisations rather than individuals though.
For private projects, I guess you could look into this integration into SonarQube? | unknown | |
d13777 | train | I checked the code and issue seems to be the place the filter is being applied.
Fiddle: http://jsfiddle.net/pfgkna8k/2/. Though I didn't know what you were exactly implementing.
please check the code
<div ng-app="lists">
<div ng-controller="ProductList as products">
<form ng-submit="addProduct()">
<input type="text" placeholder="Enter product" ng-model="productTitle" />
<button>Add</button>
</form>
<ul class="productList">
<li ng-repeat="product in list track by $index" ng-bind="filteredtitle = (product.title | custom: searchBox)" ng-show="filteredtitle">
</li>
</ul>
<input type="text" placeholder="Search" ng-model="searchBox" />
</div>
</div> | unknown | |
d13778 | train | You basically need to match all entries in the placement column against all entries in the creative name column. This can be done by a nested loop: for each placement, for each creative name, compare the placement and the creative name.
The FuzzyWuzzy library has a convenience function that can be used to replace the inner loop by a single function call that extracts the best matches:
from fuzzywuzzy import process
for placement in fp:
best_matches = process.extract(placement, tp, limit=3)
print placement, best_matches
Be warned though that this will need n² comparisons, where n is the number of rows in your data set. Depending on the size of the data set, this might take a long time.
Note that you don't need to open the file after reading the data set into memory via pandas. Your loop over the reopened file doesn't make any use of the column loop variable (which should be called row, by the way). | unknown | |
d13779 | train | Constructing a B from an A involves copying the A - it says so in your code. That has nothing to do with copy elision in function returns, all of this happens in the (eventual) construction of B. Nothing in the standard allows eliding (as in "breaking the as-if rule for") the copy construction in member initialization lists. See [class.copy.elision] for the handful of circumstances where the as-if rule may be broken.
Put another way: You get the exact same output when creating B b{A{true}};. The function return is exactly as good, but not better.
If you want A to be moved instead of copied, you need a constructor B(A&&) (which then move-constructs the a member).
A: You will not succeed at eliding that temporary in its current form.
While the language does try to limit the instantiation ("materialisation") of temporaries (in a way that is standard-mandated and doesn't affect the as-if rule), there are still times when your temporary must be materialized, and they include:
[class.temporary]/2.1: - when binding a reference to a prvalue
You're doing that here, in the constructor argument.
In fact, if you look at the example program in that paragraph of the standard, it's pretty much the same as yours and it describes how the temporary needn't be created in main then copied to a new temporary that goes into your function argument… but the temporary is created for that function argument. There's no way around that.
The copy to member then takes place in the usual manner. Now the as-if rule kicks in, and there's simply no exception to that rule that allows B's constructor's semantics (which include presenting "copied" output) to be altered in the way you were hoping.
You can check the assembly output for this, but I'd guess without the output there will be no need to actually perform any copy operations and the compiler can elide your temporary without violating the as-if rule (i.e. in the normal course of its activities when creating a computer program, from your C++, which is just an abstract description of a program). But then that's always been the case, and I guess you know that already.
Of course, if you add a B(A&& a) : a(std::move(a)) {} then you move the object into the member instead, but I guess you know that already too.
A: I have figured how to do what I wanted.
The intent was to return multiple values from a function with the minimal amount of "work".
I try to avoid passing return values as writable references (to avoid value mutation and assignment operators), so I wanted to do this by wrapping the objects to be returned in a struct.
I have succeeded at this before, so I was surprised that the code above didn't work.
This does work:
#include <iostream>
struct A {
bool x;
explicit A(bool x) : x(x) {
std::cout << "A constructed" << std::endl;
}
A(const A &other) : x(other.x) {
std::cout << "A copied" << std::endl;
}
A(A &&other) : x(other.x) {
std::cout << "A moved" << std::endl;
}
A &operator=(const A &other) {
std::cout << "A reassigned" << std::endl;
if (this != &other) {
x = other.x;
}
return *this;
}
};
struct B {
A a;
};
B foo() {
return B{A{true}};
}
int main() {
B b = foo();
std::cout << b.a.x << std::endl;
}
output:
A constructed
1
The key was to remove all the constructors of B. This enabled aggregate initialization, which seems to construct the field in-place. As a result, copying A is avoided. I am not sure if this is considered copy elision, technically. | unknown | |
d13780 | train | In order to convert between image formats, the easiest way would be using the class CImage shared by MFC and ATL and defined in the header file atlimage.h.
CImage image;
HRESULT res = image.Load("in.bmp");
image.Save("out.jpg");
image.Save("out.gif");
image.Save("out.png");
image.Save("out.tif");
If you have a RGB buffer and want to create a bitmap: just create and save a bitmap header into a file and add the RGB buffer to it.
To create the header you can use the BITMAPFILEHEADER, BITMAPINFOHEADER and RGBQUAD structures from GDI defined in the header WinGDI.h
Here is an example on how to fill the header data:
BITMAPINFOHEADER bmpInfoHdr;
bmpInfoHdr.biSize = sizeof(BITMAPINFOHEADER);
bmpInfoHdr.biHeight = nHeight;
bmpInfoHdr.biWidth = nWidthPadded;
bmpInfoHdr.biPlanes = 1;
bmpInfoHdr.biBitCount = bitsPerPixel;
bmpInfoHdr.biSizeImage = nHeight * nWidthPadded * nSPP;
bmpInfoHdr.biCompression = BI_RGB;
bmpInfoHdr.biClrImportant = 0;
bmpInfoHdr.biClrUsed = 0;
bmpInfoHdr.biXPelsPerMeter = 0;
bmpInfoHdr.biYPelsPerMeter = 0;
bmpFileHdr.bfType = BITMAP_FORMAT_BMP;
bmpFileHdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize +
sizeof(RGBQUAD)*numColors + bmpInfoHdr.biSizeImage);
bmpFileHdr.bfReserved1 = 0;
bmpFileHdr.bfReserved2 = 0;
bmpFileHdr.bfOffBits = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize +
sizeof(RGBQUAD)*numColors);
Keep into account that the bitmaps are stored upside-down and that the width of the image must be aligned on a DWORD except for RLE-compressed bitmaps.(they must be multiple of 4 bytes, add a padding if necessary).
if ((nWidth%4) != 0)
nPadding = ((nWidth/4) + 1) * 4;
When saving your buffer, add the needed padding to each row...
Summarizing, these are the needed steps to create a bitmap file from a rgb buffer:
//1. create bmp header
//2. save header to file:
write(file, &bmpFileHdr, sizeof(BITMAPFILEHEADER));
write(file, &bmpInfoHdr, sizeof(BITMAPINFOHEADER));
write(file, &colorTable, numColors * sizeof(RGBQUAD));
//3. add rgb buffer to file:
for(int h=0; h<nHeight; h++) {
for(int w=0; w<nWidth; w++) {
//3.a) add row to file
//3.b) add padding for this row to file
}
}
A: I used the CImage Class from ATL.
int width=0, height=0;
char * val = "9788994774480";
zint_symbol *my_symbol;
my_symbol = ZBarcode_Create();
//ZBarcode_Encode_and_Buffer(my_symbol,(unsigned char *) val, 0, 0);
ZBarcode_Encode(my_symbol, (unsigned char *) val, 0);
ZBarcode_Buffer(my_symbol, 0);
height = my_symbol->bitmap_height;
width = my_symbol->bitmap_width;
char * imgBits = my_symbol->bitmap;
CImage img;
img.Create(width, height, 24 /* bpp */, 0 /* No alpha channel */);
int nPixel = 0;
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
BYTE r = (BYTE)imgBits[nPixel];
BYTE g = (BYTE)imgBits[nPixel+1];
BYTE b = (BYTE)imgBits[nPixel+2];
img.SetPixel(col, row , RGB(r, g, b));
nPixel += 3;
}
}
img.Save("CImage.bmp", Gdiplus::ImageFormatBMP);
ZBarcode_Delete(my_symbol);
A: is there anyway to do this other than using SetPixel? I am experiencing major performance issues with SetPixel and need an alternative method... I have tried using CreateDIBSection to no avail. The barcode displays slanted and is unusable. here is my code for that:
void *bits = (unsigned char*)(my_symbol->bitmap);
HBITMAP hBitmap = CreateDIBSection(pDC->GetSafeHdc(), &info, DIB_RGB_COLORS, (void **)&pDestData, NULL, 0);
memcpy(pDestData, my_symbol->bitmap, info.bmiHeader.biSizeImage);
img.Attach(hBitmap);
Another option that produces the same result is this:
BITMAPINFO info;
BITMAPINFOHEADER BitmapInfoHeader;
BitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfoHeader.biWidth = my_symbol->bitmap_width;
BitmapInfoHeader.biHeight = -(my_symbol->bitmap_height);
BitmapInfoHeader.biPlanes = 1;
BitmapInfoHeader.biBitCount = 24;
BitmapInfoHeader.biCompression = BI_RGB;
BitmapInfoHeader.biSizeImage = 0;
BitmapInfoHeader.biXPelsPerMeter = 0;
BitmapInfoHeader.biYPelsPerMeter = 0;
BitmapInfoHeader.biClrUsed = 0;
BitmapInfoHeader.biClrImportant = 0;
info.bmiHeader = BitmapInfoHeader;
HBITMAP hbmp = CreateDIBitmap(dc, &BitmapInfoHeader, CBM_INIT, (LPVOID *)my_symbol->bitmap, (LPBITMAPINFO)&info, DIB_RGB_COLORS);
img.Attach(hbmp); | unknown | |
d13781 | train | I had run into the same error. The line actually causing the error for me was subprocess.call('java').
Installing Java on my machine fixed the error for me.
If installing Java still doesn't solve the problem for you, try running which java, and add the output directory to your PATH environment variable. | unknown | |
d13782 | train | I am the guy who created the bugzilla post you are referencing.
Are you sure you have the <AndroidResgenExtraArgs>--no-crunch </AndroidResgenExtraArgs> on the right place? It must be inside the configuration you are using, i.e. the .csproj must be like this if you are deploying in Debug | AnyCPU configuration:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<AndroidResgenExtraArgs>--no-crunch </AndroidResgenExtraArgs>
(also notice the trailing space after --no-crunch)
BTW I also have trouble with aapt.exe when installing Nugets and --no-crunch does not help with this. What helps is temporarily renaming aapt.exe to aapt2.exe - Visual Studio does not run the aapt process, because it can't find the exe file and Nuget installations are fast. But this would probably not work for build and deploy, I think it throws an error.
A: Well, after trying a lot of stuff I made a lucky guess and it worked.
I was looking to my csproj and noticed some weird things, like:
<ItemGroup>
<AndroidResource Include="Resources\layout\onefile.axml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\anotherfile.axml" />
</ItemGroup>
<ItemGroup>
<AndroidResource Include="Resources\layout\onemorefile.axml">
<SomeOtherAttributes />
</AndroidResource>
</ItemGroup>
So I imagined that organizing the ItemGroups would worth a try and put all ItemGroups (class, layout, image, string, etc) together like:
<ItemGroup>
<AndroidResource Include="Resources\layout\onefile.axml" />
<AndroidResource Include="Resources\layout\anotherfile.axml" />
<AndroidResource Include="Resources\layout\onemorefile.axml" />
</ItemGroup>
And it worked beyond what I expected. Not only fixed my freezing problems... it made VS faster than before of my freezing problems... REALLY faster!
I don't know if reorganizing the csproj file can cause any kind of problems, but I'll do the same with other projects and see what happen.
I did a quick research about csproj and ItemGroup and found nothing relevant... I believe it's kind a bug! | unknown | |
d13783 | train | It is because you are doing split.containsKey([temp]) instead of split.containsKey(temp).
In your snippet, you are checking whether the map split has the array [temp] as a key, (in the case of 'r': ['r']), which is false, it has 'r' as a key, not ['r'].
Change your code to
void main(){
Map<String, String> split = new Map();
var word = 'current ';
for (int i = 0; i < word.length; i++) {
String temp = word[i];
if (split.containsKey(temp)) { // <- Change here.
split[temp] = split[temp]! + ' ' + i.toString();
} else {
split[temp] = i.toString();
}
}
print(split.toString());
} | unknown | |
d13784 | train | A few things:
*
*Case matters so be sure the paths in your select attributes are the same as the source XML.
* The entity nbsp is not declared so use either a hex or decimal reference. You can create an entity declaration for nbsp if you want. In the example, I used the hex reference. Let me know if you want an example of the declaration for nbsp.
*You can't use literal & unless you're in a CDATA section. It's easier to use & instead. I used & in the example. If you want to use CDATA, do something like: <xsl:text><![CDATA[&company=]]></xsl:text>
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="ELEMENT">
<p>
<xsl:for-each select="RECORD">
<p>
<xsl:value-of select="COUNTER"/>
<xsl:text> : </xsl:text>
<a>
<xsl:attribute name="href">
<xsl:text>dynamics://</xsl:text>
<xsl:value-of select="DRILLDOWNGROUP"/>
<xsl:text>?DrillDown_0?tableid=</xsl:text>
<xsl:value-of select="TableId"/>
<xsl:text>&field=RecId&value=</xsl:text>
<xsl:value-of select="RecId"/>
<xsl:text>&company=</xsl:text>
<xsl:value-of select="dataAreaId"/>
</xsl:attribute>
<xsl:value-of select="SalesId"/>
</a>
<xsl:text>   </xsl:text>
<xsl:value-of select="PurchOrderFormNum"/>
<xsl:text>   </xsl:text>
<xsl:value-of select="dataAreaId"/>
<xsl:text>   </xsl:text>
<xsl:value-of select="RecId"/>
<br/>
<br/>
</p>
</xsl:for-each>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output
<html>
<body>
<p>
<p>1 : <a href="dynamics://TEST?DrillDown_0?tableid=40276&field=RecId&value=5637144826&company=XXX">SO090040717</a> 113657 XXX 5637144826<br><br></p>
</p>
</body>
</html> | unknown | |
d13785 | train | It turns out the url bit needs to be in the following form
url: '@url.Action("GetSiteTable", "GlobalSitesController")',
(url needs to be initialised as in below)
System.Web.Mvc.UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext); | unknown | |
d13786 | train | I'm adding a new similar answer due to the vexing lack of QRegularExpression answers that handle all capture groups specified, and not by name. I just wanted to be able to specify capture groups and get only those results, not the whole kitchen sink. That becomes a problem when blindly grabbing capture group 0, which is what almost all answers on SO do for QRegularExpressions with multiple results. This answer gets back all specified capture groups' in a list, and if no capture groups were specified, it returns capture-group 0 for a whole-regex match.
I made this simplified code-snippet on Gist that doesn't directly address this question. The sample app below if a diff that does address this specific question.
#include <QCoreApplication>
#include <QRegularExpressionMatch>
#include <QStringList>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QStringList results;
QRegularExpression this_regex("<bar \\w>(.*?)</bar>");
QString test_string = "<foo><bar s>INFO1.1</bar> </ qux> <peter></peter><bar e>INFO1.2\n\
</bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFO2.1</bar>\n\
</ nothing><endlessSenselessTags></endlessSenselessTags><rofl>\n\
<bar e>INFO2.2</bar></rofl>\n";
if(!this_regex.isValid())
{
std::cerr << "Invalid regex pattern: " << this_regex.pattern().toStdString() << std::endl;
return -2;
}
for (int i = 0; i < this_regex.captureCount()+1; ++i)
{
// This skips storing capture-group 0 if any capture-groups were actually specified.
// If they weren't, capture-group 0 will be the only thing returned.
if((i!=0) || this_regex.captureCount() < 1)
{
QRegularExpressionMatchIterator iterator = this_regex.globalMatch(test_string);
while (iterator.hasNext())
{
QRegularExpressionMatch match = iterator.next();
QString matched = match.captured(i);
// Remove this if-check if you want to keep zero-length results
if(matched.length() > 0){results << matched;}
}
}
}
if(results.length()==0){return -1;}
for(int i = 0; i < results.length(); i++)
{
std::cout << results.at(i).toStdString() << std::endl;
}
return 0;
}
Output in console:
INFO1.1
INFO2.1
INFO2.2
To me, dealing with Regular Expressions using QRegularExpression is less painful than the std::regex's, but they're both pretty general and robust, requiring more fine-tuned result-handling. I always use a wrapper I made for QRegularExpressions to quickly make the kind of regexes and results that I typically want to leverage.
A: Maybe you can try with this
QRegularExpression reA("(<bar [se]>[^<]+</bar>)");
QRegularExpressionMatchIterator i = reA.globalMatch(input);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
qDebug() << match.captured(0);
}
}
that gives me this output
"<bar s>INFO1.1</bar>"
"<bar e>INFO1.2
</bar>"
"<bar s>INFO2.1</bar>"
"<bar e>INFO2.2</bar>"
while this expression
QRegularExpression reA("((?<=<bar [se]>)((?!</bar>).)+(?=</bar>))",
QRegularExpression::DotMatchesEverythingOption);
with this input
<foo><bar s>INFO1</lol>.1</bar> </ qux> <peter></peter><bar e>INFO1.2
</bar><fred></ senseless></fred></ xx><lol></lol></foo><bar s>INFO2.1</bar>
</ nothing><endlessSenselessTags></endlessSenselessTags><rofl>
<bar e>INFO2.2</bar></rofl>
gives me as output
"INFO1</lol>.1"
"INFO1.2
"
"INFO2.1"
"INFO2.2" | unknown | |
d13787 | train | If I'm not mistaken, it looks like you want to call a coder to a view, and then show all the assignments for an a user.
First, I might start by assigning a related_name to the coder and assignment models relationships with each other, so you can easily reference them later.
class Assignment(models.Model):
coders = models.ManyToManyField(Coder, related_name='assignments')
class Coder(models.Model):
user = models.OneToOneField(User, related_name="coder")
I'd then reference the user in a template as such using the one to one relationship:
{% for assignment in user.coder.assignments.all %}
Also, looks like the problem is how you've got yout models setup. After reviewing the django.db.models.base for the "models.Model" class and "ModelBase" class, it looks like there is no "Admin" subclass. You'll probably want to remove those to start with.
Next, the __unicode__ field shows the default visible value which represents the object on the screen. In this case, you've forced it to be "Coders". If you had 5 coders to an assignment, you'd see "Coders, Coders, Coders, Coders, Coders" instead of "admin, user1, bob22, harry8, stadm1in", etc. Let's override the unicode to show something more meaningful. Since the coders field only has the user field, let's reference that by self.user.username. We'll change Assignment()'s unicode to self.title as well.
ModelForm doesn't have an 'Admin' subclass either, so let's remove that.
MODELS:
class Coder(models.Model):
"""Every user can be a coder. Coders are assigned to Assignments"""
user = models.OneToOneField(User, related_name='coder')
def __unicode__(self):
return self.user.username
class Assignment(models.Model):
"""(Assignment description)"""
title = models.CharField(blank=True, max_length=100)
start_year = models.IntegerField(blank=True, null=True)
end_year = models.IntegerField(blank=True, null=True)
country = models.IntegerField(blank=True, null=True)
coders = models.ManyToManyField(Coder, related_name='assignments')
def __unicode__(self):
return self.title
ADMIN:
class AssignmentCoderInline(admin.StackedInline):
model = Assignment.coders.through
can_delete = False
# verbose_name_plural = 'coder'
class AssignmentAdmin(admin.ModelAdmin):
fieldsets = [
('Assignment', {'fields': ['title', 'start_year', 'end_year']})
]
inlines = (AssignmentCoderInline,) | unknown | |
d13788 | train | I ran into the same problem following Sanjeev's tutorial. Given your settings, you are connecting to the right db, the issue is that it has no tables. This can be solved via Alembic.
In your docker-compose.yml, under api: add the line:
command: bash -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"
That's it!
To check that the tables have been successfully created, open a terminal in your project folder and do the following:
*
*Run docker compose
docker-compose up -d
*Find the pg container name, in your case it should be something like fastapi-postgres-1, then start a bash session into your pg container
docker ps
docker exec -it fastapi-postgres-1 bash
*From here, access psql and find your db name, in your case it should be fastapi
su - postgres
psql
\l
*Access your db and check that the tables have been created
\c fastapi
\dt
If result is something like this, you're good to go.
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | alembic_version | table | postgres
public | posts | table | postgres
public | users | table | postgres
public | votes | table | postgres
(4 rows) | unknown | |
d13789 | train | use this :
header('Location: http://localhost/yourHtmlFile.html');
but make sure your php didn't output anything before it
update
another workaround is to use include ('yourHtmlFile.html');
A: PHP can answer code written in HTML back to the browser using echo:
<?php
//do some code
$name="superuser";
echo "Hi ".$name;
?> | unknown | |
d13790 | train | Use np.sqrt on the result of the squares:
In [10]:
df['z'] = np.sqrt(df['x']**2 + df['y']**2)
df
Out[10]:
x y z
0 2 4 4.472136
1 3 4 5.000000
You can also sum row-wise the result of np.square and call np.sqrt:
In [13]:
df['z'] = np.sqrt(np.square(df[['x','y']]).sum(axis=1))
df
Out[13]:
x y z
0 2 4 4.472136
1 3 4 5.000000 | unknown | |
d13791 | train | There are many ways to update the data from one component to another.
*
*component to component using service or subjects
*parent~child component data exchange using Input() and Output() decorators. Or by using @ViweChild() interactions.
and many more
But please do check the angular docs https://angular.io/guide/component-interaction .
Use the below simple code, u might need to include modules like FormsModule. and import Input(), Output etc
@Component({
selector: 'app-journal-form',
template: `
<div *ngFor="let entry of entries.entries; let i=index">
<h2> {{ entry.num }}. {{ entry.name }} </h2>
<app-input id="{{entry.num}}" [entry]="entry" [arrayIndex]="i" (updateEntry)="updateEntry($event)" ></app-input>
</div>`
})
export class JournalFormComponent implements OnInit {
constructor(private entries: EntriesService) {
this.entries = entries;
}
ngOnInit(): void {
}
updateEntry(event){
console.log(event);
this.entries[event.arrayIndex] = event.entry;
}
}
@Component({
selector: 'app-input',
template: `
<textarea [(ngModel)]="name"
(keyup.enter)="update()"
(blur)="update()">
</textarea>
`
})
export class InputComponent {
@Input() entry: any;
@Input() arrayIndex: number;
@Output() updateEntry: EventEmitter<any> = new EventEmitter();
name:string;
constructor() {
console.log(entry);
this.name = entry.name;
}
update(){
this.entry.name = this.name;
this.updateEntry.emit({entry: this.entry, arrayIndex});
}
}
A: Output event will help in this situation.
<div *ngFor="let entry of entries.entries">
<h2> {{ entry.num }}. {{ entry.name }} </h2>
<app-input id="{{entry.num}}" (entryChange) = "entry.text = $event"></app-input>
</div>
app-input component
export class InputComponent {
private value = '';
@Output() entryChange = new EventEmitter<string>();
update(value: string) {
this.value = value;
this.entryChange.emit(value);
}
}
Instead of entry.text = $event you can also pass it to any save function, like saveEntry($event); | unknown | |
d13792 | train | You can make a copy before you start sorting, and then copy from that stored copy into the array being sorted in each iteration of the loop.
int[] toBeSorted = new int[10000];
// fill the array with data
int[] copied = new int[10000];
System.arrayCopy(toBeSorted, 0, copied, 0, copied.length);
// prepare the timer, but do not start it
for (int = 0 ; i != 100 ; i++) {
System.arrayCopy(copied, 0, toBeSorted, 0, copied.length);
// Now the toBeSorted is in its initial state
// Start the timer
Arrays.sort(toBeSorted);
// Stop the timer before the next iteration
}
A: You can use the System.currentTimeMillis() method to get the current time then subtract when the method finishes executing.
long totalRuntime = 0;
for(int i = 0; i < 100; i++)
{
long startTime = System.currentTimeMillis();
sortArrays()
long endTime = System.currentTimeMillis();
totalRuntime += (endTime - startTime);
}
System.out.println("Algorithm X on average took "
+ totalRuntime/100 + " milliseconds);
If you want to do this X times just keep a counter for each algorithm and increment. Then you can divide by the total number of runs at the end and compare.
A: Generally you would stop and start the timer in between each run of the algorithm you're testing, adding up the individual times and then dividing by the number of runs. That way any "setup time" isn't included because the timer isn't running during the setup.
A: Go with something like this
new array equals random array,
start timer
sort new array
stop timer
add time to your list of times
repeat until necessary
As long as you copy the original array each time, you will never sort the original one
A: put the sorting algorithm in a function and keep calling the function with the same again and again and passing the array to the function after cloning it using the clone method.
You can call the current time function and print it out every time you run the loop.
A: If you're willing to blow memory, then just make 100 (or however many) copies of the same array before you start timing. If you're not, then time sorting and copying together, and then time just copying to see approximately how much of your sorting + copying time was spent copying.
Also, sidenote: look into using a benchmarking framework like Caliper instead of doing your own "manual" benchmarking. It's easier, and they've solved a lot of problems that you might not even know are going on that could screw up your timings. | unknown | |
d13793 | train | you must use call_user_func_array. Also you are calling callFunctionFromClass as a static method but it isn't static
Class useful
{
public function callFunctionFromClass($className, $function, $args = array())
{
return call_user_func_array(array($className, $function), $args);
}
public function text($msg, $msg2)
{
echo $msg;
echo $msg2;
}
}
$u = new useful;
$test = $u->callFunctionFromClass('useful', "text", array("Test", "Test")); | unknown | |
d13794 | train | So I finally solved it. Made a T4 template and replaced that with the default generated tt file.
My code is here, please star it if you found it helpful and add comments in case of help or suggestions. | unknown | |
d13795 | train | In fact .* means zero or more occurrences of any character, and when it follows with a special pattern in a lookahead it means that the regex engine will assert that the regex can be matched. And when you use .* before your pattern you are telling the regex engine to match my pattern that precede by zero or more characters this means you want to be sure that your pattern is present in your string (from leading to trailing).
Here is an example with diagram:
(?=.*\d)[a-z]+
Debuggex Demo | unknown | |
d13796 | train | This can be done with ng-disabled in button
Check this Try ng-disabled
<ion-view>
<ion-nav-buttons side="primary">
<button class="button" ng-disabled="disabled" ng-click="doSomething()">
I'm a button on the primary of the navbar!
</button>
</ion-nav-buttons>
<ion-content>
<button class="button" ng-click="disable()">
Click to disable
</button>
</ion-content>
</ion-view>
//Angular code
$scope.disable=function(){
$scope.disabled=true;
} | unknown | |
d13797 | train | First of all, React's local state and Redux's global state are different things.
Let's assume you don't use Redux for the moment. State management is up to you totally. But, try to construct your components as pure as possible and use the state where do you really need it. For example, think about a favorites app as you said. The decision is, do you want to show all the favorites categories in the same UI? If yes, then you need to keep all of them in one place, in the App. Then you will pass those state pieces your other components: Book, Movie, etc. Book get the book part of your state for example. They won't have any state, your App does. Here, App is the container component, others are presentational ones or dumb ones.
Is your data really big? Then you will think about other solutions like not fetching all of them (from an API endpoint or from your DB) but fetch part by part then update your state when the client wants more.
But, if you don't plan to show all of them in one place, then you can let your components have their state maybe. Once the user goes to Book component, maybe you fetch only the book data then set its state according to that. As you can see there are pros and cons, in the first method you are doing one fetch and distributing your data to your components, in the second method you are doing multiple fetches. So, think about which one suits you.
I can see you removed the Redux tag, but with Redux you will have one global state in the store. Again, in one point you are doing some fetch then update your state. Then, you will connect your components when they need any data from the state. But again, you can have container/presentational components here, too. One container connects to your store then pass the data to your components. Or, you can connect multiple components to your store. As you examine the examples, you will see best practices about those.
If you are new don't think too much :) Just follow the official documentation, read or watch some good tutorials and try to write your app. When you realize you need to extract some component do it, then think about if you need any state there or not?
So, once the question is very broad then you get an answer which is too broad, some text blocks :) You can't see so many answers like that, because here we share our specific problems. Again, don't bloat yourself with so many thoughts. As you code, you will understand it better. | unknown | |
d13798 | train | Try to check the SqlNotificationEventArgs object in the dependency_OnChnage method. It looks like you have an error there. I had the same SqlDependency behavior one time and the problem was solved by changing select msgdtl,msgid From NotifyMsg to select msgdtl,msgid From dbo.NotifyMsg (The dbo statement has been added).
But I should warn you: be careful using SqlDependency class - it has the problems with memory leaks. Hovewer, you can use an open source realization of the SqlDependency class - SqlDependencyEx. It uses a database trigger and native Service Broker notification to receive events about the table changes. This is an usage example:
int changesReceived = 0;
using (SqlDependencyEx sqlDependency = new SqlDependencyEx(
TEST_CONNECTION_STRING, TEST_DATABASE_NAME, TEST_TABLE_NAME))
{
sqlDependency.TableChanged += (o, e) => changesReceived++;
sqlDependency.Start();
// Make table changes.
MakeTableInsertDeleteChanges(changesCount);
// Wait a little bit to receive all changes.
Thread.Sleep(1000);
}
Assert.AreEqual(changesCount, changesReceived);
With SqlDependecyEx you are able to monitor INSERT, DELETE, UPDATE separately and receive actual changed data (xml) in the event args object. Hope this help.
A: there is a custom implementation of SqlDependency that report you the changed table records:
var _con= "data source=.; initial catalog=MyDB; integrated security=True";
static void Main()
{
using (var dep = new SqlTableDependency<Customer>(_con, "Customer"))
{
dep.OnChanged += Changed;
dep.Start();
Console.WriteLine("Press a key to exit");
Console.ReadKey();
dep.Stop();
}
}
static void Changed(object sender, RecordChangedEventArgs<Customer> e)
{
if (e.ChangeType != ChangeType.None)
{
for (var index = 0; index < e.ChangedEntities.Count; index++)
{
var changedEntity = e.ChangedEntities[index];
Console.WriteLine("DML operation: " + e.ChangeType);
Console.WriteLine("ID: " + changedEntity.Id);
Console.WriteLine("Name: " + changedEntity.Name);
Console.WriteLine("Surame: " + changedEntity.Surname);
}
}
}
Here is the link: [https://tabledependency.codeplex.com] | unknown | |
d13799 | train | if these are http requests that complete, I think your bug is caused by a change to the mergeMap signature that removed the result selector. it's hard to be sure without knowing exactly which version you're on as it was there, then removed, then added again, and they're removing it once more for good in v7.
if you want to run them sequentially... this is all you need...
// concat runs input observables sequentially
concat(...observables).subscribe(res => console.log(res))
if you want to wait till they're all done to emit, do this:
concat(...observables).pipe(
// this will gather all responses and emit them all when they're done
reduce((all, res) => all.concat([res]), [])
// if you don't care about the responses, just use last()
).subscribe(allRes => console.log(allRes))
In my personal utility rxjs lib, I always include a concatJoin operator that combines concat and reduce like this.
the only trick is that concat requires observables to complete till it moves on to the next one, but the same is true for mergeMap with concurrent subscriptions set to 1.. so that should be fine. things like http requests are fine, as they complete naturally after one emission.. websockets or subjects or event emitters will behave a bit differently and have to be manually completed, either with operators like first or take or at the source.
A: If you are not concerned about the sequence of execution and just want 'Huzzah!' to be printed once all the observable has been executed forkJoin can also be used.Try this.
forkJoin(...observables).subscribe(res => console.log('Huzzah'); | unknown | |
d13800 | train | Yes. They will be retained. Your Update_Calls has an issue.
public static void Update_Calls()
{
for (int i = 0; i < callsForUpdate.Count; i++)
{
callsForUpdate.ElementAt(i)();
}
callsForUpdate.Clear();
}
You were only referring the element. Not calling it.
A: What you are creating is called Closure, which means that Action will be called with the current values of var1, var2, var3, in this case they are local variables of Extern_Func, so unless you change them in that method (Extern_Func) they will keep their value.
A: What you are doing is creating an expression pointed to by each item in the callsForUpdate list. Expressions are immutable. In order to change the values you supplied in an expression, the expression must be replaced by a new expression with new values.
In my best estimation of what you are asking is true for most any case because your list is simply a list of expressions to be executed with the values supplied at the time they were created by Etern_Func.
A: Closures capture variables, not values. Make sure that is clear.
In your case, var1, var2 and var3 are passed by value arguments that can only be changed locally. Therefore if you don't change them inside Extern_Func you are good to go.
To understand the difference between capturing values or variables, consider the following snippet:
var funcs = new List<Action>();
for (var i = 0; i < 5; i++)
{
var temp = i;
funcs.Add(() => Console.WriteLine(i));
funcs.Add(() => Console.WriteLine(temp));
}
foreach (var f in funcs)
{
f();
}
Can you guess the output? | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.