_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d7401 | train | You may do
bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
for (std::size_t i = 0, size = it.size(); i != size; ++i) {
const std::size_t index = size - 1 - i;
++it[index];
if (it[index] >= v[index].size()) {
it[index] = 0;
} else {
return true;
}
}
return false;
}
void do_job(const std::vector<std::vector<int>>& v,
const std::vector<std::size_t>& it)
{
for (std::size_t i = 0; i != it.size(); ++i) {
// TODO: manage case where v[i] is empty if relevant.
std::cout << v[i][it[i]] << " ";
}
std::cout << std::endl;
}
void iterate(const std::vector<std::vector<int>>& v)
{
std::vector<std::size_t> it(v.size(), 0u);
do {
do_job(v, it);
} while (increase(v, it));
}
Live Demo | unknown | |
d7402 | train | Here are a few methods on how to center an HTML element:
*
*The oldest trick in the book:
.form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
This works by moving the form element 50% to the left and 50% to the top of the container and move's it back 50% of its width and height.
*flex
.form-container {
display: flex;
align-items: center;
justify-content: center;
}
Set the container of the form to flex and align it to the center vertically and horizontally.
*grid
.form-container {
display: grid;
place-items: center;
}
Same thing as flex, but both justify-content and align-items are merged into the same line.
You can give the same CSS to your form using tailwindcss:
1.
<form class="absolute top-1/2 left-1/2 translate-x-1/2 translate-y-1/2">
*
<div class="bg-gray-600 flex items-center justify-center">
*
<div class="bg-gray-600 grid place-items-center">
Hope this helps!
A: Apply this css on the parent of your form, in this case, probably the bg-gray-600
.bg-gray-600 {
display:flex;
justify-content:center; /*horizontal center*/
align-items:center; /*vertical center*/
}
You might need to define width or height of the parent in order this to work. Depends on your CSS.
The * that you said you dont understand is used to select every element within the whole page, so the bg-gray-600 as well. In this case, none of its values effect the centering of your form. | unknown | |
d7403 | train | Let's build this gradually, and start with a simple substitution that prepends a newline (\r) to any sequence of comment prefixes (!):
:%substitute/!\+.*$/\r&/
This leaves behind trailing whitespace. We can match that as well, and use a capture group (\(...\)) for the actual comment. This removes the whitespace:
:%substitute/\s*\(!\+.*$\)/\r\1/
But it still matches comments at the start of a line, and introduces an additional empty line in front. We can add a lookbehind assertion that the line must not start with a !, but this now gets ugly:
:%substitute/^\%(^[^!].*\)\@=.*\zs\s*\(!\+.*$\)/\r\1/
Instead, it's easier to use another Vim command, :global (or its inverted sister :vglobal), to only match lines not starting with !, and then apply the :substitute there:
:%vglobal/^!/substitute/\s*\(!\+.*$\)/\r\1/
The final requirement is that exclamation marks within strings should be kept. This would add another regular expression, and integrating it into the overall match would be really hard, and could probably be only done approximately. Fortunately, with syntax highlighting, Vim already knows what is a Fortran string!
My PatternsOnText plugin has (among others) a :SubstituteIf / :SubstituteUnless combo that can do substitutions only if a condition is true / false. The library it depends on provides a wrapper around synIdAttr() that makes it easy to define a predicate for Fortran strings:
function! IsFortranString()
return ingo#syntaxitem#IsOnSyntax(getpos('.'), '^fortranString')
endfunction
We then only need to replace :substitute with :SubstituteUnless + predicate:
:%vglobal/^!/SubstituteUnless/\s*\(!\+.*$\)/\r\1/ IsFortranString()
The same can also be achieved without the plugin (using :help sub-replace-special and synstack() / synIdAttr()), but it'd be more complex. | unknown | |
d7404 | train | to remove lines which starts with alphabets after IP word and also
delete that line which do not starts with 192.168.180 after IP word
awk approach:
awk '$4!~/^[[:alpha:]]/ && $4~/^192\.168\.180/' file
space is a default field separator in awk.
$4!~/^[[:alpha:]]/:
$4 - fourth field
!~ - not matches
/^[[:alpha:]]/ - regular expression, means "starts with alphabetic characters"
&& - boolean "and" operator.
boolean1 && boolean2 - True if both boolean1 and boolean2 are true.
$4~/^192\.168\.180/ - matches a line if the fourth field starts with 192.168.180
Additional approach:
To strip the unneeded parts of certain columns use the following approach:
awk -v p=".[^.]+$" '$4!~/^[[:alpha:]]/ && $4~/^192\.168\.180/
{$7=$8="";for(i=2;i<=6;i+=2)gsub(p,"",$i);print}' file
The output:
2017-04-10 12:23:00 IP 192.168.180.3 > www.facebook.com
2017-04-10 12:23:09 IP 192.168.180.31 > www.facebook.com
A: I - - want to remove lines which starts with alphabets after IP word and also means (essentially) the same thing as keep lines which start with numerals and
delete that line which do not starts with 192.168.180 after IP word means to keep lines which have with IP 192.168.180 in them and basically makes the first requirement obsolete. man grep:
DESCRIPTION
grep searches the named input FILEs for lines containing a match to the
given PATTERN. - - By default, grep prints the matching lines.
Try:
grep "IP 192.168.180" file
2017-04-10 12:23:00.836184 IP 192.168.180.3.43095 > www.facebook.com.443: tcp 303
2017-04-10 12:23:09.986789 IP 192.168.180.31.47172 > www.facebook.com.443: tcp 0
A: You can try sed, something like this, it just syntax:
sed -e '/pattern here/ { N; d; }'
N and d are the command you can use.
This delete 1 lines after a pattern (including the line with the pattern):
patter= your string
sed -e '/pattern/,+1d' file.txt | unknown | |
d7405 | train | Unfortunately, I don't have enough karma to comment, so I'll do the best I can to provide a solution here.
Have you made sure to run 'rails generate devise:install' before attempting to generate the devise model? Also make sure that you ran 'bundle install' before you attempt either of installing Devise or generating a model.
A: hope u followed these steps:-
*
*Add gem 'devise' to gemfile
*Run the bundle command to install it.
*After you install Devise and add it to your Gemfile, you need to run the generator:
rails generate devise:install
The generator will install an initializer which describes ALL Devise's configuration options and you MUST take a look at it.
4. When you are done, you are ready to add Devise to any of your models using the generator:
rails generate devise MODEL | unknown | |
d7406 | train | Instead of using SelectedRows property of the DataGridview you can use as follows
dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red;
Because SelectedRows property will return rows when row(s) has been selected by the User only, if no rows are selected then your code will throw exception.
EDIT :
For your doubt here am providing a sample code, hope it will help you.
for (int i = 0; i < 10; i++)
{
if (dataGridView1.Rows.Count > i)
{
if (i == 1)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red;
else if (i == 2)
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue;
else
dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green;
}
}
A: You may handle different events of your datagrid and set cell style
Here is example from related question
private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex != color.Index)
return;
e.CellStyle.BackColor = Color.Red;
} | unknown | |
d7407 | train | The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
A: You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
A: If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking. | unknown | |
d7408 | train | you can use the parameter quotechar
data = pd.read_csv("a.txt", delim_whitespace=True, header=None,quotechar="~")
print(data.head())
a.txt
abc def xyz
"abc xyz" def
Output
0 1 2
0 abc def xyz
1 "abc xyz" def
there are qoutes left this way.
A: Try via numpy's genfromtxt() method:
import numpy as np
data=np.genfromtxt('data.csv',dtype='str',delimeter='\t',skip_header=1)
columns=np.genfromtxt('data.csv',dtype='str',delimiter='\t',skip_footer=len(data))
Finally:
df=pd.Dataframe(data=data,columns=columns) | unknown | |
d7409 | train | NSMutableArray *imagename = [[NSMutableArray alloc] initWithObjects:@"http://4cing.com/mobile_app/uploads/pageicon/6.jpg", nil];
UIImageView *imgDescView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 200, 200)];
imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]]]]];
it is working ... i think u r not creating array properly.
A: You need to verify the NSArray contents. Log out the objects of the array:
NSLog(@"imagename = %@",[imagename description]);
Also, a side-note - might want to think about loading that image dynamically. I wrote a class that makes this pretty painless:
https://stackoverflow.com/a/9786513/585320
The answer is geared toward using in TableViews (where lag would really hurt performance), but you can (and I do) use this for any web image loading. This keeps the UI fluid and is very fast.
A: Hi create url in this manner
[NSURL URLWithString:[[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
i think it will work and will resolve ur problem. | unknown | |
d7410 | train | Based on feedback from cYrixmorten, I moved the Async execute call to the onCreateOptionsMenu. Here is the modified code.
Modified onCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.review_fragment_gridview, container, false);
mGridView = (StaggeredGridView) view.findViewById(R.id.myGrid);
bundle = savedInstanceState;
reviews = new ArrayList<Review>();
offset = 0;
ReviewLoaderAsyncTask loadRSSTask = new ReviewLoaderAsyncTask(getActivity(), offset, new FragmentCallback() {
@Override
public void taskIsFinished(ArrayList<Review> add, int _offset) {
for (Review v : add) {
reviews.add(v);
}
System.out.println(reviews.size() +" is the video size!");
mReviewsAdapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager());
offset = _offset;
mGridView.setAdapter(mReviewsAdapter);
}
});
if(savedInstanceState!=null){
reviews = savedInstanceState.getParcelableArrayList(REVIEWS_LIST_TAG);
ReviewsAdapter adapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager());
mGridView.setAdapter(adapter);
((BaseAdapter) mGridView.getAdapter()).notifyDataSetChanged();
}
return view;
}
Modified onCreateOptionsMenu:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.videos, menu);
menuItem = menu.findItem(R.id.button_refresh);
ReviewLoaderAsyncTask loadRSSTask = new ReviewLoaderAsyncTask(getActivity(), offset, new FragmentCallback() {
@Override
public void taskIsFinished(ArrayList<Review> add, int _offset) {
System.out.println(add.size() + "is the passed array size to the callback");
for (Review v : add) {
reviews.add(v);
}
mReviewsAdapter = new ReviewsAdapter(getActivity(), reviews, getFragmentManager());
offset = _offset;
mGridView.setAdapter(mReviewsAdapter);
}
});
if(bundle == null){
loadRSSTask.execute();
}
super.onCreateOptionsMenu(menu, inflater);
}
This works, but I will not mark it as the solution for now in hopes to promote more discussion and alternative solutions to this question. | unknown | |
d7411 | train | ABRecord is an opaque C type. It is not an object in the sense of Objective-C. That means you can not extend it, you can not add a category on it, you can not message it. The only thing you can do is call functions described in ABRecord Reference with the ABRecord as a parameter.
You could do two things to be able to keep the information referenced by the ABRecord arround:
*
*Get the ABRecords id by ABRecordGetRecordID(). The ABRecordID is defined as int32_t so you can cast it to an NSInteger and store it wherever you like. You can later get the record back from ABAddressBookGetPersonWithRecordID () or ABAddressBookGetGroupWithRecordID(). But aware, the record could be changed or even deleted by the user or another app meanwhile.
*Copy all values inside the record to a standard NSObject subclass and use NSCoding or other techniques to store it. You will then of cause not benefit from changes or additions to the record the user could have made.
Of cause you can combine both approaches. | unknown | |
d7412 | train | According to the docs, linprog finds the minimum, while your proposed solution is the maximum. | unknown | |
d7413 | train | Since .spotlight-box is absolutely positioned, its parent needs to be relatively positioned if you want it to sit properly inside the parent:
.spotlight-container {
position: relative;
}
Fiddle: http://jsfiddle.net/ctdu9bzk/4/ | unknown | |
d7414 | train | It seems that you did not configured the URI with the credentials to connect to the database. You can find the description of the configuration file at http://docs.tryton.org/projects/server/en/latest/topics/configuration.html#uri
Once you have a configuration file, you must run the command like this:
python3 ./trytond-admin --all --database=health -c /path/to/trytond.conf | unknown | |
d7415 | train | You can check that by imply calling getImageData() or even just fillRect() right after your drawImage() call.
If the returned ImageData is empty, or if there is no rect drawn over your video frame, then, yes, it might be async, which would be a terrible bug that you should report right away.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var vid = document.createElement('video');
vid.muted = true;
vid.crossOrigin = 'anonymous';
vid.src = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm'
vid.play().then(() => {
ctx.drawImage(vid, 0, 0);
console.log(
"imageData empty",
ctx.getImageData(0, 0, canvas.width, canvas.height).data.some(d => !!d) === false
);
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 50, 50);
});
document.body.append(canvas);
So now, to give a better explanation as to what you saw, the debugger will stop the whole event loop, and Chrome might have decided to not honor the next CSS frame drawing when the debugger has been called. Hence, what is painted on your screen is still the frame from when your script got called (when no image was drawn).
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var vid = document.createElement('video');
vid.muted = true;
vid.crossOrigin = 'anonymous';
vid.src = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/a/a4/BBH_gravitational_lensing_of_gw150914.webm/BBH_gravitational_lensing_of_gw150914.webm.480p.webm'
vid.play().then(() => {
ctx.drawImage(vid, 0, 0);
const hasPixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data.some(d => !!d);
alert('That should also block the Event loop and css painting. But drawImage already happened: ' + hasPixels)
});
document.body.append(canvas);
canvas{
border:1px solid;
} | unknown | |
d7416 | train | This was fixed when I instead decided to add the data into some other cells, and then create a Macro that ran in order to grab the information from the cells and place them in the form fields. | unknown | |
d7417 | train | thanks for the this, helped me get started with uploading a video to parse, I figure out your issue, you just didn't put the parse file in your parseobject. basically you never sent the video
File inputFile = new File(uri.toString());
FileInputStream fis = new FileInputStream(inputFile);
ByteArrayOutputStream bos= new ByteArrayOutputStream();
byte[] buf = new byte[(int)inputFile.length()];
for (int readNum; (readNum=fis.read(buf)) != -1;){
bos.write(buf,0,readNum);
}
byte[] bytes = bos.toByteArray();
ParseFile file = new ParseFile("testVideo1.mp4", bytes);
ParseObject parseObject = new ParseObject("chat1");
//addition
parseObject.put("video",file);
//it should work with this
parseObject.saveInBackground(); | unknown | |
d7418 | train | The bit you're missing is that is that an unsuccessful match resets the position.
$ perl -Mv5.14 -e'$_ = "abc"; /./g; /x/g; say $& if /./g;'
a
Unless you also use /c, that is.
$ perl -Mv5.14 -e'$_ = "abc"; /./gc; /x/gc; say $& if /./gc;'
b
A: When your match fails, In the link to Mastering Perl that you provide, I wrote:
I have a way to get around Perl resetting the match position. If I want to try a match without resetting the starting point even if it fails, I can add the /c flag, which simply means to not reset the match position on a failed match. I can try something without suffering a penalty. If that doesn’t work, I can try something else at the same match position. This feature is a poor man’s lexer.
My example that I think you are trying to use has /gc on all the matches using \G. | unknown | |
d7419 | train | NullReferenceException is thrown when you try to access member of a variable set to null.
MissingReferenceException is thrown when you try to access a GameObject that has been destroyed by some logic in your code. | unknown | |
d7420 | train | Just pass $BUILD_NUMBER as a parameter to your remote shell script when you fill out the Command field in your build step. For example:
Remote shell script contents:
echo "Build number is $1"
Command field contents:
"/path/to/myshellscript $BUILD_NUMBER"
A: Just in case somebody is still puzzling over this issue, as the SSH Exec command still behaves in the same undocumented way, you need to quote the parameters you wish to pass to the command, for example :
/path/to/script "$BUILD_NUMBER" "$GIT_BRANCH"
A: Using SSH plugin to execute ssh on remote host, do below :
export BUILD_NUMBER
/path/to/myshellscript | unknown | |
d7421 | train | I suggest this new library Printy
Just released version 1.2.0 as a cross-platform library.
Check it out:
Printy on github
It is based on flags so you can do stuff like
from printy import printy
# with global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello world", "rBU")
# with inline formats, this will apply a dim(D)
#blue (b) to the word 'Hello' and a striked (S)
#yellow (y) to the word 'world', the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text") | unknown | |
d7422 | train | var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
script.innerHTML = 'alert("hello");';
head.appendChild(script);
A: You may be able to use document.write. I don't know if you can use that for javascript, but I recommend that the server should pass codes plus an element name to the client, and then execute a certain method based off of that. | unknown | |
d7423 | train | The way I've done it is by...
1) wrapping my component in a js file
import MyWidgit from './MyWidgit.vue';
// eslint-disable-next-line import/prefer-default-export
export const mount = (el, props) =>
new window.Vue({
el,
render: h => h(Filter, {props})
});
2) using rollup to generate the code (I think it's a better fit for generating libraries)
{
input: `./src/${widgetName}/${widgetName}.js`, // Path relative to package.json
output: {
format: 'umd',
name: widgetName,
file: `./dist/${widgetName}.js`,
exports: 'named',
external: ['vue'], // requires vuejs lib to be loaded separately
globals: {
vue: 'Vue',
},
},
//... etc
}
3) add to html
<script src="/dist/vue.js"></script>
<script src="/dist/mywidgit.js"></script>
<!-- mywidgit mount target-->
<div id="widget1"></div>
<!-- init and mount -->
<script>
mywidgit.mount('#widget1', {
msg: 'all is well',
});
</script>
A: To solve this issue, I removed the --inline-vue argument from the CLI build and added Vue.JS via the CDN, ie.
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
I believe this should work from a single lib, so this is potentially an issue with the build tool. | unknown | |
d7424 | train | Just do
plt.bar([row[0] for row in votes_count], [row[1] for row in votes_count])
A: If you know pandas , it will be very easy.
votes=pd.DataFrame(data=votes,columns=['List'])
votes.List.hist() | unknown | |
d7425 | train | The only solution that I managed to work out, which is not handy nor elegant but somehow works is such query:
"query": {
"bool": {
"should": [
{
"nested": {
"path": "authors",
"query": {
"multi_match": {
"query": "higgs",
"fields": ["last_name^2"]
}
}
}
},
{
"multi_match": {
"query": "higgs",
"fields": ["abstract.summary^5"]
}
}
]
}
}
I'm also not sure if the boosting will work as expected, providing it's set in different queries. Any suggestions appreciated.
A: Changing your mapping to the following one which uses include_in_root: true will allow you to use the query you original wrote:
{
"abstract": {
"properties": {
"summary": {
"type": "string"
}
}
},
"authors": {
"type": "nested",
"include_in_root": true,
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
}
}
}
}
You may want to index inner objects both as nested fields and as flattened object fields. This can be achieved by setting include_in_parent to true. - Link
Note: include_in_root may be deprecated in future versions of elasticsearch in favor of copy_to. | unknown | |
d7426 | train | That means something went wrong in the python-for-android build step, but there are tons of problems that would give that error.
Could you set the buildozer token log_level = 2 in your buildozer.spec and try it again (by default it will be 1). This will get buildozer to print much more information about the build process, including hopefully more about the error. Then, could you include that error information here? | unknown | |
d7427 | train | *
*Copying the token is not easy as you will store it in local storage of browser. It will be more secure than stealing cookie.
*You can add one more claim : Mac Address. Then on each request compare the Mac Address of Request with Mac of Claim.
*Use a long random string, it should be enough. I would recommend 25 characters as standard. Don't store the key in web.config. Your token is as secure as the secrecy of your key. | unknown | |
d7428 | train | Since data is being extracted from file names as well, I'll leave the first use of grep as is
$ # this won't depend on knowing how many matches are found per line
$ # this would also work if there are different number of matches per line
$ grep '!' encutkpoint_calculations/* | perl -lne 'print join " ", /\d+(?:\.\d+)?/g'
7.969 80 2 152.03886767
7.969 80 4 152.10112473
7.969 80 6 152.10200398
7.969 80 8 152.10203172
Alternate is to post process the data, if number of matches is constant per line
grep '!' encutkpoint_calculations/* | grep -oP '\d+(\.\d+)?' | pr -4ats' ' | unknown | |
d7429 | train | Not in Simple MAPI. If you were using Outlook Object Model or Extended MAPI, you could set a special MAPI property on the message before sending it to disable TNEF format. | unknown | |
d7430 | train | Call dialog.dismiss() before password = input.getText().toString() and add dialog.dismiss() inside setNegativeButton's OnClickListener too. | unknown | |
d7431 | train | My simple explanation of what props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.
change your function component to
function Item(props) {
return (
<div>
{props.children}
<div>
);
}
Reference : react's props children
A: @Kirill I hope this will help you .
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
{children}
<div>
);
}
Then you can call your Item like this:
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
also you can pass other element as children to your Item Component also:
<Item value="foo">
<p>Foo</p>
</Item>
A: You can destructure the component children from props.
function Item({ value, children }) {
return <div><p>{children}: {value}</p></div>;
}
function Example() {
return (
<div>
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById("react")
);
p { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Additional documentation
*
*Destructuring assignment
A: I guess this should work.
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
<p>{children}</p>
<div>
);
} | unknown | |
d7432 | train | You're doing a switch over a String, right? That's why you can, of course, add cases, that won't really happen (like "Not available to execute"). Why don't you just change your possible Strings to an enum and make obj.style return a constant from that enum? This is how you can restict those Strings.
fun style(): XYZValues {
if (true) {
return XYZValues.BIG_TEXT
}
return XYZValues.DEFAULT
}
enum class XYZValues(desc: String) {
DEFAULT("DEFAULT"),
BIG_TEXT("BIG_TEXT")
//more }
}
fun main(args: Array<String>) {
when (style()) {
XYZValues.BIG_TEXT -> println("1")
XYZValues.DEFAULT -> println("2")
}
} | unknown | |
d7433 | train | The palindrome_below definition is an instance method on Fixnum. An instance method is a function that can be called on an instance of a class (in contrast to a class method, which is called on the class itself).
Given this code, any instance of Fixnum will have access to palindrome_below method whereinself refers to the Fixnum instance itself (and i refers to the argument being passed to the method call).
14.palindrome_below(5)
#=> [1, 2, 3, 4, 6, 12] # `self` refers to the Fixnum `14`
Consequently, the output below is identical to the example above:
(1...14).select{|f| f.to_s(5) == f.to_s(5).reverse}
#=> [1, 2, 3, 4, 6, 12]
A: x...y creates a Range with the interval (x, y]. In your context, self is referring to an instance of Fixnum.
Any integer that can be represented in one native machine word is an instance of Fixnum. Here is a simple example:
class Fixnum
def double
self * 2
end
end
# self is `2`
2.double # => 4
# self is `8`
8.double # => 16 | unknown | |
d7434 | train | My process to do such a transition was gradual, I had a similar Grunt configuration.
These are my notes & steps in-order to transition to Webpack stack.
The longest step was to refactor the code so it will use ES6 imports/exports (yeah, I know you have said that it is not a phase that you wanna make, but it is important to avoid hacks).
At the end each file looks like that:
//my-component.js
class MyComponentController { ... }
export const MyComponent = {
bindings: {...},
controller: MyComponentController,
template: `...`
}
//main.js
import {MyComponent} from 'my-component'
angular.module('my-module').component('myComponent', MyComponent);
In order not going over all the files and change them, we renamed all js files and added a suffix of .not_module.js.
Those files were the old untouched files.
We added grunt-webpack as a step to the old build system (based on Grunt).
It processed via Webpack all the new files (those that are without .not_module.js suffix).
That step produced only one bundle that contains all the files there were converted already, that file we have added to concat step.
One by one, each converted file gradually moved from being processed by Grunt tasks to be processed by Webpack.
You can take as a reference that webpack.config.
Good luck. | unknown | |
d7435 | train | "Not recognized" is normally the way terminals politely tell you they don't know what you typed means.
If you can use Git from a command line, then it's installed properly. You can use where git or which git depending on your command line to find the path of the functioning Git (if those don't work, please specify your terminal type in the question).
Once done, open Visual Studio Code, hit Ctrl + , to open settings and type git path in the search. Add this path, and you should be able to use Git in Visual Studio Code. | unknown | |
d7436 | train | First of all try with post method instead of get.
A: Please add name property to your input element as
<input type="date" name="date" placeholder="Choisir une date">
You should get the value for date param in your controller method now. The name property should match with your controller method parameter name.
A: <form action="/Home/Index" method='get'>
<input type="date" name="ChoisirDate">
<br/>
<input type="submit" value="Submit">
<input type="reset">
</form>
And in controller
public IActionResult Index(string ChoisirDate) {
string ChoisirDateText = ChoisirDate;
Return View();
} | unknown | |
d7437 | train | You can use iptables:
iptables -A FORWARD -p tcp -i eth0 -s localhost -d x.x.x.x --dport 3306 -j ACCEPT
where x.x.x.x is the mysql server ip address, and eth0 is the interface you use.
A: It seems like you are asking if you are on a Linux machine you want to query to localhost and have that query forwarded to a SQL Server. In this case the above answer is partially correct and will allow packets to be forwarded but doesn't actually perform the forward/redirect. You also say "SQL Server" which I take to mean MS SQL Server. The default port in this case is listed as 1433. You would actually need (2) rules:
# iptables -t nat -A PREROUTING -p tcp -i lo -d localhost --dport 1433 -j DNAT --to-destination x.x.x.x # where x.x.x.x is the SQL Server IP address
# iptables -A FORWARD -i lo -p tcp --dport -j ACCEPT # only if your default FORWARD policy is DROP. Otherwise you just need the prerouting rule. | unknown | |
d7438 | train | I've stumbled upon the same issue and found the answer here :
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/7fcf8bb8-16e5-4be8-afd3-a21e565657d8/drag-and-drop-gridview-items-and-disabled-scrollbar
It appears that with a GridView you can't initiate the drag horizontally, you have to do it vertically and it's the exact opposite with the ListView.
So if you want to drag 'n drop items horizontally you have to use a ListView. (as recommended in the MS guidelines http://msdn.microsoft.com/en-us/library/windows/apps/hh465299.aspx )
Regards | unknown | |
d7439 | train | I have solved the problem - I just delted the web.config File in laravels /public-Folder.
Now, Laravel and RDWeb works - I hope I don't have further problems.
Thank you for your answers. | unknown | |
d7440 | train | Drag it to the Applications folder (as the green arrow suggests), and then run it from that folder rather than from the disk image. | unknown | |
d7441 | train | The problem with a Raycast is: It only checks one single ray direction. That makes no sense in your use case.
You probably want to use Physics2D.OverlapCollider
Gets a list of all Colliders that overlap the given Collider.
and do e.g.
// Reference via the Inspector
public LineRenderer theLine;
// configure via the Inspector
public ContactFilter2D filter;
private Collider2D lineCollider;
private readonly List<Collider2D> overlaps = new List<Collider2D>();
private readonly HashSet<Collider2D> alreadySeen = new HashSet<Collider2D>();
private void Awake()
{
// as fallback assume same GameObject
if(!theLine) theLine = GetComponent<LineRenderer>();
lineCollider = theLine.GetComponent<Collider2D>();
}
public void GetOverlappingObjects()
{
var amount = Physics2D.OverlapCollider(lineCollider, filter, overlaps);
for(var i = 0; i < amount; i++)
{
var overlap = overlaps[i];
if(alreadySeen.Contains(overlap)) continue;
alreadySeen.Add(overlap);
var overlapObject = overlap.gameObject;
// These checks are actually kind of redundant
// the second heck for the component should already be enough
// instead of the tag you could rather use a Layer and configure the filter accordingly
if (!overlapObject.CompareTag("Player")) continue;
if (!overlapObject.TryGetComponent<GridSquare>(out var gridSquare)) continue;
words.tekstSlova.text += gridSquare.tekst;
}
} | unknown | |
d7442 | train | Actually, Apple does all this automatically, just name your NIB files:
MyViewController~iphone.xib // iPhone
MyViewController~ipad.xib // iPad
and load your view controller with the smallest amount of code:
[[MyViewController alloc] initWithNibName:nil bundle:nil]; // Apple will take care of everything
A: Your interface files should be named differently so something like this should work.
UIViewController *someViewController = nil;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
someViewController = [[UIViewController alloc] initWithNibName:@"SomeView_iPad" bundle:nil];
}
else
{
someViewController = [[UIViewController alloc] initWithNibName:@"SomeView" bundle:nil];
}
A: You should use a initializer -[UIViewController initWithNibNamed:bundle:];.
In your SomeViewController.m:
- (id)init {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if (nil != (self = [super initWithNibName:@"SomeViewControllerIPad"])) {
[self setup];
}
} else {
if (nil != (self = [super initWithNibName:@"SomeViewControllerIPhone"])) {
[self setup];
}
}
return self;
} | unknown | |
d7443 | train | Basically the problem is, as I understand, that you're trying to open your .html template directly from IDEA. Which means you're not using the thymeleaf engine to render it - you're just opening the template itself and not the resulting page. If you open the source code of this page using your browser's dev tools, you will see that all your expressions stay unprocessed which leads to it trying to fetch the resources on the wrong port (e.g. 63342 instead of 8080 where your application is really running and is ready to serve the resources).
Thus, you cannot edit your templates like this. But Thymeleaf does have an option to do that. If you're running your Spring Boot application from the IDE directly (e.g. a profile in Intellij IDEA Ultimate) you can add the following to your application.properties:
spring.thymeleaf.cache=false
This will tell your Spring template resolver that you do not want to cache your .html templates and it will load the files from disk every time, so if you modify your template and then hit IDE's build button it should re-package your template and when you refresh your page in browser it will load (and process!) the edited one.
Caution! Only use this for development builds, set value to true for production environments to prevent unnecessary re-reading.
See Spring Boot Docs on Hot Swapping for more.
A: if you want intelj to display your image you have to add a regular src and add a th:src to show the image when the program is run. Try adding both
<img th:src="@{/assets/img/image.svg}" src="../static/assets/img/image.svg"/> | unknown | |
d7444 | train | For each country div add style="display:none", e.g.:
This will hide the div but will keep default country selection. | unknown | |
d7445 | train | You need to use track by as the error suggests. If you don't have a unique key to use you can use $index.
ng-repeat='talent in talents.data | testFilter:filterInput track by $index'
Here is a working example with your code: http://jsfiddle.net/hwT4P/ | unknown | |
d7446 | train | Put them side to side (in html structure) and use the adjacent sibling selector +
Something like this
html
<input type="checkbox" id="box1" />
<label for="box1">checkbox #1</label>
css
input[type="checkbox"]{
position:absolute;
visibility:hidden;
z-index:-1;
}
input[type="checkbox"]:checked + label{
color:red;
}
you could style the label (2nd rule) as you want of course..
demo at http://jsfiddle.net/kb67J/1/ | unknown | |
d7447 | train | The problem is the naming of the userControl in its owning Window. I named as:
Name="UserCtrlSimulator"
instead of:
x:Name="UserCtrlSimulator"
You can find the bug and a more useful error message by removing the reference of that badly named object (remove any reference to the object named without the "x:").
I can't tell the exact reason why it is like this ??? But my solution works fine.
Hope it can help anybody because I lost a lots of time with this weird bug. | unknown | |
d7448 | train | Fixed by updating Express to version 4.9.
Edit: Turns out I've been doing it wrong, as noted in the documentation. | unknown | |
d7449 | train | *
*always test your code to https://shellcheck.net on errors (you have too much do statements)
*bash can't compute floating numbers itself, use bc [1] instead
*to do arithmetic substitution, use $(( ))
*to do arithmetic, without arithmetic substitution, use (( )) form
*UPPER CASE variables are reserved for system, better use lower case
*inflation=(0 0.03 0.05) is an array, you can access it via "${inflation[@]}"
*quote variables ! [2]
[1] bc
bc <<< "scale=2; (4000*((1+0.07*(1-$r))/(1+$i))^10)"
[2]
Learn how to quote properly in shell, it's very important :
"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
Command Substitution: "$(cmd "foo bar")" causes the command 'cmd' to be executed with the argument 'foo bar' and "$(..)" will be replaced by the output. See http://mywiki.wooledge.org/BashFAQ/002 and http://mywiki.wooledge.org/CommandSubstitution
$((...)) is an arithmetic substitution. After doing the arithmetic, the whole thing is replaced by the value of the expression. See http://mywiki.wooledge.org/ArithmeticExpression
((...)) is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.
Finally
#!/bin/bash
echo "Calculating the value v for all given values"
inflation=(0 0.03 0.05)
tax_rate=(0 0.28 0.35)
for i in "${inflation[@]}"; do
for r in "${tax_rate[@]}"; do
v="$(bc <<< "scale=2; (4000*((1+0.07*(1-$r))/(1+$i))^10)")"
echo -n "$v "
done
done
echo
Output
Calculating the value v for all given values
7840.00 6480.00 5920.00 5360.00 4400.00 4000.00 4400.00 4000.00 3600.00 | unknown | |
d7450 | train | Welcome to SO.
Why do you not want the error?
If you just don't want to see the error, then you could always just throw it away with 2>/dev/null, but PLEASE don't do that. Not every error is the one you expect, and this is a debugging nightmare. You could write it to a log with 2>$logpath and then build in logic to read that to make certain it's ok, and ignore or respond accordingly --
mv *.json /dir/ 2>$someLog
executeMyLogParsingFunction # verify expected err is the ONLY err
If it's because you have set -e or a trap in place, and you know it's ok for the mv to fail (which might not be because there is no file!), then you can use this trick -
mv *.json /dir/ || echo "(Error ok if no files found)"
or
mv *.json /dir/ ||: # : is a no-op synonym for "true" that returns 0
see https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html
(If it's failing simply because the mv is returning a nonzero as the last command, you could also add an explicit exit 0, but don't do that either - fix the actual problem rather than patching the symptom. Any of these other solutions should handle that, but I wanted to point out that unless there's a set -e or a trap that catches the error, it shouldn't cause the script to fail unless it's the very last command.)
Better would be to specifically handle the problem you expect without disabling error handling on other problems.
shopt -s nullglob # globs with no match do not eval to the glob as a string
for f in *.json; do mv "$f" /dir/; done # no match means no loop entry
c.f. https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
or if you don't want to use shopt,
for f in *.json; do [[ -e "$f" ]] && mv "$f" /dir/; done
Note that I'm only testing existence, so that will include any match, including directories, symlinks, named pipes... you might want [[ -f "$f" ]] && mv "$f" /dir/ instead.
c.f. https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html
A: This is expected behavior -- it's why the shell leaves *.json unexpanded when there are no matches, to allow mv to show a useful error.
If you don't want that, though, you can always check the list of files yourself, before passing it to mv. As an approach that works with all POSIX-compliant shells, not just bash:
#!/bin/sh
# using a function here gives us our own private argument list.
# that's useful because minimal POSIX sh doesn't provide arrays.
move_if_any() {
dest=$1; shift # shift makes the old $2 be $1, the old $3 be $2, etc.
# so, we then check how many arguments were left after the shift;
# if it's only one, we need to also check whether it refers to a filesystem
# object that actually exists.
if [ "$#" -gt 1 ] || [ -e "$1" ] || [ -L "$1" ]; then
mv -- "$@" "$dest"
fi
}
# put destination_directory/ in $1 where it'll be shifted off
# $2 will be either nonexistent (if we were really running in bash with nullglob set)
# ...or the name of a legitimate file or symlink, or the string '*.json'
move_if_any destination_directory/ *.json
...or, as a more bash-specific approach:
#!/bin/bash
files=( *.json )
if (( ${#files[@]} > 1 )) || [[ -e ${files[0]} || -L ${files[0]} ]]; then
mv -- "${files[@]}" destination/
fi
A: Loop over all json files and move each of them, if it exists, in a oneliner:
for X in *.json; do [[ -e $X ]] && mv "$X" /dir/; done | unknown | |
d7451 | train | Search, don't categorise.
You can display the control as a simple text box, and when the user types in a few characters, you could pop up an autocomplete-like dropdown to select the final value. Here's a link to the jQuery plugin for autocomplete.
A: I really wouldn't have a 30,000 element drop-down. The GUI is supposed to make it easier on the user rather than harder.
If you have no other way to categorise the data other than alphabetically, you're not restricted to using a two-stage approach with just the first character. Make it reliant on the first two characters.
This would give you at most 676 (assuming alphas only) in the first drop-down and (on average) 44 in the second.
We've actually taken two approaches to this problem. BIRT (which we use) allows for cascading parameters which can easily run that second-level query whenever you change the first drop-down box.
However, some of our customers care absolutely zero for nice GUI stuff (other than the output of nice 9-point Verdana and beautiful charts to placate management, of course). They prefer a free-form text entry field where they can just type in "SYS_PAX_%" to change their queries.
Of course, these are the customers that know exactly what data is in their database and use values which lend themselves to categorisation with SQL LIKE clauses. Others prefer the ability to search.
A: I had this same question about 2 years ago concerning a asp.net dropdown box.
Trust me, don't even try it. Use the auto complete suggestions above. I've found that displaying anything above 5000 records tends to crash the browser.
Just my 2 cents.
A: +1 @pax. Still i'd like to see a 30K dropdown! :)
@JustAProgrammer, perhaps you could do a text box where people can type in the beginning of what they are looking for and you can filter as they type in.
A: If you're asking from a performance perspective rather than a usability perspective I would consider using a live-list approach that loads only a subset of the list items on demand as you scroll up or down. If the user clicks down the list quickly, to say the middle, it will load another 10 elements corresponding to that position. Both render time and load time will be much faster.
Like paging, but 'fluid'.
A: Auto complete drop down as suggested above is best to have. But it will require the users to have some idea about the type of entries to start with. If the users are familiar with data, go for it.
Alternatively, if you can categorize your data, then you can start with the categories first and then based on the selection you can populate the dependent drop down with actual values which will be a subset of original values. | unknown | |
d7452 | train | formGroup expects a FormGroup instance means that you did not create an instance for the FormGroup defined in your template which is signupForm
so you have to create an instance for signupForm like this:
this.signupForm = new FormGroup({
// form controls
// arg1 - intial state/value of this control
// arg2 - single validator or an array of validators
// arg3 - async validators
'username': new FormControl(null),
'email': new FormControl(null),
'gender': new FormControl('male')
});
A: Please double check your component code. What I noticed is that the variable you defined there is different to the one specified in your template.
You should change the reference of sigupForm to signupForm instead.
A: In my case, I was using Reactive Forms and loading the data for form asynchronously from a service. But, the form template will start getting generated parallelly. And at that time form would be undefined as it would be built only after the data from API call was received. So, first, check if the form is initialized, then only start generating the template.
<form class="col-sm-12 form-content" *ngIf="form" [formGroup]="form"> | unknown | |
d7453 | train | true == [] is false simply because true is not equal to [].
![] evaluates to false, so true == ![] is false.
Also, true == !![] is true. | unknown | |
d7454 | train | The answer is simple! :
(\[+|$)
Because the only empty string you need to capture is the last of the string.
A: Here's a different approach.
import re
def ismatch(match):
return '' if match is None else match.group()
one = 'this is the first string [with brackets]'
two = 'this is the second string without brackets'
ismatch(re.search('\[', one)) # Returns the bracket '['
ismatch(re.search('\[', two)) # Returns empty string ''
A: Ultimately, the thing I wanted to do is to take a string and, if I find any square or curly brackets, remove the brackets and their contents from the string.
I was trying to isolate the strings that needed fixing first by finding a match and the fixing the resulting list in a second step when all I needed to do was do both at the same time as follows:
re.sub ("\[.*\]|\{.*\}", "", one) | unknown | |
d7455 | train | You can turn your numbers into strings and then sort them.
Afterwards if one number is a pre-number all numbers that start with it will follow and once a number does not start with it anymore you found all.
Example_List=[112,34533344,11234543,98]
list_s = sorted(str(i) for i in Example_List)
result = []
for i in range(len(list_s)):
k=i+1
while k<len(list_s) and list_s[k].startswith(list_s[i]):
result.append((list_s[i],list_s[k]))
k += 1
print(result)
A: If you want to find all numbers, starting with any number from your list you could do something like this:
#Converte your list of ints to list of strings
tmp = map(lambda x : str(x),l)
#Use a set so you duplicate entries are eliminated
result = set()
for x in tmp:
#Insert all numbers starting with the current one
result.update([y for y in filter(lambda z : z.startswith(x) and z != x, l)])
#Convert your set of ints to a list of strings
result = list(map(int, result))
A: A single list comprehension will return all numbers in your list (as integers) which start with a specified "pre-number":
In [1]: Example_List=[112,34533344,11234543,98]
In [2]: [num for num in Example_List if str(num).startswith('112')]
Out[2]: [112, 11234543]
If your pre-number is always the first entry in your list but may be different for different lists then you can still do it in one line, but it's a little longer:
In [3]: [num for num in Example_List[1:] if str(num).startswith(str(Example_List[0]))]
Out[3]: [11234543] | unknown | |
d7456 | train | if you want to search in listed directories (not in scope of your app) then you need a MANAGE_EXTERNAL_STORAGE permission. some doc in HERE | unknown | |
d7457 | train | If someone else has the same problem the reason was because I had installed SSIS 2017 but was using SSMS 18.x , if you have SSIS 2017 use SSMS 17.x and such with other versions | unknown | |
d7458 | train | Magento has helper classes for those kind of methods. So make your extensions and add your methods and you can then later call them like follows
Mage::helper('yourextension/yourhelper')->yourMethod();
Or you can make a library class out of your common methods. | unknown | |
d7459 | train | ## React createtableselect prevent creating element not in option ##
'''
import CreatableSelect from 'react-select/creatable';
const createOption = (label, dataId) => ({
label,
value: dataId,
});
const levelOptions = ([{ "name": "Course1", "id": 1 }, { "name": "Course2", "id": 2 }, { "name": "Course3", "id": 3 }, { "name": "Course4", "id": 4 }])?.map((post, id) => {
return createOption(post.name, post.id);
});
<CreatableSelect
name="dataN"
id="dataN"
className="selctInputs"
placeholder=" Select..."
isMulti
onChange={(e) => getData(e)}
options={Options} />
'''
## Set isLoading to true provides a simple fix ##
'''
<CreatableSelect
isLoading={true}
name="dataN"
id="dataN"
className="selctInputs"
placeholder=" Select"
isMulti
onChange={(e) => getData(e)}
options={Options} />
''' | unknown | |
d7460 | train | Your question isn't very clear, but I'm guessing this is what you want.
Use enumerate() to iterate through brand_search along with the indexes. When you find a match, get the corresponding element of value_search.
for i, item in enumerate(brand_search):
if item in brand:
value = value_search[i]
print(value[search_type[0]:search_type[1]]) | unknown | |
d7461 | train | Every time I run the app, and then re-run it, it saves the same items into the NSUserDefaults even if it is already there.
Yes, because that's exactly what your code does:
defaults.setObject(existingArr, forKey: "D")
But what is existingArr? It's the defaults you've just loaded before:
if var existingArr = NSUserDefaults.standardUserDefaults().arrayForKey("D") as? [String]
So what happens is that when you enter the .contains branch, you always do the same operation: you save the existing array.
Contrary to what your comment in the code states, you're not appending anything to any array in that block, you're saving the existing one. | unknown | |
d7462 | train | Vanilla Javascript
document.querySelector('#parallax-bg1 #bg1-1').style.left = `0-(${scrolled}*.4))px`
Jquery
$('#parallax-bg1 #bg1-1').css('left',(0-(scrolled*.4))+'px'); //parent | unknown | |
d7463 | train | require 'date'
Time.now.to_datetime.rfc3339 | unknown | |
d7464 | train | The streaming buffer is a queue, and the extraction worker processes rows in order. The extraction workers take from the queue either when it reaches a certain volume of data or when a certain amount of time has elapsed in order to write sufficiently large chunks of data to managed storage. The underlying storage format in BigQuery is Capacitor, which reorders rows as it is persisting them to disk and performs a variety of other optimizations as well. | unknown | |
d7465 | train | From your comments, I can understand that you are looking for a value matching the key that the user inputs. You can simply check for it without any splits and for loops like:
var xboxConverter = {
"1": "Up",
"2": "Down",
"3": "Down Foward",
"4": "Backward",
"5": "Standing",
"6": "Forward",
"7": "Up Backward",
"8": "Up",
"9": "Up Foward",
"236S": "Quarter Circle Special",
",": " ",
"H": "B",
"M": "Y",
"L": "X",
"S": "A",
"2": "Down",
"RB": "RB",
"236": "Quarter Circle Forward",
"214": "Quarter Circle Backwards",
"214S": "Quarter Circle Backwards Special",
};
document.querySelector("textarea").addEventListener("keyup", (e) => {
const input = e.target.value.toUpperCase();
const inputValidated = input.replace(/[^a-zA-Z0-9 ,]/g, "");
document.getElementById("output").innerText = xboxConverter[inputValidated] ? xboxConverter[inputValidated] : "No data";
});
<textarea></textarea>
<div id="output"></div>
Is this what you're looking for? | unknown | |
d7466 | train | smallURL:([NSString stringWithFormat:@"bundle://%@", [visuel lpath]])
A: If lpath is of type NSString then you should use %@. It is used every time you need to convert a Cocoa object (or any other descendant of NSObject) into its string representation.
smallURL:(@"bundle://%@", [visuel lpath]) | unknown | |
d7467 | train | My understanding is that destroy() is fired and that should remove the
content script, but if I look in the debugger in dev tools, the script
is still listed after I disable.
I can remove the listeners and the observers when handling the detach
event, but my understanding was that the content script is removed
during the detach so the listeners, should be removed?
This is a very good question.
The detach event is event is meant to let you know it's time to clean your content script. Event listeners need to be removed, anything added to the window scope should also be removed,
You don't need to let the main.js script know when you are done. | unknown | |
d7468 | train | Mostly it's a problem with to big association filters.
Disable the auto created filters and reenable them one by one, to find the problem filter.
This will help you if your filter is not to big:
filter :foo, as: :select, collection: Foo.pluck(:name, :id)
(but works only for rails > 4.0, you can build a similar thing by hand in rails 3.x)
A: Yes, this is usualy because of auto created filters, you can disable filters by:
remove_filter :some_param
Also you can eager-load some association with include in scoped collection, and if you have a huge count of records may be it can help to set:
index pagination_total: false | unknown | |
d7469 | train | Found this and it seems to do the trick if anyone else was interested:
http://www.redips.net/javascript/drag-and-drop-table-content/ | unknown | |
d7470 | train | Because I had simmilar problems and needed a lot of time to fix it, I will summarize the important facts for getting it running:
*
*Install doxygen AND graphviz
*Add the bin directory of graphviz to your windows path variable (e.g. C:\Program Files (x86)\Graphviz2.38\bin)
*In the Settings.ini located in the graphviz bin directory, also set the path (e.g. binPath=C:\Program Files (x86)\Graphviz2.38\bin)
*In doxygen, under the tab "Expert" -> Dot check "HAVE_DOT"
*In doxygen, under the tab "Expert" -> Dot set "DOT_PATH" to your graphviz bin directory like above
These steps did it to make it working for me.
A: I know you found your solution, but for the sake of people like myself coming from Google, I'd like to make this as easy as possible for everyone.
If you're on Windows, and have installed both Doxygen and Graphviz, or if you're on Linux and have used apt-get install doxygen graphviz, the next step is to make sure that you're able to run the dot command from the command prompt/terminal. You can do this by making sure that the Graphviz/bin folder is appended to your PATH file.
Refer to this answer (removed by SO so here is a archive.org link) if you need more details on how to properly set up Doxygen/Graphviz for visualizations
A: On Windows 10 in 2017, I needed to:
*
*Install graphviz from http://graphviz.org/
*In the Dot heading under the Doxygen expert tab, populate DOT_PATH with "C:\Program Files (x86)\Graphviz2.38\bin"
*In the Diagrams heading under the Doxygen Wizard tab, select "Use dot tool from the GraphVizPackage"
A: *
*Go to Control Panel and search for Edit System Environment Variables
*Go to System Properties -> Environment settings -> Path
*Add the path to your Graphviz bin folder at the end of the Path variables.
They are separated with a semicolon ";"
See example below, where I added:
; C:\Program Files (x86)\Graphviz2.38\bin
Alternatively you can use the Setx command from the command window. | unknown | |
d7471 | train | Apparently the issue was caused by the fact that an old version of the translation jsons was cached in the dist folder of my Angular project.
Once I deleted it it all went fine. | unknown | |
d7472 | train | So you want to react to some events happening in the UI. First things first: if you want, in reaction, to change only your view/layout, you do not need ICommand and a simple event handler will do the trick. If you expect to change the underlying data (your view model) in reaction to that event, you can use an ICommand or an event handler, as described below.
Let's first define a simple view model for our MainWindow:
public class MyViewModel {
/// <summary>
/// Command that performs stuff.
/// </summary>
public ICommand MyCommand { get; private set; }
public MyViewModel() {
//Create the ICommand
MyCommand = new RelayCommand(() => PerformStuff());
}
public void PerformStuff() {
//Do stuff that affects your view model and model.
//Do not do anything here that needs a reference to a view object, as this breaks MVVM.
Console.WriteLine("Stuff performed in ViewModel.");
}
}
This assumes that you have a RelayCommand implementation of the ICommand interface that lets you invoke Action delegates on Execute:
public class RelayCommand : ICommand {
//Saved Action to invoke on Execute
private Action _action;
/// <summary>
/// ICommand that always runs the passed <paramref name="action"/> when executing.
/// </summary>
/// <param name="action"></param>
public RelayCommand(Action action) {
_action = action;
}
#region ICommand
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter) => _action.Invoke();
#endregion
}
In your MainWindow.xaml, we define two Border objects: the first one operates on the view model through an event handler, the second one through the ICommand pattern:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<!--Performs action on click through event handler-->
<Border Grid.Row="0" MouseUp="Border_MouseUp" Background="Red"></Border>
<!--Performs action on click through ICommand-->
<Border Grid.Row="1" Background="Blue">
<Border.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding MyCommand}"></MouseBinding>
</Border.InputBindings>
</Border>
</Grid>
In your MainWindow.xaml.cs, assign a view model object and define the event handler for mouse up event:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new MyViewModel(); ;
}
//Handles mouse up event on the first Border
private void Border_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) {
//...
//Do stuff that affects only your view here!
//...
//Now the stuff that affects the view model/model:
((MyViewModel)DataContext).PerformStuff();
}
}
Clicking on any of the two Border objects will perfom stuff on your view model.
How to apply this to your specific control and event?
*
*You can always use a custom event handler DockingManager_LayoutChanged as shown above.
*If you want to use the ICommand and your event is something else than a mouse or keyboard event, you can achieve the binding by following this instead of using a MouseBinding.
A: For such scenarios I always write attached properties.
For example for the Loaded-Event of a Window I use the following attached property:
internal class WindowExtensions
{
public static readonly DependencyProperty WindowLoadedCommandProperty = DependencyProperty.RegisterAttached(
"WindowLoadedCommand", typeof(ICommand), typeof(WindowExtensions), new PropertyMetadata(default(ICommand), OnWindowLoadedCommandChanged));
private static void OnWindowLoadedCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Window window = d as Window;
if (window == null)
return;
if (e.NewValue is bool newValue)
{
if (newValue)
{
window.Loaded += WindowOnLoaded;
}
}
}
private static void WindowOnLoaded(object sender, RoutedEventArgs e)
{
Window window = sender as Window;
if (window == null)
return;
ICommand command = GetWindowLoadedCommand(window);
command.Execute(null);
}
public static void SetWindowLoadedCommand(DependencyObject element, ICommand value)
{
element.SetValue(WindowLoadedCommandProperty, value);
}
public static ICommand GetWindowLoadedCommand(DependencyObject element)
{
return (ICommand) element.GetValue(WindowLoadedCommandProperty);
}
}
In the viewmodel you have a standard command like:
private ICommand loadedCommand;
public ICommand LoadedCommand
{
get { return loadedCommand ?? (loadedCommand = new RelayCommand(Loaded)); }
}
private void Loaded(object obj)
{
// Logic here
}
And on the Window-Element in the XAML you write:
local:WindowExtensions.WindowLoadedCommand="{Binding LoadedCommand}"
local is the namespace where the WindowExtensions is located | unknown | |
d7473 | train | simply make the bot an admin in the targeted group, then the bot will be able to read messages from the group, thus you'll get the id
Or disable privacy mode from BotFather, check the link below:
https://core.telegram.org/bots#privacy-mode | unknown | |
d7474 | train | check this out
./app >> /home/user/logs/debug.log 2> >( while read line; do echo "$(date): ${line}"; done > /home/user/logs/debug.err ) | unknown | |
d7475 | train | 1a) For Eclipse you can either configure the usual WebToolsPlatform (WTP) to do hot deployments.
1b) You can install the JBoss Tools from http://www.jboss.org/tools which might some things smoother. You can think of it as an extension of WTP.
1c) Use a small Ant-Skript to do the same as 2)
2) Simply copy your war file into the subdirectory server/default/deploy. | unknown | |
d7476 | train | So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):
The call fold!(fun)(range, seed) first assigns seed to an internal
variable result, also called the accumulator. Then, for each element
x in range, result = fun(result, x) gets evaluated. Finally, result
is returned. The one-argument version fold!(fun)(range) works
similarly, but it uses the first element of the range as the seed
(the range must be non-empty).
The reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).
The reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.
The documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold
A: I was able to tweak the answer provied by Akshay. The following compiled and ran:
module example;
import std.stdio;
import std.algorithm.iteration : fold;
void main() {
string fileName = "test1.txt";
auto sum = File(fileName, "r")
.byLine
.fold!( (a, b) {
// You can define the lambda function using the `{}` syntax
auto len = b.length;
return a + len;
})(0); // Initialize the fold with a value of 0
} | unknown | |
d7477 | train | You can change your setChart method to this:
func setChart(dataPoints: [String], values: [Double]) {
chartView.noDataText = "You need to provide data for the chart."
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i)+0.5, y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
let chartData = LineChartData(dataSets: [chartDataSet])
chartDataSet.colors = [red]
chartDataSet.drawCirclesEnabled = true
chartDataSet.circleRadius = 16
chartDataSet.circleColors = [red]
chartDataSet.circleHoleRadius = 12
chartDataSet.circleHoleColor = UIColor.white
chartDataSet.lineWidth = 4
chartView.data = chartData
}
Result:
update:
chartView.xAxis.axisMinimum = 0.0 //I changed this from 1 to 0
let xvalues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xvalues)
class MyIndexFormatter: IndexAxisValueFormatter {
open override func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
return "\(value)"
}
} | unknown | |
d7478 | train | Broadly speaking, the advantage of splitting it up into more parts is that you can optimize your processor use.
If the dataset is split into 3 parts, one per processor, and they take the following time:
Split A - 10 min
Split B - 20 min
Split C - 12 min
You can see immediately that two of your processors are going to be idle for a significant amount of time needed to do the full analysis.
Instead, if you have 12 splits, each one taking between 3 and 6 minutes to run, then processor A can pick up another chunk of the job after it finishes with the first one instead of idling until the longest-running split finishes. | unknown | |
d7479 | train | Auto execution/installation of a downloaded file are disabled in every main stream Operating systems, be it windows, android, etc. | unknown | |
d7480 | train | Try changing Navigation view like this
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu"
/>
A: DrawerLayout must contains 2 children (not more than 2). Can you please try this layout
<android.support.v4.widget.DrawerLayout
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/DrawerId"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bird.play.MainActivity">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu" />
</android.support.v4.widget.DrawerLayout>
Please check the doc | unknown | |
d7481 | train | My aim to to create a plain text string, replacing the image based on its title, so I'd have a string like:
Text Before HAMBURGER Text After
An option is to use an XPath query to select the text/titles that you want, and output their respective values.
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><p>Text Before<img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">Text After</p></body></html>';
$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('/html/body//text() | /html/body//img/@title');
$text = '';
foreach ($nodes as $node) {
$text .= $node->nodeValue . ' ';
}
echo $text; // Text Before HAMBURGER Text After
A: You can use XPath to find specific items and then replace them with new nodes.
E.g.
<?php
foreach( range(0,2) as $i ) {
$doc = new DOMDocument;
$doc->loadhtml( getData($i) );
foo($doc);
}
function foo(DOMDocument $doc) {
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//p/img') as $img ) {
$alt = $img->getAttribute('alt');
$img->parentNode->replaceChild(
$doc->createTextNode($alt),
$img
);
}
echo "\n---\n", $doc->savehtml(), "\n---\n";
}
function getData($i) {
$rv = null;
switch($i) {
case 0; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><p>Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20"> Text After</p></body></html>'; break;
case 1; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>
Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
</body>
</html>';
break;
case 2; $rv = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>
Text Before <img alt="HAMBURGER" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
<p>
Text Before <img alt="HAMBURGER2" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
<p>
Text Before <img alt="HAMBURGER3" height="20" src="/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png" title="HAMBURGER" width="20">
Text After
</p>
</body>
</html>';
break;
}
return $rv;
}
prints
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>Text Before HAMBURGER Text After</p></body></html>
---
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>
Text Before HAMBURGER
Text After
</p>
</body></html>
---
---
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>
Text Before HAMBURGER
Text After
</p>
<p>
Text Before HAMBURGER2
Text After
</p>
<p>
Text Before HAMBURGER3
Text After
</p>
</body></html>
---
For your question #2: please elaborate. Can be as simple as echo $doc->documentElement->textContent. But could also end up using XSL(T)
A: You could simply use a regular expression replacement:
<?php
$text = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">#012<html><body><p>Text Before <img alt=\"HAMBURGER\" height=\"20\" src=\"/sites/all/modules/ckeditor/plugins/apoji/images/emoji-E120.png\" title=\"HAMBURGER\" width=\"20\"> Text After</p></body></html>";
$match = array();
preg_match("/<p[^>]*>(.*(?=<\/p))/i", $text, $match);
echo preg_replace("/<img[^>]*title=\"([^\"]+)\"[^>]*>/i", "$1", $match[1]);
?> | unknown | |
d7482 | train | array_splice get first argument by reference, so don't assign result to the same variable name $newString.
array_splice($newString, $wstawwloowo, 0, $inserted); it's enough.
A: $article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';
$words = explode(' ', $article);
// a new array to hold the string we are going to create
$randId = rand(0, sizeOf($words));
array_splice($words, $randId, 0, array('Random string in random place'));
$newString = implode(',', $words);
echo $newString; // Will print the new string | unknown | |
d7483 | train | You must have specified if the path to the directory is absolute or relative. If it is absolute, you can check with -e to see if it exists and with -d if the input given it is a directory or not.
if ( -e $dir and -d $dir) {
print "\nyour folder exists";
}
If the path is relative, then you must create the absolute path. For that you will have to use as $base your drvives (you need to do that for each drive) and after, use rel2abs to find an absolute path for the given relative path. If the folder exists, $abs_path will contain the absolute path, else it's value will be undef. Bellow as an example for searching your folder with a relative path on drive c:\:
$base = 'c:\';
$abs_path = File::Spec->rel2abs( $relative_path ) ;
$abs_path = File::Spec->rel2abs( $relative_path, $base ) ;
if ( defined $abs_path ) {
print "\n folder exists ";
}
For more options, see perldoc -f -X | unknown | |
d7484 | train | The functionalities you are asking for are provided by the PaymentKit library. | unknown | |
d7485 | train | I guess, you have Vrapper or a different plug-in installed that provides these key bindings. If you don't want to have these features, try to uninstall them (select Help -> About from the menu, then click on Installation Details button on the bottom of the About dialog, where you can look for any possible culprits, and uninstall them. | unknown | |
d7486 | train | I found a solution,
In the Filter function You have to use just the Column you need and Filter with this Formula:
COUNT(CONTAINS([Column1], "25")) < 2
After that you just create a new calculation that you put in the Filter, the calculation uses then this Formula:
CONTAINS([Column1], "Santiego") | unknown | |
d7487 | train | Raise an exception. Not only is it the appropriate way to signal an error, it's also more useful for debugging. The traceback includes the line which did the method call but also additional lines, line numbers, function names, etc. which are more useful for debugging than just a variable name. Example:
class A:
def do(self, x):
if x < 0:
raise ValueError("Negative x")
def wrong(a, x):
a.do(-x)
wrong(A(), 1)
This gives a traceback similar to this, if the exception isn't caught:
Traceback (most recent call last):
File "...", line 1, in <module>
wrong(A(), 1)
File "...", line 7, in wrong
a.do(-x)
File "...", line 4, in do
raise ValueError("Negative x")
ValueError: Negative x
You can also use the traceback module to get this information programmatically, even without an exception (print_stack and friends).
A: globals() return a dictionary that represents the namespace of the module (the namespace is not this dictionary, this latter only represents it)
class A(object):
def get_instance_name(self):
for name,ob in globals().iteritems():
if ob is self:
return name
obj = A()
print obj.get_instance_name()
blah = A()
print blah.get_instance_name()
tu = (obj,blah)
print [x.get_instance_name() for x in tu]
result
obj
blah
['obj', 'blah']
.
EDIT
Taking account of the remarks, I wrote this new code:
class A(object):
def rondo(self,nameinst,namespace,li,s,seen):
for namea,a in namespace.iteritems():
if a is self:
li.append(nameinst+s+namea)
if namea=='__builtins__':
#this condition prevents the execution to go
# in the following section elif, so that self
# isn't searched among the cascading attributes
# of the builtin objects and the attributes.
# This is to avoid to explore all the big tree
# of builtin objects and their cascading attributes.
# It supposes that every builtin object has not
# received the instance, of which the names are
# searched, as a new attribute. This makes sense.
for bn,b in __builtins__.__dict__.iteritems():
if b is self:
li.append(nameinst+'-'+b)
elif hasattr(a,'__dict__') \
and not any(n+s+namea in seen for n in seen)\
and not any(n+s+namea in li for n in li):
seen.append(nameinst+s+namea)
self.rondo(nameinst+s+namea,a.__dict__,li,'.')
else:
seen.append(nameinst+s+namea)
def get_instance_name(self):
li = []
seen = []
self.rondo('',globals(),li,'')
return li if li else None
With the following
bumbum = A()
blah = A()
print "bumbum's names:\n",bumbum.get_instance_name()
print "\nmap(lambda y:y.get_instance_name(), (bumbum,blah) :\n",map(lambda y:y.get_instance_name(), (bumbum,blah))
print "\n[y.get_instance_name() for y in (bumbum,blah)] :\n",[y.get_instance_name() for y in (bumbum,blah)]
the result is
bumbum's names:
['bumbum']
map(lambda y:y.get_instance_name(), (bumbum,blah) :
[['bumbum'], ['blah']]
[y.get_instance_name() for y in (bumbum,blah)] :
[['bumbum', 'y'], ['blah', 'y']]
The second list comprehension shows that the function get_instance_name() must be used with care. In the list comp, identifier y is assigned in turn to every element of (bumbum,blah) then the finction finds it out as a name of the instance !
.
Now, a more complex situation:
ahah = A() # ahah : first name for this instance
class B(object):
pass
bobo = B()
bobo.x = ahah # bobo.x : second name for ahah
jupiter = bobo.x # jupiter : third name for ahah
class C(object):
def __init__(self):
self.azerty = jupiter # fourth name for ahah
ccc = C()
kkk = ccc.azerty # kkk : fifth name for ahah
bobo.x.inxnum = 1005
bobo.x.inxwhat = kkk # bobo.x.inxwhat : fifth name for ahah
# Since bobo.x is instance ahah, this instruction also
# creates attribute inxwhat in ahah instance's __dict__ .
# Consequently, instance ahah having already 5 names,
# this instruction adds 5 additional names, each one
# ending with .inxwhat
# By the way, this kkk being ahah itself, it results that ahah
# is the value of its own attribute inxwhat.
print ahah.get_instance_name()
result
['bobo.x', 'bobo.x.inxwhat',
'ahah', 'ahah.inxwhat',
'jupiter', 'jupiter.inxwhat',
'kkk', 'kkk.inxwhat',
'ccc.azerty', 'ccc.azerty.inxwhat']
I concur to judge this solution a little heavy and that if a coder thinks he needs such a heavy function, it is probably because the algorithm isn't optimal. But I find interesting to see that it's possible to do this in Python though it doesn't seem evident.
I say heavy, not hacky, I don't find it's hacky, by the way.
A: No, you can't. Objects can have any number of names, so the question doesn't even make sense. Consider:
a1 = a2 = a3 = A()
What is the name of the instance of A()? | unknown | |
d7488 | train | I believe your problem is this line:
df.index.name = 'Facility'
All this would do is name the existing df index (which looks like 0, 1, 2, 3...) "Facility," rather than taking the existing Facility column and making it the index. To do that, you'd want:
df = df.set_index('Facility')
I found this discrepancy by adding a bunch of print(df.head()) statements after each line where your code modified the dataset, and doing the same in the original Bokeh heatmap example, and looking for where they diverged. Might be useful in case there are other problems. | unknown | |
d7489 | train | You should set user_logger.propagate = False. logging.propagate docs
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
So, your root logger will not send any data to stderr.
This example outputs nothing
import io
import logging
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"
logging.basicConfig(
level=logging.INFO,
format=SERVER_FORMAT,
datefmt=DATETIME_FORMAT,
handlers=[stream_handler])
user_logger = logging.getLogger('user_logger')
user_logger.propagate = False
user_logger.setLevel(logging.INFO)
log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)
log_capture_string_handler.setFormatter(logging.Formatter(SERVER_FORMAT))
user_logger.handlers = [log_capture_string_handler]
user_logger.info('This should only be in "log_capture_string"') | unknown | |
d7490 | train | Your javascript function is returning an object literal, not a JSON string. Probably you need to do the parallel in Java, which would be to return an instance of a class that contains a property named speech, which a getter and setter for speech, and with the value of speech set to "hello lambda java". AWS will probably take care of serializing that object to the JSON response you want.
More typing in Java than Javascript. Ha! I punned.
A: It doesn't really make sense but send the method something like "hello", not JSON. Lambda tries to be smarter than you and, if it sees something that looks like JSON it tries to parse it. But then you ask for a string so it gets confused. Personally I think this is a bug but since you can't pass a "Content-Type" it has to guess.
For reference, if I use this code:
public class HelloWorldLambdaHandler implements RequestHandler<String, String> {
public String handleRequest(String inputObject, Context context) {
context.getLogger().log("context logger - got \"" + inputObject + "\" from call");
return "{\"speech\": \"hello lambda java\"}";
}
}
and test with the string "hello" (yes, including the quotes) I get back what I expect in the Lambda test console. If I send:
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
I get the same error as you. | unknown | |
d7491 | train | Use a TextInputEditText instead of a EditText
<com.google.android.material.textfield.TextInputLayout
...>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
.../>
</com.google.android.material.textfield.TextInputLayout>
Automatically with layout_height="wrap_content" the content uses multiple lines.
Also try the latest version 1.1.0-alpha10.
A: Using TextInputEditText.
Try android: scrollbars="vertical".
Version api "com.google.android.material: material: 1.0.0" | unknown | |
d7492 | train | It is not possible to maintain the format of the text in <textarea> as you requested.
You can achieve maintaining new lines (basically text is wrapped), if some exists in the text.
You have to use "wrap=Hard".
https://www.w3schools.com/tags/att_textarea_wrap.asp
Also refer stackoverflow answers, which has more explanation (look into comments also) about retaining format from text in <textarea>
HTML : How to retain formatting in textarea?
how to preserve formatting of html textarea
A: I was able to figure out how to do it by exporting the text area to a text file, appending the data, then import it back in using
fso.OpenTextFile("C:\file.txt",ForReading).ReadAll and formatting it using
( html body pre )
Doing it that way I was able to hold my line breaks then I send the information using CDO.Message.
Const FOR_APPENDING = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTSO = objFSO.OpenTextFile("C:File.txt", FOR_APPENDING)
objTSO.WriteLine strDT & ":" & vbCrLf & Text2.value & vbCrLf
objTSO.Close()
Sub SendEmail(strSubject, strBody, strBody8, strFrom)
Const ForReading = 1
Dim fso, BodyText
Set fso = CreateObject("Scripting.FileSystemObject")
strMailbox = "Address<[email protected]>"
' E-Mail address being sent to
strSMTPServer = "SMTP Server"
' Primary SMTP relay server name
strSMTPPort = 25
' SMTP Port Number
Set objEmail = CreateObject( "CDO.Message" )
BodyText = fso.OpenTextFile("C:\file.txt",ForReading).ReadAll
With objEmail
.From = strFrom
.To = strMailbox
.Subject = strSubject
.HTMLBody = "<html><body><pre>" & strBody & "<BR>" & BodyText & "<BR>" &
strBody8 & "</pre></body></html>"
With .Configuration.Fields
.Item( "http://schemas.microsoft.com/cdo/configuration/sendusing" ) = 2
.Item( "http://schemas.microsoft.com/cdo/configuration/smtpserver" ) =
strSMTPServer
.Item( "http://schemas.microsoft.com/cdo/configuration/smtpserverport" ) =
strSMTPPort
.Update
End With
.Send ' Send the message!
End With
Set objEmail = Nothing | unknown | |
d7493 | train | it seems cannot be done for now.
when consumeing the topic, consumers would get all tags
A: Tags are only stored in messages, there is no global place to store all tags of a topic, so only consumers can specify tags for filtering and consumption
A: You can't! Since there are no ways to save all tags in the broker.
Actually, you need not know all the tags when you consume. You should only care about the tag you know. If there are some tags that a consumer does not know, which means the messages with that tag should not be consumed by it. | unknown | |
d7494 | train | You want to filter the list based on the country column.
us_movies = [movie for movie in movies if movie[6] == 'USA']
You can also transform the line into just the title if you like.
us_movie_titles = [movie[0] for movie in movies if movie[6] == 'USA']
If you want a corresponding list of match predicate results, this will work:
is_match = [movie[6] == 'USA' for movie in movies]
Note, the size of the first two lists may be smaller than the original list, but is_match will have the same size and ordering as your original list.
To add the booleans to your full dataset:
movies_with_usa = [m[0] + [m[1]] for m in zip(movies, is_match)]
But what you really have is named data, so it's probably more appropriate in a dictionary or object. Also, if you're reading a csv file, a csv reader is part of the standard library. So for something a little more robust
import csv
def read_data(filename):
with open(filename) as f:
reader = csv.DictReader(f)
return [row for row in reader]
def match(record, field, value):
return record[field] == value
data = read_data("movie_metadata.csv")
us_movies = [record for record in data if match(record, 'country', 'USA')]
A: You want to use a pandas dataframe and then you can filter very easily based on the columns.
import pandas as pd
df = pd.DataFrame(movie_data[1:],columns = movie_data[0])
movie_title director_name color duration actor_1_name language country title_year
0 Avatar James Cameron Color 178 CCH Pounder English USA 2009
1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007
2 Spectre Sam Mendes Color 148 Christoph Waltz English UK 2015
df[df.country == "USA"]
movie_title director_name color duration actor_1_name language country title_year
0 Avatar James Cameron Color 178 CCH Pounder English USA 2009
1 Pirates of the Caribbean: At World\'s End Gore Verbinski Color 169 Johnny Depp English USA 2007
A: Just iterate over all movies and compare the 7th column:
made_usa = []
for l in movie_data:
if l[6] == 'USA':
made_usa.append(l)
print (made_usa)
To add only the movie name, it is just to do this:
made_usa = []
for l in movie_data:
if l[6] == 'USA':
made_usa.append(l[0])
print (made_usa)
To save if there is a match or not, you can use a dictionary like this:
made_usa = {}
for l in movie_data:
if l[6] == 'USA':
made_usa.update({l[0]: 'True'})
else:
made_usa.update({l[0]: 'False'})
print (made_usa)
After that, if you want to look if a certain move was made in USA or not. All you need to do is, for example:
print(made_usa['Avatar'])
Output:
'True'
A: Probably you are looking for a generic solution without any third party libraries (i.e. only standard library). Here we go:
def filter_by(csv_data, column_name, column_value):
indices = [i for i, name in enumerate(data[0]) if name == column_name]
if not indices:
return
index = indices[0]
for row in data[1:]:
if row[index] == column_value:
yield row
And this is how you use it:
print(list(filter_by(movie_data, "country", "USA")))
This shall output (I formatted it a bit for clarity):
[
['Avatar', 'James Cameron', 'Color', '178', 'CCH Pounder', 'English', 'USA', '2009'],
["Pirates of the Caribbean: At World's End", 'Gore Verbinski', 'Color', '169', 'Johnny Depp', 'English', 'USA', '2007']
] | unknown | |
d7495 | train | The preprocessorOptions.*.additionalData parameter will only work if there are already loaded/imported css to prepend to, so basically using both options of importing directly into your main.ts file for the bulk and any other preprocessing can be defined in the vite.config.js file.
Th documentation at https://vitejs.dev/config/#css-preprocessoroptions unfortunately does NOT explain this, which did tarnish a perfectly good Saturday night
A: I have had exactly the same problem. Although many vite vue 3 boilerplates do it the same way you and I do, strangely it didn't work, maybe it's a certain vite version that might have bugs.
The only thing that worked for me was the import in main.ts:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
//import your scss here
import "@/assets/scss/style.scss";
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
My versions:
sass: 1.49.8 (you only need the sass package here and not the loader)
vue: 3.2.29
A: Here's what worked for me:
If you haven't, install the Storybook builder for Vite (@storybook/builder-vite)
npm install @storybook/builder-vite --save-dev
or
yarn add --dev @storybook/builder-vite
Then in the .storybook/main.js file,
const { mergeConfig } = require('vite');
module.exports = {
async viteFinal(config, { configType }) {
// return the customized config
return mergeConfig(config, {
css: {
preprocessorOptions: {
scss: {
// Next line will prepend the import in all you scss files as you did with your vite.config.js file
additionalData: `@import "./src/styles/main";`,
},
},
},
});
},
// ... other options here
};
It is almost the same thing as you did, the trick here, is to add the same css.preprocessorOptions.scss object to the storybook configuration via mergeConfig in the main.js file in storybook.
Based on the @storybook/builder-vite documentation | unknown | |
d7496 | train | 1) Do not omit server side validation. MVC has some capabilities built in to do some of that for you on the server side, but it's a good idea to test that it's working. Normally this just tests for type, length, range, and some other basic validation. Any complex validation should be done by you. Either way TEST IT to make sure the correct validation is indeed occurring.
2) Json is most common since it works with JavaScript and is easy to serialize in .Net. I Recommend Newtonsoft.Json as your serialization library. You can use whatever language you can parse however, from protobuff to XML.
A ViewModel is a model that is sent to the view, for what the view needs and generally only goes one way, to the view.
The domain models are the objects you persist, and generally travel both ways, from client to server.
A good example might be that your view requires the current date, manager data, and employee data, so your view model contains properties for all of these, but the form only edits the employee which is a domain model that gets sent back from the client to the server to be persisted.
MVC has ModelBinders that will take your post data and turn them into whatever type you need (supposing you properly follow its conventions.) It's unlikely you'll have to map viewmodels to domain models. | unknown | |
d7497 | train | If you wrote the Apache startup-script yourself, you can include a check if the database instance is already running.
You can include a simple wait-loop:
MYSQL_OK=1
while ["$MYSQL_OK" -ne 0] ; do
echo "SELECT version();" | mysql -utestuser -ptestpassword testdb
MYSQL_OK=$?
sleep 5
done
Obivously you have to create some testuser and the test-database in Mysql:
CREATE DATABASE testdb;
GRANT USAGE,SELECT ON testdb.* TO 'testuser'@'localhost' IDENTIFIED BY 'testpassword';
FLUSH PRIVILEGES;
Simply put the while-loop somewhere in the start) part of your script. If your system is some kind of Redhat-system, you will notice that the start-script /etc/init.d/httpd has a line like this:
Required-Start: $local_fs $remote_fs $network $named
If you add $mysqld to that line, Apache will insist on a running mysqld before startup:
Required-Start: $local_fs $remote_fs $network $named $mysqld
However, the disadvantage is that the Apache startup will fail instead of waiting for running mylsqd.
Good luck,
Alex. | unknown | |
d7498 | train | I never saw a single .gitignore file that prevented me from adding and committing the file in question. However I do remember removing that file from commit using Tortoise.
In any case, I solved the issue by renaming the file, adding it, and committing it, and later on, giving the file its former name. | unknown | |
d7499 | train | I solved the issue !!!
The problem was't with site location, it was because the permalinks are in Hebrew language. I added the following condition to wp-config file
if (isset($_SERVER['UNENCODED_URL'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL'];
}
according to this link: Wordpress Hebrew permalinks
Finally its work ! | unknown | |
d7500 | train | As the resource is read only [...]
No, it is not : the fill() method proceed to writes through the following :
random_numbers.push_back(std::rand()); // write to random_numbers
So the shared mutex really is necessary to synchronize your access to the vector. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.