_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d14501 | val | Use a struct:
struct velocity
{
float x_component; /*ToDo - do you really need a float*/
float y_component;
};
This will be the most extensible option. You can extend to provide a constructor and other niceties such as computing the speed. Perhaps a class is more natural, where the data members are private by default.
A: If you have more than one return value, since C++11 you can return them as a std::tuple. No need to explicit declare a data struct.
e.g.
tuple<float,float> calcVelocity(/*parameters*/) {
// your code
return make_tuple(xvelocity,yvelocity);
}
Outside the function you can access the values by:
tuple mytuple = calcVelocity(/*parameters*/);
float xvelocity = get<0>(my_tuple);
float yvelocity = get<1>(my_tuple);
For pre-C++11 std::pair is also an option for just 2 values. But in this case the struct solution is more explicit. | unknown | |
d14502 | val | It's not required to use %23 in Search Query for Search Values `.
Instead of 'q' => '%23bookmyshow', use 'q' => 'bookmyshow'.
Also, You haven't request Twitter to get tweets. Read this Documentation. If this is your Token secret, i would suggest you to reset your keys right now. Go to Twitter Developer page to access your apps & reset it. | unknown | |
d14503 | val | By default, XML files in Android project will use a custom XML formatter intended for XML files (so it for example has different policies for whether attributes appear on separate lines and blank lines between elements depending on which type of resource file you're editing -- values, layouts, manifests, etc.)
You can edit these preferences under Preferences > Android > Editors.
If you want to use the default XML editor instead (which uses the settings path pointed to by others in this thread) you can also go to that preference page and turn off the custom formatter.
A: If you're using android xml editor check:
Window > Preferences > Android > Editors > Always remove empty lines between elements
A: set enable
Window -> Preference -> XML Files ->Editor ->Clear all blank lines
And than use code formatting
A: The Android layout editor has its own formatter. Perhaps it has its own preference page? | unknown | |
d14504 | val | to split a sentence, use String's .split() method
String [] splitter = text.split(" ");
this will break the sentence based on spaces. Then you can do whatever you need to the array
A: String text = JOptionPane.showInputDialog("Enter a sentence");
int count = 0;
char space = ' ';
int index = 0;
do
{
++ count;
++ index;
index = text.indexOf(space, index);
}
while (index != -1);
String[] array = new String[count];
index = 0;
int endIndex = 0;
for(int i = 0; i < count; i++)
{
endIndex = text.indexOf(space, index);
if(endIndex == -1)
{
array[i] = text.substring(index);
}else{
array[i] = text.substring(index, endIndex);
}
index = endIndex + 1;
}
for(String s : array)
{
System.out.println(s);
} | unknown | |
d14505 | val | Best to use:
SqlParameter
Eg:
var parameter = new SqlParameter();
parameter.ParameterName = "@paramName";
parameter.Direction = ParameterDirection.Input;
parameter.SqlDbType = SqlDbType.Int;
//parameter.IsNullable = true;
parameter.Value = DaysInStock; | unknown | |
d14506 | val | A SubGird associated with candidates will only show candidates that are already connected to collage.
When you create a new collage it does not exist yet so you can’t associate candidates with it anyway.
What you’re trying to do can only be accomplished via plug-in (server side code) and some JS that collects the selected candidates from a General SubGrid
That enlists all candidates. The JS should drill in to get selected candidates and save there guids (ids) in some arbitrary text field to be used in the plug-in.
Once candidates are related to this newly created collage you can see the association in the associated view on the navigation pane.
The easier way is to do it the way CRM intended it to be, which is to firstly create the collage record and then go to its associated candidates view and add them.
Good Luck | unknown | |
d14507 | val | I realized I have to push my serverside code to App Engine the same way I pushed my React code, with different yaml configs for node.js files. Thanks everyone! | unknown | |
d14508 | val | One way to do this is with a Javascript interface, like so:
class JavaScriptInterface {
@JavascriptInterface
public String getFileContents(){
// read the file into a String and return it here.
return "the contents of your file";
}
}
Then, to set the Javascript Interface on the webview:
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "android");
and in the js of the page inside the webview:
function getFileContents(){
var info = window.android.getFileContents();
return info;
}
This, however, is not asynchronous. if you want to implement this functionality in an async manner, you would instead:
*
*add a method in javascript called something like "populateFileContents(data)"
*call the window.android.getFileContents() from javascript,
*have that return nothing, only kick off (an asynctask probably) functionality that would read the file contents, then call, in the Java android code, webview.loadUrl("javascript:populateFileContents(data);"); - which would pass the data from the file back to the javascript, where you could do with it what you like.
A: Thanks #nebulae for answering.
However I solved my problem with some sort of digging around. I created a file using file writer and stored it in a folder in the internal SD card of Android (say folder name ABC file name XYZ).
I am then calling that file from my javascript using the absolute address of that file. The absolute address for the file ABC/XYZ is written in my JS as:
url: 'file:///storage/sdcard0/ABC/XYZ.txt',
This method does the trick. | unknown | |
d14509 | val | I'm thinking that you are storing an array of class Time.
You could do something like
((Time)get(i)).difference
Assuming that difference is an accessible field in the Time class. | unknown | |
d14510 | val | Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered. | unknown | |
d14511 | val | Select from the dataframe only the second line of each pair, which is the line
containing the separator, then use astype(str).apply(''.join...) to restrain the word
that can be on any value column on the original dataframe to a single string.
Iterate over each row using split with the word[i] of the respective row, after split
reinsert the separator back on the list, and with the recently created list build the
desired dataframe.
Input used as data.csv
title,Value,Value,Value,Value,Value
Very nice blue car haha,Very,nice,,car,haha
Very nice blue car haha,,,blue,,
A beautiful green building,A,,green,building,lol
A beautiful green building,,beautiful,,,
import pandas as pd
df = pd.read_csv("data.csv")
# second line of each pair
d1 = df[1::2]
d1 = d1.fillna("").reset_index(drop=True)
# get separators
word = d1.iloc[:,1:].astype(str).apply(''.join, axis=1)
strings = []
for i in range(len(d1.index)):
word_split = d1.iloc[i, 0].split(word[i])
word_split.insert(1, word[i])
strings.append(word_split)
dn = pd.DataFrame(strings)
dn.insert(0, "title", d1["title"])
print(dn)
Output from dn
title 0 1 2
0 Very nice blue car haha Very nice blue car haha
1 A beautiful green building A beautiful green building | unknown | |
d14512 | val | For types where you want to allow anything whatsoever as long as it is an object and not a primitive, you can use the object type. This should be the case for your B-like type parameters, whose values you have (in your tsplay link at the bottom) only constrained to any | undefined (which is just any, by the way).
For types where you want to make sure that the values are constrained to string or undefined, and you want to support optional properties, I'd create a type alias like this:
type OptStrDict<T> = { [K in keyof T]?: string }
You will use it to recursively constrain your type parameters like T extends OptStrDict<T>.
So your Request interface becomes, for example:
export interface Request<
Q extends OptStrDict<Q>,
H extends OptStrDict<H>,
B extends object
> {
queryParameters: Q;
headers: H;
body?: B;
}
I will dispense with writing out the full version of your code with these changes, but you can verify that this works via the Playground link below.
Note that re-use of the OptStrDict type alias will reduce verbosity of your code, especially if you shorten it to OSD or something. If you think that createHandler()'s type signature is still too wordy after this, I'm not sure how best to proceed; pragmatically speaking, having five constrained generic type parameters is going to take up some space no matter what you do. ♂️
Playground link to code | unknown | |
d14513 | val | You should be fine doing that, modules are constructed per request - there should be no need to use a before hook though, just stick that code in the start of your constructor as if you would when setting a property from a constructor parameter.
A: As @StevenRobbins said, you can, but the question is - why? For the snipped you provided, using local variable in the constructor is just enough.
I can envision few other reasons to want to have this:
*
*Your route(s) use a private methods to do their work. Then a private readonly field will work (for the same reasons, each module is constructed per request). Or even better, make these private functions to accept myThing as parameter, and still use local var in ctor.
*You want to access this outside of the module - it's better to create your own class to hold this outside the module. Register it "per request" and have a beforerequest hook to fill the data, and inject into whatever other functionality needs it.
To elaborate on (2):
public interface IMyThingBag
{
MyThing MyThing{get;set;}
}
public class MyBagFiller : IRequestStartup
{
private readonly IMyThingBag _bag;
public MyBagFiller(IMyThingBag bad)
{
_bad = bag;
}
public void Initialize(IPipelines pipelines, NancyContext context)
{
_bag.MyThing = new MyThing{.....};
}
}
Now, anywhere in the chain (need to have the parts registered per request), you can inject the bag and use the thing :)
You can even inject it in the module if you need the data there. | unknown | |
d14514 | val | Sounds like you need the TAdvSpreadGrid from TMS instead. It's an enchanced version of TAdvStringGrid that has support for the formulas as well.
If you need even more Excel Support they have TMS FlexCel Studio that is very nice.
A: I use TAdvSpreadGrid from TMS also. For reading and writing really spiffy spreadsheets with support for formulas, nice formatting and even pane freezing to make data editing easier for my clients, I use Native Excel. It's fast, has good documentation, and is easy to use. It's worth a look.
A: While the previous answers aren't wrong, I found another solution.
I tried adding the calculation (e.g. =A1+B1) to the cell as plain text. When copying to Excel it accepts my formula as an Excel formula and calculates it just like I want it.
No need to splash out more money on TAdvSpreadGrid or something else. :-) | unknown | |
d14515 | val | FormData can handle multiple files, even under the same field name. If the API supports it, build up your request payload and send it once
export const uploadImages =
({ images }) =>
async (dispatch) => { // async here
const formData = new FormData();
images.forEach(image => {
formData.append(image.name, image.imageFile);
})
// as per usual from here...
};
Otherwise, you'll need to chunk the progress by the number of images, treating the average as the total progress.
export const uploadImages =
({ images }) =>
async (dispatch) => {
const imageCount = images.length;
const chunks = Array.from({ length: imageCount }, () => 0);
await Promise.all(images.map(async (image, index) => {
// snip...
await axios.post(url, formData, {
onUploadProgress({ loaded, total }) {
// for debugging
console.log(
"chunk:", index,
"loaded:", loaded,
"total:", total,
"ratio:", loaded / total
);
// store this chunk's progress ratio
chunks[index] = loaded / total;
// the average of chunks represents the total progress
const avg = chunks.reduce((sum, p) => sum + p, 0) / chunks.length;
dispatch(setUploadProgress(Math.floor(avg * 100)));
}
});
// snip...
});
// snip...
};
Note that the upload progress can reach 100% before the request actually completes. To handle that, you may want something in your store that detects when the uploadProgress is set to 100 and set another state (finalisingUpload = true for example) that you can clear after the request complete.
Here's a quick demo using mocks showing how the logic works ~ https://jsfiddle.net/rtLvxkb2/ | unknown | |
d14516 | val | It seems there is! From re documentation:
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
the (optional) no pattern otherwise.
Which makes the example this:
rx = re.compile(r'(?P<prefix>(?P<prefix_two>)\w{2}(?= \d{2})|(?P<prefix_four>)\w{4}(?= \d{4})) (?P<digits>(?(prefix_two))\d{2}|(?(prefix_four))\d{4})')
def get_id(s):
m = rx.match(s)
if not m:
return (None, None,)
return m.group('prefix', 'digits')
print(get_id('AA 12')) # ('AA', 12)
print(get_id('BB 1234')) # ('BB', 12)
print(get_id('BBBB 12')) # (None, None)
print(get_id('BBBB 1234')) # ('BBBB', 1234)
Whether it’s worth the trouble, I’ll leave up to the reader. | unknown | |
d14517 | val | It is possible to parse a JSON in a text field by ignoring any hierarchy and only looking for a specific field. In your case the field names were title and city . Please be aware that this approach is not save for user entered data: By setting the value of the "city":"\" hide \"" the script cannot extract the city.
select *,
REGEXP_EXTRACT(data, r'"title":\s*"([^"]+)') as title,
REGEXP_EXTRACT(data, r'"city":\s*"([^"]+)') as city
from(
Select ' { "address":{ "city":"This is what i want", "country":"blablabla", "lineAdresse":"blablabla", "region":"blablabla", "zipCode":"blablabla" }, "contract":"blablabla", "dataType":"blablabla", "description":"blablabla", "endDate":{ "_seconds":1625841747, "_nanoseconds":690000000 }, "entreprise":{ "denomination":"blabla", "description":"1", "logo":"blablabla", "blabla":"blablabla", "verified":"false" }, "id":"16256R8TOUHJG", "idEntreprise":"blablabla", "jobType":"blablabla", "listInfosRh":null, "listeCandidats":[ ], "field":0, "field":0, "field":14, "field":"1625834547690", "field":true, "field":"", "field":"ref1625834547690", "skills":[ "field", "field", "field" ], "startDate":{ "_seconds":1625841747, "_nanoseconds":690000000 }, "status":true, "title":"this I can extract", "urlRedirection":"blablabla", "validated":true }' as data
) | unknown | |
d14518 | val | I'm not sure exactly what you want, as there is some undefined values and syntax errors in your code, but here is an example on how to create elements from an array and add to an existing ul element:
$(function(){
$.each(['link1', 'link2', 'link3', 'link4', 'link5'], function(i, link){
$('<li/>')
.append(
$('<a/>')
.attr({ 'class': 'c' + i, ref: i, href: 'page.php#' + link })
.text(link)
).appendTo('ul');
});
});
With the existing ul element, it produces:
<ul>
<li><a class="c0" ref="0" href="page.php#link1">link1</a></li>
<li><a class="c1" ref="1" href="page.php#link2">link2</a></li>
<li><a class="c2" ref="2" href="page.php#link3">link3</a></li>
<li><a class="c3" ref="3" href="page.php#link4">link4</a></li>
<li><a class="c4" ref="4" href="page.php#link5">link5</a></li>
</ul>
(In place of the array literal [...] you could of course use an array variable.)
A: something like this?:
*Edit II * for comment
var link = ['strategy', 'branding', 'marketing', 'media', 'management'],
refNumericId = $("."+ numericId);
$(link).each(function(i, el){
$("<li></li>")
.attr("id", numericId + "_" + (i+1))
.attr("class", numericId + (i+1))
.html("<a href=\"capabilities.php#"+el+"\"></a>")
.appendTo(refNumericId);
});
I saw your code in the file 'easySlider1.7.js' and you're including in 'for' of the line 123 the code 'var link = [' strategy,''which should go after this 'for' | unknown | |
d14519 | val | I don't know if you managed to find the solution to your issue but the first problem in that config file is that the auth rules are matched in order. All your requests are matching the deny first and you never get to evaluate the access for USER1 and USER2. | unknown | |
d14520 | val | First of all, take a look at this SO on reasons not to use Vector. That being said:
1) Vector locks on every operation. That means it only allows one thread at a time to call any of its operations (get,set,add,etc.). There is nothing preventing multiple threads from modifying Bs or their members because they can obtain a reference to them at different times. The only guarantee with Vector (or classes that have similar synchronization policies) is that no two threads can concurrently modify the vector and thus get into a race condition (which could throw ConcurrentModificationException and/or lead to undefined behavior);
2) As above, there is nothing preventing multiple threads to access Cs at the same time because they can obtain a reference to them at different times.
If you need to protect the state of an object, you need to do it as close to the state as possible. Java has no concept of a thread owning an object. So in your case, if you want to prevent many threads from calling setSameString concurrently, you need to declare the method synchronized.
I recommend the excellent book by Brian Goetz on concurrency for more on the topic.
A: In case 2. It's not thread-safe because multiple threads could visit the data at the same time. Consider using read-write lock if you want to achieve better performance. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html#readLock() | unknown | |
d14521 | val | You are missing the tables aliases:
SELECT
employees.name AS employee_name,
employees.role AS employee_role,
depatments.name AS department_name
FROM
`strategic-volt-320816.employee_data.employees` employees
INNER JOIN
`strategic-volt-320816.employee_data.departments` departments
ON
employees.department_id = departments.department_id | unknown | |
d14522 | val | 1: Install ImageMagick software Link
2: Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3: Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4: Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5: Restart your server
A: cmorrissey's link for 2) seems to be broken but dlls can be downloaded here.
If you get a "CORE_RL_wand_.dll is missing" error, the solution is here. In my case, I had to take all the "CORE" dlls from the ImageMagic installation folder and copy them into the /php folder. | unknown | |
d14523 | val | You have to make a small change in css.
a:hover {
color:#adff2f;
font-weight: 400;
letter-spacing: 5px;
}
You have to remove letter-spacing: 5px; from css file.
then code looks like :
a:hover {
color:#adff2f;
font-weight: 400;
}
A: based on what you've mentioned, it sounds like you're trying to have a generic pop-up/modal as a HTML element and then when you click on different illustrations it will open the modal and the modal would contain some text related to that illustration that you clicked on.
What you want to do, is keep your modal, which appears to be the #popup element, add an onclick to each illustration that runs a function which dynamically injects some text by targetting the heading where you need the text to be, for example:
toggleModal (title, subtitle) {
const headingEl = document.querySelector('[data-your-heading]')
const subtitleEl = document.querySelector('[data-your-subtitle]')
headingEl.innerText = title
subtitleEl.innerText = subtitle
// run some code to hide/show the modal below here
}
Next, attach the data-your-* attributes to whichever tag you want to update text with, for instance a <p> tag within your generic HTML modal/pop-up.
And then on each of your illustrations, you add an onclick function and pass the arguments of what text you want, for example:
<button type="button" onclick="toggleModal('My Title', 'My Subtitle')">Show Illustration 1</button> | unknown | |
d14524 | val | Django 1.9 has authentication mixins for class based views. You can use the UserPassesTest mixin as follows.
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class UserSettingsView(LoginRequiredMixin, UserPassesTestMixin, View):
def test_func(self):
return test_settings(self.request.user)
def get_login_url(self):
if not self.request.user.is_authenticated():
return super(UserSettingsView, self).get_login_url()
else:
return '/accounts/usertype/'
Note that in this case you have to override get_login_url, because you want to redirect to a different url depending on whether the user is not logged in, or is logged in but fails the test.
For Django 1.8 and earlier, you should decorate the dispatch method, not get_initial.
@method_decorator(user_passes_test(test_settings, login_url='/accounts/usertype/'))
def dispatch(self, *args, **kwargs):
return super(UserSettingsView, self).dispatch(*args, **kwargs) | unknown | |
d14525 | val | The Relay specification only requires that your schema include a Node interface -- when creating a Relay-compliant, normally you don't create interfaces for Connection and Edge.
The reason Relay requires a Node interface is to allow us to query for any Node by id. However, typically there's no need for a field that returns one of many edges or one of many connections. Therefore, typically there's no need to need to make an interface for edges or connections. This is what you would normally do:
interface Node {
id: ID!
}
interface Group {
id: ID!
type: String!
}
type GroupA implements Node & Group {
id: ID!
type: String!
# other fields
}
type GroupA implements Node & Group {
id: ID!
type: String!
# other fields
}
type GroupEdge {
cursor: String!
node: Group!
}
type GroupConnection {
edges: [GroupEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
According to the spec, "the [implementing] object type must include a field of the same name for every field defined in an interface." So, if an interface specifies that a field is of the type Foo, an implementing type cannot have the field be of type FooBar even if Foo is an interface and FooBar implements it. Unfortunately, that means it's not really possible to use interfaces like you're trying to do.
If you would like to utilize interfaces to provide a safety-net of sorts and ensure that the implementing types are consistent, you can do something like this:
interface Connection {
pageInfo: PageInfo!
# don't specify edges
}
interface Edge {
cursor: String!
# don't specify node
}
This way you can ensure that fields like pageInfo or cursor are present in the implementing types, have the correct type and are non-null. But this kind of schema-level validation is really the only benefit you get out adding and implementing these two interfaces. | unknown | |
d14526 | val | You can loop through all markers and look which has the shortest distance. map.distance(USER_LATLNG, BIKE_STATION_LATLNG) | unknown | |
d14527 | val | Not sure what the info object is but you're adding it in both queries:
info.SectionInfo = "Indepth Inquiries";
info.Result = Indepth.Count();
QuarterlyInfo.Add(info);
info.SectionInfo = "Indepth Inquiries";
info.Result = Indepth.Count();
QuarterlyInfo.Add(info);
that might account for the dupes? | unknown | |
d14528 | val | You can try js_cols, a collections library for JavaScript.
A: Can't you use the jquery collection plugin.
http://plugins.jquery.com/project/Collection
A: jQuery's primary focus is the DOM. It doesn't and shouldn't try and be all things to all people, so it doesn't have much in the way of collections support.
For maps and sets, I'd like to shamelessly point you in the direction of my own implementations of these: http://code.google.com/p/jshashtable/
Regarding lists, Array provides much of what you need. Like most methods you might want for arrays, you can knock together a contains() method in a few lines (most of which are to deal with IE <= 8's lack of support for the indexOf() method):
Array.prototype.contains = Array.prototype.indexOf ?
function(val) {
return this.indexOf(val) > -1;
} :
function(val) {
var i = this.length;
while (i--) {
if (this[i] === val) {
return true;
}
}
return false;
};
["a", "b", "c"].contains("a"); // true
A: You can also try buckets, it has the most used collections.
A: Since javascript have both arrays [] and associative arrays {}, most needs for datstructures are already solved. The array solves the ordered list, fast access by numeric index whilst the associative array can be considered a unordered hashmap and solves the fast access by string keys.
For me that covers 95% of my data structure needs.
A: If you get some free time you can checkout.
https://github.com/somnathpanja/jscollection | unknown | |
d14529 | val | According to the documentation for MATCH:
MATCH returns the position of the matched value within lookup_array, not the value itself.
and with 0as the optional third argument (match_type):
If match_type is 0, MATCH finds the first value that is exactly equal to lookup_value. Lookup_array can be in any order.
So the returned 1refers to the position on B19in the array Range("B19:B30") and the code sample is indeed behaving as expected.
A: Application.Match("name", ActiveSheet.Range("B19:B30"), 0)
The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range
So parsing the parameter ActiveSheet.Range("B19:B30") means that B19 equals relative position =1.
A: add slgn
Sub mat()
Y = Application.Match(slng(range("a4").value), ActiveSheet.Range("B19:B30"), 0)
MsgBox Y
End Sub
ex2:
Application.WorksheetFunction.Match(CLng(TextBox1.Text), sheet110.Range("B6:B" & ls), 0) | unknown | |
d14530 | val | Ok, it's not ideal but you can use notepad++.
It had a "find and replace" feature and you can use \t to replace tabs as \n
Then you can record a macro to move any given line to the previous, skipping lines.
Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead of commas
Another option is to read each line,and process it separately. Basically a while loop with the condition being not m_line == null
Then inside the loop, split the string up with str.split ()
And have another loop that makes a dictionary, for each row. In the end, you'd have a list of dictionaries where each entry is ID:frequency
A: Have you tried work separately with each item?
For example:
Open document:
with open('delimiters.txt') as r:
lines = r.readlines()
linecontent = ' '.join(lines)
Create a list for each item:
result = linecontent.replace(' ', ',').split(',')
Create sublist for ids and freqs:
newResult = [result[x:x+2] for x in range(0, len(result), 2)]
Working with each data type:
ids = [x[0][:] for x in newResult]
freq = [x[1][:] for x in newResult]
Create a DataFrame
df = pandas.DataFrame({'A ids': ids, 'B freq': freq})
A: Here's what I did.
This creates a dictionary containing key-value pairs
from each row.
data = []
with open('../data/input.mat', 'r') as file:
for i, line in enumerate(file):
l = line.split()
d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
data.append(d) | unknown | |
d14531 | val | Thanks to @special N9NE
This works: define an own ripple ripple_bg.xml:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/accent_26" />
And set it as background (globally):
<resources>
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- ... -->
<!-- custom checkbox style to improve visibility on special (TV) devices -->
<item name="android:checkboxStyle">@style/MyCheckBoxStyle</item>
</style>
<style name="MyCheckBoxStyle" parent="Widget.AppCompat.CompoundButton.CheckBox">
<item name="android:background">@drawable/ripple_bg</item>
</style>
</resources>
A: You can check this blog: AppCompat themes
colorControlHighlight is for ripple color
So try to create a ThemeOverlay.AppCompat theme where you will set the value of the color that you want and that will allow you to change the ripple color for that view and its children.
To target ripple in theme use this attribute:
android:colorControlHighlight
A: you can use the theme attribute:
app:theme="@style/MyCheckboxStyle"
then add this in your style.xml file :
<style name="MyCheckboxStyle" parent="AppTheme">
<item name="colorAccent">@color/colorAccent</item> // color when checkbox is checked
<item name="android:textColorSecondary">@color/colorSecondary</item> // when it is unchecked
</style> | unknown | |
d14532 | val | Never figured out a way to deal configure DictReader to do this for me, but in the meantime, I did wind up just manually sanitizing each row with this helper function:
def __sanitize__(row):
for key, value in row.items():
if value in ('', ' '):
row[key] = None
return row
Still hope someone can come along with a sexier answer! | unknown | |
d14533 | val | Try this..
Your getting response as JSONArray like below
JSON
[ //JSONArray array
{ //JSONObject jObj
"CityName": "Jaipur", //optString cityName
"CityId": 1 //optInt CityId
},
{
"CityName": "Jodhpur",
"CityId": 2
},
{
"CityName": "Ajmer",
"CityId": 3
},
{
"CityName": "Bikaner",
"CityId": 4
}
]
Code
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jObj = array.optJSONObject(i);
String cityName = jObj.optString("CityName");
int CityId = jObj.optInt("CityId");
Log.v("cityName :",""+cityName);
Log.v("CityId :",""+CityId);
}
A: try this one
JSONArray jarray =new JSONArray(response);
String[] cityName = new String[jarray.length()]
JSONObject jObject=null;
for(int j=0;j<jarray.length();j++){
jObject=jarray.getJSONObject(j);
cityName[j]=jObject.getString("CityName");
}
A: Do like this
ArrayList<String> cityname=new ArrayList<String>();
JSONArray jsonarr=new JSONArray(string);
for(i=0;i<jsonarr.length();i++){
cityname.add(jsonarr.getJSONObject(i).getString("CityName"));
}
A: Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
String CityName= mainObject .getJSONObject("CityName");
String CityId= mainObject .getJSONObject("CityId");
...
A: Try this:
JSONArray jsonArray= jsonResponse.getJSONArray("your_json_array_name");
for (int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name = jsonObject.getString("CityName");
String id = jsonObject.getString("CityId");
}
A: You can use json-path library it will simplifies the JSON parsing.
You can download json-path lib from here
Then add this library to your project /libs/ folder.
Then import the project name like this
import com.jayway.jsonpath.JsonPath;
Then parse your JSON data like this
JSONArray jsonData= new JSONArray(JsonPath.read(jsonStringData,"$..CityId[*]").toString()); | unknown | |
d14534 | val | There's no magic flag to have a UIView not rotate, but you could rotate it back with the following code:
-(void) viewDidLoad {
[super viewDidLoad];
// Request to turn on accelerometer and begin receiving accelerometer events
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)orientationChanged:(NSNotification *)notification {
// Respond to changes in device orientation
switch ([UIDevice currentDevice].orientation)
{
case UIDeviceOrientationLandscapeLeft:
self.img.transform = CGAffineTransformMakeRotation(-M_PI/2);
break;
case UIDeviceOrientationLandscapeRight:
self.img.transform = CGAffineTransformMakeRotation(M_PI/2);
break;
case UIDeviceOrientationPortrait:
self.img.transform = CGAffineTransformMakeRotation(0);
break;
case UIDeviceOrientationPortraitUpsideDown:
self.img.transform = CGAffineTransformMakeRotation(0);
break;
case UIDeviceOrientationFaceUp:
break;
case UIDeviceOrientationFaceDown:
break;
case UIDeviceOrientationUnknown:
break;
}
}
-(void) viewDidDisappear {
// Request to stop receiving accelerometer events and turn off accelerometer
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
} | unknown | |
d14535 | val | That is because of how the stroke is done in SVG. It is done something like half-and-half, that is, the stroke is half from 0 to 1 and the other half is -1 to 0 (if you get what I mean) and so you see a thinner stroke.
You can refer the Stroke section in this MDN page to see what I mean. They've put it as follows:
Strokes are drawn centered around the path
If you make the points as 10,1 and 30,1 you would see the same stroke width. Reason for this is that the stroke is now kind of between 0 to 2 on the Y-axis (half of the stroke is on top of the point and half is on the bottom).
<svg>
<polyline points="10 1, 30 1,10 10,30 10" fill="none" stroke-width="2px" stroke="#19af5c"></polyline>
</svg> | unknown | |
d14536 | val | You can use NUnit Console to run the tests from command line. So first download the NUnit Console ZIP package from here and unzip binaries. Create a new .net Console project as you have done it and call nunit3-console.exe to run tests through process.start method, as below:
public static void Main(String[] args)
{
RunTests();
}
private static void RunTests()
{
string outputFolder = @"E:\OutputFolder";
string testDllPath = @"E:\Projects\TestProj\bin\Debug\netcoreapp3.1\TestProjTests.dll";
//exeFilePath is where you unzipped NUnit console binaries
string exeFilePath = @"E:\Tools\NUnit.Console-3.12.0\bin\netcoreapp3.1\nunit3-console.exe";
//or E:\Tools\NUnit.Console-3.12.0\bin\net35 for .net framework based tests proj
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = exeFilePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "\"" + testDllPath + "\" --work=\"" + outputFolder + "\"";
try
{
// Start the process with the info we specified.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception ex)
{
// Log error.
string msg = ex.Message;
}
}
Once completed you will get the TestResult.xml file generated in outputFolder | unknown | |
d14537 | val | It seems that
'abc' in myObject
is being evaluated as:
for i in myObject:
if myObject[i] == 'abc':
return true
Where i is an integer.
Try implementing the __contains__(self, value) magic method. | unknown | |
d14538 | val | You should add explicit wait for this button:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.implicitly_wait(10)
driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="uc-btn-accept-banner"]')))
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()
Your locator is correct.
As css selector, you can use .uc-btn-footer-container .uc-btn.uc-btn-primary | unknown | |
d14539 | val | If you have many such values to check you can use grep/list:
use strict;
use warnings;
my %hash;
my $val1 = undef;
my $val2 = 10;
$hash{$_->[0]} = $_->[1] for grep { defined $_->[1] }
['key1', $val1], ['key2', $val2];
Or you can filter the hash after populating it blindly:
$hash{key1} = $val1;
$hash{key2} = $val2;
%hash = map { $_, $hash{$_} } grep { defined $hash{$_} } keys %hash;
A: Write a subroutine.
set( \%hash, $key1, $val1 );
set( \&hash, $key2, $val2 );
sub set {
my $hash = shift;
my $key = shift;
my $val = shift;
$hash->{$key} = $val if defined $val;
} | unknown | |
d14540 | val | It generates the next number by keeping some state and modifying the state every time you call the function. Such a function is called a pseudorandom number generator. An old method of creating a PRNG is the linear congruential generator, which is easy enough:
static int rand_state;
int rand(void)
{
rand_state = (rand_state * 1103515245 + 12345) & 0x7fffffff;
return rand_state;
}
As you can see, this method allows you to predict the next number in the series if you know the previous number. There are more sophisticated methods.
Various types of pseudorandom number generators have been designed for specific purposes. There are secure PRNGs which are slow but hard to predict even if you know how they work, and there are big PRNGs like Mersenne Twister which have nice distribution properties and are therefore useful for writing Monte Carlo simulations.
As a rule of thumb, a linear congruential generator is good enough for writing a game (how much damage does the monster deal) but not good enough for writing a simulation. There is a colorful history of researchers who have chosen poor PRNGs for their programs; the results of their simulations are suspect as a result.
A: If C++ is also acceptable for you, have a look at Boost.
http://www.boost.org/doc/libs/1_51_0/doc/html/boost_random/reference.html
It does not only offer one generator, but several dozen, and gives an overview of speed, memory requirement and randomness quality. | unknown | |
d14541 | val | StepVerifier#withVirtualTime replaces ALL default Schedulers with the virtual time one, so it is not a good idea to use it in parallel | unknown | |
d14542 | val | First of all, what if Firebase.firestore? Are you checking if that variable is returning an app or an instance? Or, you just debug it using for example: Log.e("TAG", "$db") or using the Android debugger.
To debug inside of the lambda I recommend you to use the following code:
db.collection("Users").get()
.addOnCompleteListener(object : OnCompleteListener<QuerySnapshot?> {
override fun onComplete(task: Task<QuerySnapshot?>) {
if (task.isSuccessful) {
for (document in task.result!!) {
val user = User(document.data["name"] as String, document.data["email"] as String)
userList.add(user)
}
Log.d(TAG, userList.toString())
} else {
Log.d(TAG, "Error getting documents: ", task.exception)
}
}
})
In that block you can use the Android Debugger because it's not a lambda function, so, when you figured out the null data and fixed it you can switch the object function to a lambda. | unknown | |
d14543 | val | Create module which you would like to secure, for example
/app/backend/modules/sfGuardRegister
After that you can secure the module with creating
/module_path/config/security.yml
and configure credentials.
I have not tryed that beheivour with security.yml, but I've rewroten the templates, actions, components. It should work. | unknown | |
d14544 | val | You can get columns of primary key.
This returns the names and data types of all columns of the primary
key for the tablename table:
SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_index i
JOIN pg_attribute a ON a.attrelid = i.indrelid
AND a.attnum = ANY(i.indkey)
WHERE i.indrelid = 'tablename'::regclass
AND i.indisprimary;
(source)
Here used the fact that primary key's uniqueness is handled by Postgres via index, so you can use pg_index table. | unknown | |
d14545 | val | I solved this thanks to the help of a number of people in this question - Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
It wasn't a Travis CI issue after all. It's all explained in the link above. | unknown | |
d14546 | val | Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).
http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)
(This URL refuses to become a hyperlink for some reason (?))
A: It's hard to say without more details or more surrounding code, but my initial suspicion is that the file your are trying to load is in a format not supported by the device.
A: Let us have a look at the docs: IllegalArgumentException is thrown
if imageData is incorrectly formatted or otherwise cannot be decoded
So the possible reason can be either unsupported format of the image, or truncated data. Remember, you should pass entire file to that method, including all the headers. If you have doubts about the format, you'd better choose PNG, it must be supported anyway.
A: I just had the same problem with my MIDLET and the problem in my case was the HTTP header that comes along the JPEG image that I read from the socket's InputStream. And I solved it by finding the JPEG SOI marker that is identified by two bytes: FFD8 in my byte array. Then when I find the location of the FFD8 in my byte array, I trim the starting bytes that represent the HTTP header, and then I could call createImage() without any Exception being thrown...
You should check if this is the case with you. Just check is this true (temp[0] == 0xFF && temp[1] == 0xD8) and if it is not, trim the start of temp so you remove HTTP header or some other junk...
P.S.
I presume that you are reading JPEG image, if not, look for the appropriate header in the temp array.
Also if this doesn't help, and you are reading JPEG image make sure that the array starts with FFD8 and ends with FFD9 (which is the EOI marker). And if it doesn't end with the EOI just trim the end like I explained for SOI...
P.P.S
And if you find that the data in temp is valid, then your platform cannot decode the JPEG images or the image in temp is to large for JPEG decoder. | unknown | |
d14547 | val | class Program
{
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"c:\temp");
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.EnableRaisingEvents = true;
Console.ReadLine();
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was created", e.FullPath);
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("{0} was Renamed", e.FullPath);
}
static void fsw_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was Deleted", e.FullPath);
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was Changed", e.FullPath);
}
}
A: Microsoft Windows, and its ultimate ancestor MS-DOS, has always had an attribute on its files that indicates whether that file was changed since the last time that attribute was cleared, sort of a "dirty flag". It was used in the past by backup programs to find those files that needed to be backed up incrementally, and then cleared when a copy of that file had been made.
You can use File.GetAttributes to get the attributes on a file, and use File.SetAttributes to clear that "Archive" attribute. The next time that file is opened for writing, that archive flag will be set again.
Be careful about copying files that have been changed, as those files may still be open. You probably want to avoid concurrency problems by opening them for read exclusively when copying, and if that fails you know that file is still open for writing.
A: To all who responded with, use FileSystemWatcher, how do you deal with the time your app isn't running? For example, the user has rebooted the box, modified the file you are interested in, and then starts up your app?
Be sure to also read the docs on FileSystemWatcher Class carefully specially the section about Events and Buffer Sizes.
A: You can use a FileSystemWatcher object. This raises events on changes to files within the specified watched folder.
A: You're likely to run into issues with FileSystemWatcher (not getting events, too many events, etc.) This code wraps it up and solves many of them:
http://precisionsoftware.blogspot.com/2009/05/filesystemwatcher-done-right.html
A: You will have to note the modified date of files which you want to check.
After certain period you can check if the file was modified later.
If the file is modified with different date and time, you can make the copy. | unknown | |
d14548 | val | Please refer to the Transaction Flow in the documentation. Furthermore, Please check out the Key Concept Section too (Both Ledger and Ordering Service for you to understand the flow and also what is inside a block).
Committing peers do not create new blocks, they execute, validate and commit the block created by orderer to their ledger. The signing is done by Endorsing Peers using private key with ECDSA-SHA256 signing. Then of course, verification uses ECDSA-SHA256 too.
Validation is basically executing the read write set and check if the output is deterministic (and thus the result should be same with all other nodes).
I am over simplifying here tho. | unknown | |
d14549 | val | public static void main(String[] args) {
int array[] = {10, 20, 30, 10, 40, 50};
System.out.println(hasDuplicates(array));
}
public static boolean hasDuplicates(int[] array) {
var distinct = Arrays.stream(array).distinct().count();
return distinct != array.length;
}
A: your code return false because its stops when first cycle says its false
and after that your for statement return false
instead of "return false" you can change a bit
public boolean hasDuplicates2()
{
bool hasDuclicates = false;
for (int i = 0; i < array.length; i++) {
for (int i2 = i+1; i2 < array.length - 1; i2++) {
if (array[i] == array[i2]) {
hasDuplicates = true;
}
}
}
return hasDuplicates;
}
it may not be efficient by the way
A: So a couple of problems:
1)You need to have array.length - 1 even in the first for loop, or you're going to go out of range at the last iteration.
2)You're checking each and every element including the element itself - which means when i = i2, you're always going to satisfy the if condition, so you need to check for that as well.
Try this:
public static boolean hasDuplicates2(int[] array) {
for (int i = 0; i <= array.length - 1; i++) {
for (int i2 = 1; i2 <= array.length - 1; i2++) {
if (i != i2 && array[i] == array[i2]) {
return true;
}
}
}
return false;
} | unknown | |
d14550 | val | #lock! uses SELECT … FOR UPDATE to acquire a lock.
According to PostgreSQL doc.
FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being locked, modified or deleted by other transactions until the current transaction ends.
You need a transaction to keep holding a lock of a certain row.
Try
console1:
Plan.transaction{Plan.find(12).lock!; sleep 100.days}
console2:
p = Plan.find(12)
p.name = 'should not be able to be stored in database'
p.save
#with_lock acquire a transaction for you, so you don't need explicit transaction.
(This is PostgreSQL document. But I think other databases implement similar logic. ) | unknown | |
d14551 | val | That is because you are iterating over all li when iterating over array and setting the value. jquery .text() accepts function as argument which accepts index as parameter. This will eliminates the need of iterating over li and array elements:
var arr = ['a','b','c'];
$('li').text(function(i){
return arr[i];
});
Working Demo
A: First, you set the text of all li to 'a', then to 'b' and finally to 'c'.
Instead, you may try iterating the li elements, and set the text content of the current one to the corresponding item in arr:
var arr = ['a','b','c'];
$('li').each(function(i) {
$(this).text(arr[i]);
});
var arr = ['a','b','c'];
$('li').each(function(i) {
$(this).text(arr[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
Alternatively (but similarly), you can iterate the array, and set the text content of the corresponding li to the current value:
var arr = ['a','b','c'],
$li = $('li');
arr.forEach(function(txt, i) {
$li.eq(i).text(txt);
});
var arr = ['a','b','c'],
$li = $('li');
arr.forEach(function(txt, i) {
$li.eq(i).text(txt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
A: You should iterate by arr, not by all li elements, you can do it like this:
arr = ['a','b','c'];
$.each(arr, function(i,v){
$('li').eq(i).text(v);
});
This way you will assign exactly the same number of li text as there is elements in the array.
A: In your code, everytime the outer iterator performed, all <li> was texted with the iteration result. So as a result you'll get all 'c'.
To do it right, you should code like this:
arr = ['a','b','c'];
$('li').each(function(index) {
$(this).text(arr[index]);
});
A: The jQuery each() function will pass in an index, which you can use
arr = ['a','b','c'];
$('li').each(function(i) {
$(this).text(arr[i]);
}); | unknown | |
d14552 | val | Installing python with pyenv with ucs2:
$ export PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs2
$ pyenv install -v 2.7.11
...
$ pyenv local 2.7.11
$ pyenv versions
system
* 2.7.11 (set by /home/nwani/.python-version)
$ /home/nwani/.pyenv/shims/python
Python 2.7.11 (default, Aug 13 2016, 13:42:13)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sysconfig
>>> sysconfig.get_config_vars()['CONFIG_ARGS']
"'--prefix=/home/nwani/.pyenv/versions/2.7.11' '--enable-unicode=ucs2' '--libdir=/home/nwani/.pyenv/versions/2.7.11/lib' 'LDFLAGS=-L/home/nwani/.pyenv/versions/2.7.11/lib ' 'CPPFLAGS=-I/home/nwani/.pyenv/versions/2.7.11/include '"
Installing python with pyenv with ucs4:
$ pyenv uninstall 2.7.11
pyenv: remove /home/nwani/.pyenv/versions/2.7.11? y
$ export PYTHON_CONFIGURE_OPTS=--enable-unicode=ucs4
$ pyenv install -v 2.7.11
...
$ pyenv local 2.7.11
$ pyenv versions
system
* 2.7.11 (set by /home/nwani/.python-version)
$ /home/nwani/.pyenv/shims/python
Python 2.7.11 (default, Aug 13 2016, 13:49:09)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sysconfig
>>> sysconfig.get_config_vars()['CONFIG_ARGS']
"'--prefix=/home/nwani/.pyenv/versions/2.7.11' '--enable-unicode=ucs4' '--libdir=/home/nwani/.pyenv/versions/2.7.11/lib' 'LDFLAGS=-L/home/nwani/.pyenv/versions/2.7.11/lib ' 'CPPFLAGS=-I/home/nwani/.pyenv/versions/2.7.11/include '" | unknown | |
d14553 | val | try json_encode
for more refer -
http://php.net/manual/en/function.json-encode.php
A: stringify before sending
Eg :
var postData = [
{ "id":"1", "name":"bob"},
{ "id":"2", "name":"jonas"}]
this works,
$.ajax({
url: Url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(postData) //stringify is important,
});
A: Do it like so, using jQuery(which you need to include in your script):
<script>
var data={};
data= {
"title":"mr",
"fname":"john",
"lname":"Annah",
"oname":"Clement",
"staffid":"123"};
$.ajax({
url:"somwhere.php",
type:"POST",
dataType:"JSON",
data:data,
async: true});
</script>
And on the page where you want to catch this data, do it like this:
<?php
$title=$_POST['title'];
$fname=$_POST['fname'];
?>
And so on.
A: Try this
$(document).on("click", "#your element", function () {
$.ajax({
type: 'POST',
url: "your_url",
data : {"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"},,
success: function (result) {
### your action after ajax
},
})
})
A: you can pass it in data like this,
$.ajax({
url: 'url',
type: 'GET',
data: { title:"mr",fname:"john",lname:"Annah",oname:"Clement",staffid:"123" } ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
}
}); | unknown | |
d14554 | val | For historic reasons SDN up to 3.2.2 heavily uses core Neo4j API calls. While this is fast for embedded it slows down when connected via REST.
The following blog post explains this in regards to history and future of SDN: Spring Data Neo4j 3.3.0 – Improving Remoting Performance.
Apart from the SDN 3.3.0 performance gains there is also a rewritten SDN in the works that specifically focusses on Neo4j over REST via Cypher: SDN4 / neo4j-ogm. | unknown | |
d14555 | val | In SQL Server, you would use row_number() and a CTE:
with toupdate as (
select t.*, row_number() over (partition by UserId order by SeqId) as seqnum
from table t
)
update toupdate
set rownum = seqnum; | unknown | |
d14556 | val | I'm afraid the webmaster of the domain has set XSS protection. So to load a XSS protected site with javascript is simply can't be done.
Update: XSS only allow access to data if both frames (iframe/parent frame) they are on the same protocol, have the exact domain name (mysite.com == mysite.com, but www.mysite.com != mysite.com they are considered different) and both of frames running on the same port. But though, you can ive it a try by placing document.domain on all pages so it allows communication even on different subdomains. | unknown | |
d14557 | val | I think this should do the job and is a bit simpler. It just keeps track of files at next level, expands them, then repeats the process. The algorithm itself keeps track of depth so there is no need for that extra class.
// start in home directory.
File root = new File(System.getProperty("user.dir"));
List<File> expand = new LinkedList<File>();
expand.add(root);
for (int depth = 0; depth < 10; depth++) {
File[] expandCopy = expand.toArray(new File[expand.size()]);
expand.clear();
for (File file : expandCopy) {
System.out.println(depth + " " + file);
if (file.isDirectory()) {
expand.addAll(Arrays.asList(file.listFiles()));
}
}
}
A: In Java 8, you can use stream, Files.walk and a maxDepth of 1
try (Stream<Path> walk = Files.walk(Paths.get(filePath), 1)) {
List<String> result = walk.filter(Files::isRegularFile)
.map(Path::toString).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
A: To avoid recursion when walking a tree there are basically two options:
*
*Use a "work list" (similar to the above) to track work to be done. As each item is examined new work items that are "discovered" as a result are added to the work list (can be FIFO, LIFO, or random order -- doesn't matter conceptually though it will often affect "locality of reference" for performance).
*Use a stack/"push down list" so essentially simulate the recursive scheme.
For #2 you have to write an algorithm that is something of a state machine, returning to the stack after every step to determine what to do next. The stack entries, for a tree walk, basically contain the current tree node and the index into the child list of the next child to examine.
A: Assuming you want to limit the amount of space used and:
*
*you can assume the list of files/directories is static over the course of your traversal, AND
*you can assume the list of files/directories in a give directory are always returned in the same order
*you have access to the parent of the current directory
Then you can traverse the directory using only the information of the last node visited. Specifically, something along the lines of
1. Keep track of the last Entry (directory or file) visited
2. Keep track of the current directory
3. Get a list of files in the current directory
4. Find the index of the last Entry visited in the list of files
5. If lastVisited is the last Entry in the current directory,
5.1.1 If current directory == start directory, we're done
5.1.2 Otherwise, lastVisited = the current directory and current directory is the parent directory
5.2. Otherwise, visit the element after lastVisited and set lastVisited to that element
6. Repeat from step 3
If I can, I'll try to write up some code to show what I mean tomorrow... but I just don't have the time right now.
NOTE: This isn't a GOOD way to traverse the directory structure... its just a possible way. Outside the normal box, and probably for good reason.
You'll have to forgive me for not giving sample code in Java, I don't have the time to work on that atm. Doing it in Tcl is faster for me and it shouldn't be too hard to understand. So, that being said:
proc getFiles {dir} {
set result {}
foreach entry [glob -tails -directory $dir * .*] {
if { $entry != "." && $entry != ".." } {
lappend result [file join $dir $entry]
}
}
return [lsort $result]
}
proc listdir {startDir} {
if {! ([file exists $startDir] && [file isdirectory $startDir])} {
error "File '$startDir' either doesn't exist or isnt a directory"
}
set result {}
set startDir [file normalize $startDir]
set currDir $startDir
set currFile {}
set fileList [getFiles $currDir]
for {set i 0} {$i < 1000} {incr i} { # use for to avoid infinate loop
set index [expr {1 + ({} == $currFile ? -1 : [lsearch $fileList $currFile])}]
if {$index < ([llength $fileList])} {
set currFile [lindex $fileList $index]
lappend result $currFile
if { [file isdirectory $currFile] } {
set currDir $currFile
set fileList [getFiles $currDir]
set currFile {}
}
} else {
# at last entry in the dir, move up one dir
if {$currDir == $startDir} {
# at the starting directory, we're done
return $result
}
set currFile $currDir
set currDir [file dirname $currDir]
set fileList [getFiles $currDir]
}
}
}
puts "Files:\n\t[join [listdir [lindex $argv 0]] \n\t]"
And, running it:
VirtualBox:~/Programming/temp$ ./dirlist.tcl /usr/share/gnome-media/icons/hicolor
Files:
/usr/share/gnome-media/icons/hicolor/16x16
/usr/share/gnome-media/icons/hicolor/16x16/status
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-high.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-low.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-medium.png
/usr/share/gnome-media/icons/hicolor/16x16/status/audio-input-microphone-muted.png
/usr/share/gnome-media/icons/hicolor/22x22
[snip]
/usr/share/gnome-media/icons/hicolor/48x48/devices/audio-subwoofer-testing.svg
/usr/share/gnome-media/icons/hicolor/48x48/devices/audio-subwoofer.svg
/usr/share/gnome-media/icons/hicolor/scalable
/usr/share/gnome-media/icons/hicolor/scalable/status
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-high.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-low.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-medium.svg
/usr/share/gnome-media/icons/hicolor/scalable/status/audio-input-microphone-muted.svg
A: If you're using Java 7, there is a very elegant method of walking file trees. You'll need to confirm whether it meets your needs recursion wise though.
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.*;
public class myFinder extends SimpleFileVisitor<Path> {
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) { }
public FileVisitResult postVisitDirectory(Path dir, IOException exc) { }
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { }
public FileVisitResult visitFileFailed(Path file, IOException exc) { }
<snip>
}
Essentially it does a depth first walk of the tree and calls certain methods when it enters/exits directories and when it "visits" a file.
I believe this to be specific to Java 7 though.
http://docs.oracle.com/javase/tutorial/essential/io/walk.html
A: And - of course - there's always the multi-threaded option to avoid recursion.
*
*Create a queue of files.
*If it's a file add it to the queue.
*If it's a folder start a new thread to list files in it that also feeds this queue.
*Get next item.
*Repeat from 2 as necessary.
Obviously this may not list the files in a predictable order. | unknown | |
d14558 | val | Are you sure about your css file address?
I suggest you to move your css file in the root of your project and change your address like this:
<link rel="stylesheet" type="text/css" href="style.css"/>
If it will be work then you should resolve your css address and move your file.
A: You may have to press CTRL + F5 to clear your browser cache, or failing that add a meaningless parameter to the css link to force the browser to take the latest file instead of a cached version eg add ?version=1.1
<link rel="stylesheet" type="text/css" href="./css/style.css?version=1.1"/> | unknown | |
d14559 | val | You should put the code related to Alt-only shortcut in a void cc::keyReleaseEvent(QKeyEvent * event) event. this event happens once a key is released.
So when you press Alt, nothing happens, if you release it, the "show menu bar" will happen, but if you keep pressing and press 3, then the other code will happen. | unknown | |
d14560 | val | You can use a wrapped class to store both values, as in the example below:
public class StackOverflow_15441384
{
const string XML = @"<StartLot>
<fileCreationDate level=""7"">201301132210</fileCreationDate>
<fmtVersion level=""7"">3.0</fmtVersion>
</StartLot>";
public class StartLot
{
[XmlElement("fileCreationDate")]
public LevelAndValue FileCreationDate { get; set; }
[XmlElement("fmtVersion")]
public LevelAndValue FmtVersion { get; set; }
}
public class LevelAndValue
{
[XmlAttribute("level")]
public string Level { get; set; }
[XmlText]
public string Value { get; set; }
}
public static void Test()
{
XmlSerializer xs = new XmlSerializer(typeof(StartLot));
StartLot sl = (StartLot)xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(XML)));
Console.WriteLine("FCD.L = {0}", sl.FileCreationDate.Level);
Console.WriteLine("FCD.V = {0}", sl.FileCreationDate.Value);
Console.WriteLine("FV.L = {0}", sl.FmtVersion.Level);
Console.WriteLine("FV.V = {0}", sl.FmtVersion.Value);
}
}
A: I always find Linq To Xml easier to use
var xDoc = XDocument.Parse(xml); /* XDocument.Load(filename); */
var items = xDoc.Root.Descendants()
.Select(e => new
{
Name = e.Name.LocalName,
Level = e.Attribute("level").Value,
Value = e.Value
})
.ToList(); | unknown | |
d14561 | val | Figured out the issue. [NSAttributedString alloc] initWithData was taking too long to execute, so blocked everything. | unknown | |
d14562 | val | Your test is creating a mock object and binding that mock object into the Laravel service container. However, your controller is not pulling a TheHelper instance from the Laravel service container; it is manually instantiating it with the new keyword. Using the new keyword is core PHP, and does not involve Laravel at all.
Your test is showing you an issue in your code. TheHelper is a dependency of your method, and should therefore be passed into the method instead of being created inside the method.
You either need to update your controller method to use dependency injection, so that Laravel can automatically resolve the TheHelper dependency from its container, or you need to replace your new keyword with a call into the Laravel container.
Using dependency injection:
public function A(Request $request, TheHelper $helper)
{
$result = $helper->getResult($request->email);
// rest of function...
}
Manually pull from the container:
public function A(Request $request)
{
$helper = app(TheHelper::class);
$result = $helper->getResult($request->email);
// rest of function...
} | unknown | |
d14563 | val | Couldn't you just have a resolver columns that resolves a list of these columns that will grow over time? It makes more sense to me. I don't believe that you can achieve this modeling that you want.
you would have a type Column which defines what a column is supposed to be, and have:
type Data {
email: [String]!
columns: [Column]!
}
Hope it helps you :) | unknown | |
d14564 | val | The brute force approach would be as follows, this will give you a good idea on how to proceed.
.envelop img {
margin-top: 50px;
margin-left: -60px;
width: 113%;
}
.envelop {
padding: 0;
margin: 0;
}
By doing this you're giving the envelop a bigger width so it matches the div above it. Then move it to the left with negative margin-left.
I have a 1920px width screen and it shows perfectly in sync for me, but it's not responsive with this approach. You'd need to use many media queries to adjust the size as it goes.
You can try playing around with negative % for the margin-left or even better the "vw" values. Position: relative and a negative value for left will give you the same result as margin-left.
Image of my approach's result. | unknown | |
d14565 | val | IOException definition from javadoc
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
While I don't have access to your full stacktrace, the statement Dell/127.16.3.24 let me believe that this is the IP address that was given when creating the socket.
I think you might want to try using InetAddress.getLocalHost().getHostAddress which will return only the IP while InetAddress.getLocalHost() will also return the hostname of the system.
InetAddress.getLocalHost from javadoc
Returns the address of the local host. This is achieved by retrieving
the name of the host from the system, then resolving that name into an
InetAddress.
Note that if you already know that you want local host ip, you can simply pass "127.0.0.1" when creating the socket and it should also fix the problem.
You should also consider adding the flush statement in a finally block to make sure the stream is flushed even if exception occurs. And for sure add a close statement in that block too. | unknown | |
d14566 | val | Add #import "mainRootVC.h" in you CustomClass.m file
And create object of mainRootVC such like,
mainRootVC *obj = [[mainRootVC alloc] init];
// Now you can access your label by
obj.gameStateLabel...
A: Do like this...
YourViewController *rootController =[(YourViewController*)[(YourAppDelegate*)
[[UIApplication sharedApplication]delegate] window] rootViewController];
A: Try the following too:
ViewController *controller = (ViewController*)self.window.rootViewController;
It will return the initial view controller of the main storyboard.
A: For sending information from a viewController to other viewController you have:
*
*Delegates:Definiton and examples
*NSNotificationCenter: Apple Documentation
NSString *label = @"label text";
[[NSNotificationCenter defaultCenter] postNotificationName:NAVIGATETO object:label userInfo:nil];
You can found tons of examples about those two. I recommend you use one of those.
Hope this helps a bit.
A: OK. I found two issues.
*
*I had copied the code over from my Mac project and modified it. Something seems to have gone wrong.
I retyped the entire function and it solved most of the problem
*
*uvc should be of the type ViewController* - not UIViewController* as I was doing
Thanks everyone for your replies - much appreciated. | unknown | |
d14567 | val | To the best of my knowledge anything that's inside of a url should always be urlencoded.
The only gotcha is that you need to make sure to reverse the encoding when you read in the arguments. It's very possible that django already does this for you. I'd need to consult the documentation and/or code to confirm though. | unknown | |
d14568 | val | If your query is modified to this, it works:
SELECT
[key] = kvp.[key],
[value] = ISNULL(
JSON_QUERY(CASE WHEN ISJSON(kvp.[value]) = 1 THEN kvp.[value] END),
'"' + STRING_ESCAPE(kvp.[value], 'json') + '"'
)
FROM (VALUES
('key1', 'This value is a "string"')
,('key2', '{"description":"This value is an object"}')
,('key3', '["This","value","is","an","array","of","strings"]')
,('key4', NULL)
-- These now work
,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH, INCLUDE_NULL_VALUES
Of course, this wouldn't be sufficient if value was an int. Also, I can't really explain why yours doesn't work. | unknown | |
d14569 | val | If you go to the redux-form documentation, you will find what you need under the action creator section. With that, let's answer your questions.
one can use 'Undo Changes' to reset form to InitialValues
In its documentation, Redux-Form lists out a couple of actions that you can use. You can either use an action creator or used an action that is already bound to the dispatch. For your requirement, you'll need to use the library's reset function
a) using action creator
import { reset } from 'redux-form';
...// then inside a function you can dispatch the reset action.
resetMyForm() {
const action = reset('myFormName');
dispatch(action);
}
b) using an action already bound to the dispatch
I wont type this since there is an example in the library on GitHub here
And as for
button to reset to empty form
similar to the initial answer but you would have to use the clearFields function instead.
Hope this helps. | unknown | |
d14570 | val | In JavaScript, you can simple do variablename.toFixed(2); for that.
Example:
var num1 = 12312.12312
console.log(num1.toFixed(2)); // Will give 12312.12 | unknown | |
d14571 | val | Below is how I understand your question, and this is how I would go about it:
# models.py
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntergerField()
class Info(models.Model):
the_person = models.ForeignKey(Person)
info = models.CharField(max_length=200)
# views.py
# I'm using Class Based Views from Generic Views
class PersonDetail(ListView):
# automatically uses pk of
# model specified below as slug
model = Person
So now in your template, you can have something like this:
# html. Just a rough html below. I hope it gives you the idea. Might not tabulate the data properly, but the point is is to have both model data in templates, then simply use {% for %} loop to list one data in one column or more columns of the table and then whatever model(s) in the other columns.
<table style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Info</td>
</tr>
{% for object in object_list %}
<tr>
<td>{{ object.name }}</td>
<td>{{ object.age }}</td>
{% for i in object.the_person.set_all %}
<td>{{ i.info }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
If you're looking to retrieve two models 'Non-ForeignKey-ed' to each other, you can use context object. See here | unknown | |
d14572 | val | Thanks for the suggestions from @mjwills and whoever deleted their answer, I was able to figure out a good method.
I'm now using a ConcurrentDictionary<long, ExampleClass> which means I can both index and add without risking the issue of having duplicated ID's - exactly what I needed. | unknown | |
d14573 | val | It could be achieved with type constraints as follows.
public interface IHelper<TKey,TValue,TMsgLst> where TMsgLst : TMessageListener<TValue> | unknown | |
d14574 | val | Simply assign it NULL or a default constructed boost::function (which are empty by default):
#include <boost/function.hpp>
#include <iostream>
int foo(int) { return 42; }
int main()
{
boost::function<int(int)> f = foo;
std::cout << f.empty();
f = NULL;
std::cout << f.empty();
f = boost::function<int(int)>();
std::cout << f.empty();
}
Output: 011
A: f.clear() will do the trick. Using the example above
#include <boost/function.hpp>
#include <iostream>
int foo(int) { return 42; }
int main()
{
boost::function<int(int)> f = foo;
std::cout << f.empty();
f.clear();
std::cout << f.empty();
f = boost::function<int(int)>();
std::cout << f.empty();
}
will yield the same result. | unknown | |
d14575 | val | That may be happening because you are trying to call the clone() method outside its allowed access. For you to be able to call it, the class that is calling it should extend directly from Object, or belong to the Same Package, or be Object. More information here http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
A: If you want some code inside class A to clone an instance of class B, then either place A and B in the same package, or broaden the access to B.clone() by making it public (rather than leaving it protected-scope.)
Furthermore, I would refer you to the book Effective Java by Josh Bloch. I found a PDF of Chapter three here
A: You can only access protected members of a type in a different package if the compile-time type of the expression you're referencing it through is either your own class or a subclass.
Check this link. | unknown | |
d14576 | val | Font files have various names and other annotations. In FontForge, you can find these listed in menu Element > Font info. Here as I found cairo is able to identify the font by its TTF names > Family or which is the same its WindowsString. In case of Adobe's Helvetica Neue light this string has the value 'HelveticaNeueLT Std Lt'. Then selecting the font by this name, and setting the slant and weight to normal, the light weight will be used:
context.select_font_face('HelveticaNeueLT Std Lt', \
cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
It is possible to find font names by many softwares. On Linux fontconfig is able to list fonts, and the name in the second column what cairo recognizes:
$ fc-list | grep HelveticaNeue
...
/usr/share/fonts/.../HelveticaNeueLTStd-Lt.otf: Helvetica Neue LT Std,HelveticaNeueLT Std Lt:style=45 Light,Regular
...
$ fc-list | sed 's/.*:\(.*,\|\s\)\(.*\):.*/\2/'
...
HelveticaNeueLT Std Lt
... | unknown | |
d14577 | val | There's definitely a compromise between accessing and manually updating the cell view content, and calling reloadData on the whole collection view that you could try.
You can use the func reloadItems(at: [IndexPath]) to ask the UICollectionView to reload a single cell if it's on screen.
Presumably, imageNotInCache means you're storing image in an in-memory cache, so as long as image is also accessible by the func collectionView(UICollectionView, cellForItemAt: IndexPath), the following should "just work":
if (imageNotInCache) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
if let thumb = imageFromPathAndCacheIt(path) {
DispatchQueue.main.async {
self.collectionView.reloadItems(at: [indexPath])
}
}
}
} | unknown | |
d14578 | val | Here is some that solves the does a word exist. I wasn't sure how you were storing the array of characters so I guessed it was a 2d array of chars. The method wordExists is the one used to check if the word exists. I used a test to check that it worked and it did on multiple inputs. Edit: I just realized that this could cause the words to cycle back onto itself if its a palindrome, ill post the fixed code as soon as I make it
public static boolean wordExists(char[] [] characters, String word)
{
char[] word_as_char = word.toCharArray();
for (int i = 0; i < characters.length; i++)
{
for (int j = 0; j < characters[0].length; j++)
{
boolean wordExists = checkWord(characters, word_as_char, 0, i, j);
if (wordExists)
{
return true;
}
}
}
return false;
}
public static boolean checkWord(char[] [] characters, char[] word, int index, int x, int y)
{
boolean wordExists = false;
if (index < word.length) {
if (characters[x] [y] == word[index])
{
if (x + 1 < characters.length)
{
wordExists = wordExists | checkWord(characters, word, index + 1, x + 1, y);
}
if (x - 1 > 0)
{
wordExists = wordExists | checkWord(characters, word, index + 1, x - 1, y);
}
if (y + 1 < characters[0].length)
{
wordExists = wordExists | checkWord(characters, word, index + 1, x, y + 1);
}
if (y - 1 > 0)
{
wordExists = wordExists | checkWord(characters, word, index + 1, x, y - 1);
}
}
}
if (index == word.length - 1 && characters[x] [y] == word[index])
{
wordExists = true;
}
return wordExists;
}
}
A: CheckLetter != (" ") doesn't check content equality, it checks reference equality - are these 2 variables referring to the same object. Use !" ".equals(CheckLetter). Better yet, don't use String for holding single characters, there is char for this and there is Character class that has some methods for handling them (like toUpperCase). | unknown | |
d14579 | val | No, don't inject shell variables into your jq filter! Rather use options provided by jq to introduce them as variables inside jq. In your case, when using a variable that holds a number, --argjson will do:
i=1
test2=$(/bin/lshw -quiet -json -C network|/bin/jq --argjson i $i '.[$i] | .logicalname') | unknown | |
d14580 | val | Never mind, I figured it out. I was searching for something within the chart options, but it turns out the DateRangeFilter control has a "state" parameter. Here it is implemented in my example
var rangeFliter = new google.visualization.ControlWrapper({
'controlType': 'DateRangeFilter',
'containerId': 'filter_div',
'options': {
'filterColumnLabel': 'Closed Date'
},
//this will set the default range based on the values you provide
'state': {'lowValue': new Date(2016, 0, 11), 'highValue': new Date(2016, 1, 1)}
}); | unknown | |
d14581 | val | I would suggest making DialogueManager Component that will hold all of your dialogues and each of these should hold reference to other dialogues. Then after displaying dialogue you can check if it has multiple children or just one ( or none ) and display some dialog/popup to choose from keys of these.
In code example it would be like :
[Serializable]
public class Dialogue
{
[SerializeField]
Dictionary<string, Dialogue> _dialogues;
[SerializeField]
string _dialogueText;
public Dialogue(string text)
{
_dialogues = new Dictionary<string, Dialogue>();
_dialogueText = text;
}
public string GetText() { return _dialogueText; }
public bool HasManyPaths() { return _dialogues.Count > 1; }
public string[] GetKeys() { return _dialogues.Keys; }
public Dialogue GetDialogue(string key) { return _dialogues[key]; }
}
Now you should fill this within your Unity inspector and make DialogueManager Component to manage your Dialogues :
public class DialogueManager
: Component
{
[SerializeField]
Dialogue _currentDialogue;
public void InitializeDialogue()
{
string text = _currentDialogue.GetText();
// display the text
if ( _currentDialogue.HasManyPaths() )
{
string[] keys = _currentDialogue.GetKeys();
// display keys;
string selected_key = // user input here
_currentDialogue = _currentDialogue.GetDialogue(selected_key);
}
else
{
string key = _currentDialogue.GetKeys()[0];
_currentDialogue = _currentDialogue.GetDialogue(key);
}
}
}
Using this method you can simply make your dialogues inside Unity editor and add MonoBehaviour script with something like this :
public void Start()
{
GetComponent<DialogueManager>().InitializeDialogue();
}
Simple example of making dialogue tree would be :
{ currentDialogue [ "hello! choose 1 or 2" ]
1.{ dialogue [ "you've chosen 1" ]
. { dialogue [ "this ends dialogue" ] }
}
2. { dialogue [ "you've chosen 2" ]
. { dialogue [ "now choose another number between 3 and 4" ]
3. { dialogue [ "you've chosen 3" ] }
4. { dialogue [ "you've chosen 4" ] }
}
}
} | unknown | |
d14582 | val | .myClass/DomElement > .myotherclassinsidethatelement selects only the direct children of the parent class.
So:
<div class='myClass'>
<div class='someOther'>
<div class='myotherclassinsidethatelement'></div>
</div>
</div>
In this case, the > version won't select it.
See here: http://jsfiddle.net/RRv7u/1/
A: UPDATE
The previous answer I gave was incorrect. I was under the impression that inheritance and nesting were the same thing, but they are not. If anyone else had this impression, here is a resource explaining what nesting is:
http://www.htmldog.com/guides/css/intermediate/grouping/
Here is another explaining what specificity is:
http://www.htmldog.com/guides/css/intermediate/specificity/
And here is a final link explaining specificity and inheritance:
http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/
Previous answer:
The angle bracket in CSS denotes inheritance. So when you say
.class1 > .class2 { styles }
You're saying that the styles you're about to apply for class2 are
only going to be applied when class2 is a child of class1. | unknown | |
d14583 | val | Do not extend ResultSet. Create your entity class, let say Person. And implement 'get some date' method. Like so
class Person {
public Person(ResultSet resultSet) {
this.resultSet = resultSet;
}
...
public Date getBirthday() {
resultSet.getDate("BIRTHDAY_COLUMN");
}
...
}
You should be aware that this Person class is more like wrapper then pure entity. And using it is OK only in a scope where you have established connection and valid ResultSet object.
while (resultSet.next()) {
Person person = new Person(resultSet);
someAction(person);
someMoreActions(person);
}
To make Person more entity-like you could consider using JPA
A: First, you don't extend interfaces, but you do implement interfaces :)
That said, you are likely looking in the wrong direction for the solution. Forget about implementing your ResultSet and just create a DAO class which does all the the ResultSet <--> Entity mapping tasks and do the desired date conversion just there. The DAO method may look like
public Person find(Long id) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Person person = null;
try {
connection = database.getConnection();
preparedStatement = connection.prepareStatement(SQL_FIND);
preparedStatement.setLong(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
person = new Person();
person.setId(resultSet.getLong("id"));
person.setName(resultSet.getString("name"));
person.setBirthDate(resultSet.getDate("birth_date"));
// ...
}
} finally {
close(connection, preparedStatement, resultSet);
}
return person;
}
You see, if the database column type is DATE, DATETIME or TIMESTAMP, then you can just use ResultSet#getDate() to obtain it as a java.util.Date object. To display the date in the desired format in the presentation layer, use the therefore supplied tools like SimpleDateFormat for "plain Java", fmt:formatDate for JSP pages, f:convertDateTime for JSF, etcetera.
Tight-coupling the ResultSet inside the model (entity, the "Person" in this example) is a bad idea. The model doesn't need to know anything about how it is been created and doing it may only potentially leak DB resources (because that approach may require the ResultSet to be open all the time) and may cause your app to crash sooner or later because the DB has run out of resources. Don't do that.
To get more ideas and insights about the DAO you may find this article useful.
A:
I would like to create myRecordSet
object that extends java.sql.ResultSet
Easy enough. A decent IDE will do it for you.
and to implement a method that returns
UTC date from SQL statement.
Impossible, because you can't get your database to create an instance of your class instead of its own.
So you don't want to do that. What you really want to do is write a wrapper for ResultSet that talks to whatever you get from the database and adds whatever functionality you need. This is called the Delegate pattern. | unknown | |
d14584 | val | If you want to use Decimal Number only on your EditText
use the xml attribute android:inputType="numberDecimal" in your EditText widget your EditText declaration will be like this:
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
If you want to use Signed Decimal Number than combine the two Xml attributes android:inputType="numberDecimal" and android:inputType="numberSigned". Your EditText declaration will be like this:
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal|numberSigned" >
</EditText>
A: Change android:inputType from "number" to "numberDecimal". See the documentation for even more options for inputType.
A: inputType="number" doesnt allow floats. try changing:
android:inputType="number"
to:
android:numeric="integer|decimal"
A: You need to change the input type of your EditText in the XML code.
Change the inputType attribute of the EditText from
android:inputType="number"
to
android:inputType="numberDecimal"
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:inputType="numberDecimal"
android:id="@+id/txtOpd1"/> | unknown | |
d14585 | val | A preliminary answer before someone who can do more than read through the help commands comes along:
Although:
php artisan clear
...isn't listed in artisan's documentation at all (or at least not in php artisan list), based on its output it seems to be an alias of:
php artisan clear-compiled
This seems to be confirmed by php artisan help clear-compiled:
Description:
Remove the compiled class file
Usage:
clear-compiled
Although that help command doesn't really clear up much, like what exactly compiled class files are or what relation they have to any of the other clear commands, I'm guessing the command does something similar to:
php artisan view:clear
...which does the following according to its own help command:
Description:
Clear all compiled view files
Usage:
view:clear
Based on the above, I can only guess that running php artisan clear is about as harmless as running php artisan view:clear, in that both are designed to clear away compiled files that, when cleared, are simply recompiled again on the next build.
How exactly php artisan clear differs from php artisan view:clear and why it needs its own separate command and a much more memorable alias than any of the other clear commands is still... unclear.
BONUS
To anyone else that arrived here because they find themselves constantly running some variation of the above commands for debugging and troubleshooting, I just learnt about the php artisan optimize:clear command, which runs all of these commands at once:
php artisan view:clear
php artisan cache:clear
php artisan route:clear
php artisan config:clear
php artisan clear
and returns the following output:
Compiled views cleared!
Application cache cleared!
Route cache cleared!
Configuration cache cleared!
Compiled services and packages files removed!
Caches cleared successfully! | unknown | |
d14586 | val | You could map your data to include relevance points:
const index = await res.json();
const searchTextLowercased = searchText.toLowerCase();
const rankedIndex = index.map(entry => {
let points = 0;
if (entry.name.toLowerCase().includes(searchTextLowercased)) {
points += 2;
}
if (entry.text.toLowerCase().includes(searchTextLowercased)) {
points += 1;
}
return {...entry, points};
}).sort((a, b) => b.points - a.points);
This way, you have ranked results in rankedIndex const.
Keep in mind that your code probably needs some refactoring, because you're fetching data on each search. I'm assuming your searchIndex() is called with every key press or something like that. | unknown | |
d14587 | val | I sorted this out by implementing the referral exclusion in javascript, right before the gtm tag:
var previousReferrer = Cookies.get("previous_referrer")
if(document.referrer.match(/paypal\.com/))
Object.defineProperty(document,
"referrer",
{get : function(){
return previousReferrer; }});
Cookies.set("previous_referrer", document.URL);
please notice that as it is hard to change the document.referrer variable we need to use defineProperty and that this only works in modern browsers (safari <=5, Firefox < 4, Chrome < 5 and Internet Explorer < 9 ):
How to manually set REFERER header in Javascript? | unknown | |
d14588 | val | It is not a fix but explains the cause of bug...
In the below snippet, you are trying to access board[i] with index i > 9 but your board is of size 9. For instance, check for j=9.
for j in range(0, 9, 3):
if [t] * 3 == [board[i] for i in range(j, j+3)]:
return t | unknown | |
d14589 | val | Using call_user_func_array and array_merge
<?php
$array = [
[
"[wd[wd5][amount]]" => 1.00,
"[wd[wd5][address]]" => "1BitcoinAddress",
"[wd[wd5][currency]]" => "BTC"
],
[
"[wd[wd7][amount]]" => 1.00,
"[wd[wd7][address]]" => "1BitcoinAddress",
"[wd[wd7][currency]]" => "BTC"
]
];
$result = call_user_func_array('array_merge', $array);
echo "<pre>";
print_r($result);
A: Loop the array using foreach and create an new array.
$new_array = array();
foreach($array as $value){
foreach($value as $k=>$v){
$new_array[$k] = $v;
}
}
print_r($new_array);
Output:
Array
(
[wd[wd5][amount]] => 1.00
[wd[wd5][address]] => 1BitcoinAddress
[wd[wd5][currency]] => BTC
[wd[wd7][amount]] => 1.00
[wd[wd7][address]] => 1BitcoinAddress
[wd[wd7][currency]] => BTC
)
A: you can do this like:
$result = array();
foreach($array as $item) {
$result = array_merge($result, $item);
}
here $result is a new blank array, and $array is the array to merge.
A: You can do it using RecursiveIteratorIterator and RecursiveArrayIterator.
Though I'm liking @BilalAkbar's answer abit more now for the simplicity.
<?php
$array = [
[
'wd[wd5][amount]' => 1.00,
'wd[wd5][address]' => '1BitcoinAddress',
'wd[wd5][currency]' => 'BTC',
],
[
'wd[wd7][amount]' => 1.00,
'wd[wd7][address]' => '1BitcoinAddress',
'wd[wd7][currency]' => 'BTC'
],
];
$result = [];
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
) as $key => $value) {
$result[$key] = $value;
}
print_r($result);
/*
Array
(
[wd[wd5][amount]] => 1
[wd[wd5][address]] => 1BitcoinAddress
[wd[wd5][currency]] => BTC
[wd[wd7][amount]] => 1
[wd[wd7][address]] => 1BitcoinAddress
[wd[wd7][currency]] => BTC
)
*/
https://3v4l.org/0fCKj
A: Use array_merge to merge combine the arrays.
http://php.net/manual/en/function.array-merge.php
<?php
$arrayWithSubarrays = array(
array(
"[wd[wd5][amount]]" => 1.00,
"[wd[wd5][address]]" => "1BitcoinAddress",
"[wd[wd5][currency]]" => "BTC"
),
array(
"[wd[wd7][amount]]" => 1.00,
"[wd[wd7][address]]" => "1BitcoinAddress",
"[wd[wd7][currency]]" => "BTC"
)
);
// merge each array explicitly:
$mergedArray1 = array_merge($arrayWithSubarrays[0],$arrayWithSubarrays[1]);
// or merge as many as you have in the array:
$mergedArray2 = array();
foreach($arrayWithSubarrays as $array) {
$mergedArray2 = array_merge($mergedArray2, $array);
}
// (mergedArray1 contains the same data as mergedArray2)
A: Here answer, but you have 2 solution one different key then below answer.
otherwise only save array last values beacause every time 3 keys same.
hope you understand.
<?php
$a = array
(
array
(
'wd[wd[amount]]' => '1.00',
'[wd[wd5][address]]' => '1BitcoinAddress',
'[wd[wd5][currency]]' => 'BTC'
),
array
(
'wd[wd[amount1]]' => '1.00',
'[wd[wd5][address1]]' => '1BitcoinAddress',
'[wd[wd5][currency1]]' => 'BTC'
)
);
$total = count($a);
$p = array();
$q = array();
$pq = array();
for($i=0;$i<$total;$i++){
$tarray = $a[$i];
foreach($tarray as $k=>$v){
array_push($p,$k);
array_push($q,$v);
}
}
$pq = array_combine($p,$q);
print_r($pq);
?> | unknown | |
d14590 | val | </b>" . $cgpa . "<br><br>" . "<b>Reg No: </b>" . $regno . "<br><br>" . "<b>Position: </b>" . $position . "<br><br>" . "<b>Why You Want To Be Part Of Society?: </b><br><br>" . $why;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From:" . $from;
mail($to,$subject,$message,$headers);
// Close connection
mysqli_close($conn);
}
?> | unknown | |
d14591 | val | jQuery.each could do this for you if I'm understanding your question correctly:-
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
You can find more info here: http://api.jquery.com/jQuery.each/
a clearer example:
var idYouAreLookingFor=2;
$.each(bubble, function(index, value) {
if(value.id==idYouAreLookingFor)
{
value.name='test';
//profit.
}
});
A: Here is my suggestion:
Use JSON as storage format. Now, I don't know which value is which, but here is an example for JSON encoded data:
[{"posx": 143,"posy": 753,"priority": 3, "color": "rgba(65,146,160,0.7)"}, ...]
You can then use JSON.parse [MDN] to create a JavaScript object from this data, which will look like this:
// var obj = JSON.parse(json); is the same as:
var obj = [
{
posx: 143,
posy: 753,
priority: 3,
color: "rgba(65,146,160,0.7)"
},
...
];
It also seems that the IDs of your "bubbles" are continuous, 1-based. If you make them zero-based, you don't have to store them explicitly. The ID would be the index in the array.
Then you can change the values like so:
obj[id].posx = newvalue;
obj[id].posy = another_newvalue;
and afterwards serialize the the whole array with JSON.stringify [MDN]:
var json = JSON.stringify(obj);
and store it in the cookie.
JSON is available for older browser with json2.js. | unknown | |
d14592 | val | First off, you should not store the audio files in the same directory as your php files because its easy to protect from someone loading your PHP files by using the basename() function to isolate the filename else you must make further checks its not a php or system file path thats been passed to the $_GET['fname'] parameter, you should also put a .htaccess in the media folder with deny from all in it, this will stop direct access and if you want to be able to stream with seek-able functionality then you need to handle the HTTP_RANGE headers.
<?php
if(!empty($_GET['fname'])){
$file_name = './wav_files/'.basename($_GET['fname']);
stream($file_name, 'audio/wav');
}
/**
* Streamable file handler
*
* @param String $file_location
* @param Header|String $content_type
* @return content
*/
function stream($file, $content_type = 'application/octet-stream') {
// Make sure the files exists
if (!file_exists($file)) {
header("HTTP/1.1 404 Not Found");
exit;
}
// Get file size
$filesize = sprintf("%u", filesize($file));
// Handle 'Range' header
if(isset($_SERVER['HTTP_RANGE'])){
$range = $_SERVER['HTTP_RANGE'];
}elseif($apache = apache_request_headers()){
$headers = array();
foreach ($apache as $header => $val){
$headers[strtolower($header)] = $val;
}
if(isset($headers['range'])){
$range = $headers['range'];
}
else $range = FALSE;
} else $range = FALSE;
//Is range
if($range){
$partial = true;
list($param, $range) = explode('=',$range);
// Bad request - range unit is not 'bytes'
if(strtolower(trim($param)) != 'bytes'){
header("HTTP/1.1 400 Invalid Request");
exit;
}
// Get range values
$range = explode(',',$range);
$range = explode('-',$range[0]);
// Deal with range values
if ($range[0] === ''){
$end = $filesize - 1;
$start = $end - intval($range[0]);
} else if ($range[1] === '') {
$start = intval($range[0]);
$end = $filesize - 1;
}else{
// Both numbers present, return specific range
$start = intval($range[0]);
$end = intval($range[1]);
if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) $partial = false;
}
$length = $end - $start + 1;
}
// No range requested
else {
$partial = false;
$length = $filesize;
}
// Send standard headers
header("Content-Type: $content_type");
header("Content-Length: $length");
header('Accept-Ranges: bytes');
// send extra headers for range handling...
if ($partial) {
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $start-$end/$filesize");
if (!$fp = fopen($file, 'rb')) { // Error out if we can't read the file
header("HTTP/1.1 500 Internal Server Error");
exit;
}
if ($start) fseek($fp,$start);
while($length){
set_time_limit(0);
$read = ($length > 8192) ? 8192 : $length;
$length -= $read;
print(fread($fp,$read));
}
fclose($fp);
}
//just send the whole file
else readfile($file);
exit;
}
?> | unknown | |
d14593 | val | " Referenced from: /Users/owner12/Library/Application Support/iPhone Simulator/5.1/" - isn't AdSupport available only in iOS 6.0 and later? | unknown | |
d14594 | val | I am assuming that the problem is the refNode is not the correct type. One possible solution is to check the type of refNode, and if it is not of type TEXT_NODE, create a text node and add it to refData. The code would look something like:
public native void insertText(String text, int pos) /*-{
var elem = [email protected]::getElement()();
var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
if(refNode.nodeType == 3){
var newTxtNode = document.createTextNode(text);
refNode.appendChild(newTxtNode);
} else {
refNode.insertData(pos, text);
}
}-*/;
The nodeType can be found here.
A: So I have this working I think. I changed Matthew's answer a bit and it seems to work in all my tests. When refNode equals Element type, I guess the pos value was always the index of the child node element where I needed to insert before.
public native void insertText(String text, int pos) /*-{
var elem = [email protected]::getElement()();
var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
if (refNode.nodeType == 1) {
var newTextNode = document.createTextNode(text);
refNode.insertBefore(newTextNode, refNode.childNodes[pos]);
} else {
refNode.insertData(pos, text);
}
}-*/; | unknown | |
d14595 | val | I can see only one option to do less configurations. You can use benefit of flattering by renaming properties of UserForAuthorisation class to:
public class UserForAuthorisation
{
public string UserLoginName { get; set; }
public int UserGroup { get; set; }
}
In this case properties of nested User object will be mapped without any additional configuration:
Mapper.CreateMap<Session, UserForAuthorisation>(); | unknown | |
d14596 | val | Edit:
I published an NPM library called parse-node-with-cloud that provides a Parse.Cloud object in node.js. I hope this will enable node.js unit tests of Parse cloud code.
===========
My solution to this is to use the parse-cloud-express library on NPM. Import it with
const Parse = require('parse-cloud-express').Parse;
Then Parse.Cloud functions will work as expected.
Unfortunately, the source code is no longer available on github and the module is likely no longer maintained. | unknown | |
d14597 | val | It should not skip the deleted ID when new record gets entered
Yes it should. You're just relying on the system to do something that it was never designed to do and never claimed to do.
AUTOINCREMENT is not designed to generate your "Bill No". It's designed to generate an ever-incrementing identifier and guarantee uniqueness by never re-using a value. And it's doing exactly that.
You can manually generate your "Bill No" using whatever logic you like and store it in another column. It would be strange to re-use values though. Imagine if you issue a bill to someone, later delete the record, and then issue another bill to someone else with the same number.
Uniqueness is important with identifiers.
A: From a financial control point of view being able to delete and reuse invoice numbers damages your audit trail and leaves you open to risk. Also from a database integrity point of view, reusing primary keys is not allowed as it would lead to unexpected results,such as records in other tables appearing wrongly in a join. There are consequences to naturalising your primary keys (excellent discussion of natural and surrogate primary keys). The database is protecting its referential integrity by not allowing the reuse of the primary key. Indeed, as @David says in his response, part of the function of autoincrement on a primary key is to maintain the uniqueness of the key.
Now to solutions, from a financial aspect invoices should never be deleted so there is an audit trail, an incorrect invoice should have a contra through a credit note. On the database side if you must 'delete' a record and reuse the invoice number, I would suggest having a different field for the invoice number, not actually deleting, but using a field to flag active or deleted, and maintaining a separate incrementing invoice number. Although not advised, this will at least help maintain the integrity of your records. | unknown | |
d14598 | val | Please refer this tutorial to send an email with attachment: https://www.google.com/amp/s/javatutorial.net/send-email-with-attachments-android/amp
You also don't need the "text/csv" mimetype, this is for the email and wrong as you need plain text or html, as you prefer.
In addition to that, do you have the file read permission? | unknown | |
d14599 | val | Eventually found the answer, for anyone else who is facing similar newbie issues:
/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_graph"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/nav_view"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java under onCreate
BottomNavigationView navView = findViewById(R.id.nav_view);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(navView,navController);
Under /res/navigation/nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/mapFragment">
<fragment
android:id="@+id/mapFragment"
android:name="com.company.pinpoint.MapFragment"
android:label="fragment_map"
tools:layout="@layout/fragment_map">
<action
android:id="@+id/action_mapFragment_to_newsFeedFragment"
app:destination="@id/newsFeedFragment" />
<!--app:enterAnim="@anim/slide_in_right"-->
<!--app:exitAnim="@anim/slide_out_left"-->
<!--app:popEnterAnim="@anim/slide_in_left"-->
<!--app:popExitAnim="@anim/slide_out_right" />-->
</fragment>
<fragment
android:id="@+id/newsFeedFragment"
android:name="com.company.pinpoint.NewsFeedFragment"
android:label="fragment_news_feed"
tools:layout="@layout/fragment_news_feed" />
</navigation> | unknown | |
d14600 | val | So your code attempts to launch "bcdedit.exe". From the command line, the only location of bcdedit.exe in your PATH environment is the Windows System directory, c:\Windows\System32.
When you compile your code as 32-bit and run it on a 64-bit system, your process's view of the file system will change. Namely, the process view of the C:\Windows\System32 is replaced by the contents of C:\Windows\SysWOW64 - where only 32-bit DLLs and EXEs are located. However.... There is no 32-bit version bcdedit.exe located in this folder. (If you want to simulate this, go run c:\windows\syswow64\cmd.exe - you won't be able to find bcdedit.exe in the c:\windows\system32 folder anymore).
You probably need something like this: How to retrieve correct path of either system32 or SysWOW64?
Format your ShellExecute function to directly specificy the SysWow64 path for both bcdedit.exe and cmd.exe. Or as others have suggested, just compile for 64-bit. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.