qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
42,564,910 | I have series of ~10 queries to be executed every hour automatically in Redshift (maybe report success/failure).
Most queries are aggregation on my tables.
I have tried using AWS Lambda with [CloudWatch Events](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html), but Lambda functions only survive for 5 minutes max and my queries can take up to 25 minutes. | 2017/03/02 | [
"https://Stackoverflow.com/questions/42564910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713955/"
] | It's kind of strange that AWS doesn't provide a simple distributed cron style service. It would be useful for so many things. There is [SWF](https://aws.amazon.com/swf/), but the timing/scheduling aspect is left up to the user. You could use Lambda/Cloudwatch to trigger SWF events. That's a lot of overhead to get reasonable cron like activity.
Like the comment says the easiest way would be to run a small instance and host cron jobs there. Use an autoscale group of 1 for some reliability. A similar but more complicated approach is to use [elastic beanstalk](https://stackoverflow.com/questions/14077095/aws-elastic-beanstalk-running-a-cronjob).
If you really want redundancy, reliability, visibility, etc. it might be worth looking at a [third party solution](https://airflow.incubator.apache.org/scheduler.html) like [Airflow](https://github.com/apache/incubator-airflow). There are many others depending on your language of preference.
Here's a [similar question](https://stackoverflow.com/questions/11616205/run-scheduled-task-in-aws-without-cron) with more info. | use aws lambda to run your script. you can schedule it. see <https://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html>
this uses CloudWatch events behind the scenes. If you do it from the console, it will set things up for you. |
41,116,613 | I have a popup model where user add the course name. I have added a form validation in my codeigniter controller and then if the validation is false, I am loading my view again with a form error showing above form input in the model, but due to page reload the model closes. What I want is if the form validation is false I want to reload the page with the modal open. I am not familiar with ajax. Any help will be really appreciated.
Codeigniter Controller
```
$this->form_validation->set_rules('course_name', 'Course Name', 'required|max_length[30]');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if ($this->form_validation->run() ) {
echo "inserted";
}else {
$this->load->view('admin/coursename');
}
```
Codeigniter View (Modal Code)
```
<center><button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Add Course</button><center>
<!-- Modal -->
<div class="modal fade" data-backdrop="static" data-keyboard="false" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Course</h4>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="name">Course Name:</label>
<?php echo form_error('course_name'); ?>
<input type="text" class="form-control" id="name" name="course_name" placeholder="Enter course name...">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Save</button>
<button type="reset" class="btn btn-warning">Cancel</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
``` | 2016/12/13 | [
"https://Stackoverflow.com/questions/41116613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7289695/"
] | [The answer by Eran](https://stackoverflow.com/a/41117159/1421925) is definitely the straightforward way of performing the search. However, I would like to propose a slightly different approach:
```
private static final Map<String, Runnable> stringToRunnable = new HashMap<>();
{
stringToRunnable.put("a", this::doSomething);
stringToRunnable.put("b", this::doSomethingElse);
stringToRunnable.put("c", this::doSomethingElseElse);
}
public static void main(String[] args) {
List<String> names = Arrays.asList("1", "2", "b", "a");
names.stream()
.filter(stringToRunnable::containsKey)
.findFirst()
.ifPresent(name -> stringToRunnable.get(name).run());
}
private void doSomethingElseElse() {
}
private void doSomethingElse() {
}
public void doSomething() {
}
```
The part that does the job is the code below, but I added it to a `main()` function assuming `a`, `b`, and `c` are strings. However, the idea would work with any datatype.
```
names.stream()
.filter(stringToRunnable::containsKey)
.findFirst()
.ifPresent(name -> stringToRunnable.get(name).run());
```
The idea is to keep a map of keys and [`Runnable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)s. By having `Runnable` as value it is possible to define a void method reference without parameters. The stream first filters away all values not present in the map, then finds the first hit, and executes its method if found. | You can use `anyMatch` to find the first element matching one of your conditions and terminate. Use side effects for calling the processing methods :
```
boolean found =
names.stream()
.anyMatch (name -> {
if (name.equals(a)) {
doSomething();
return true;
} else if (name.equals(b)) {
doSomethingElse ();
return true;
} else if (name.equals(c)) {
doSomethingElseElse ();
return true;
} else {
return false;
}
}
);
```
Pretty ugly, but does what you asked in a single iteration. |
6,431,281 | I am developing a chrome extension.
I open an image file in canvas, I apply some changes to it, then I am trying to save it to the HTML5 filesystem api.
First I get the dataURL from the canvas:
```
var dataURL = canvas.toDataURL('image/png;base64');
```
Then just the data:
```
var image64 = dataURL.replace(/data:image\/png;base64,/, '');
```
Then I make a Blob.
```
var bb = new BlobBuilder();
bb.append(image64);
var blob = bb.getBlob('image/png');
```
Then I request the file system with the following function onInitFs();
```
function onInitFs(fs) {
fs.root.getFile('image.png', {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
//WRITING THE BLOB TO FILE
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.PERSISTENT, 5*1024*1024, onInitFs, errorHandler);
```
This results in a corrupted file being written to the file system.
I don't know what else I can do to make this work.
Could someone please guide me in the right direction.
The following are some of the sources to the functions I am using to accomplish this task.
<http://dev.w3.org/html5/canvas-api/canvas-2d-api.html#todataurl-method>
<http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-creatingempty>
Thank You! | 2011/06/21 | [
"https://Stackoverflow.com/questions/6431281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809181/"
] | I've found a function that converts a data URL to a blob.
Great for when you need to save a canvas image to the sandboxed FileSystem. Works in Chrome 13.
```
function dataURItoBlob(dataURI, callback) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var bb = new window.WebKitBlobBuilder(); // or just BlobBuilder() if not using Chrome
bb.append(ab);
return bb.getBlob(mimeString);
};
```
Usage:
```
window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs){
fs.root.getFile("image.png", {create:true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.write(dataURItoBlob(myCanvas.toDataURL("image/png")));
}, errorHandler);
}, errorHandler);
}, errorHandler);
```
Source trail:
<http://mustachified.com/master.js>
via <http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2011-April/031243.html>
via <https://bugs.webkit.org/show_bug.cgi?id=51652>
via <http://code.google.com/p/chromium/issues/detail?id=67587> | I had been wondering the same thing and had a look at finding an answer.
From what I can tell you have to convert the raw string you get from an atob to an unit8array and then you can append it to a blob.
Here's an example that converts an image to a canvas and then the data from the canvas to a blob and then the third images src is set to the uri of the blob....you should be able to add the fs stuff from there....
<http://jsfiddle.net/PAEz/XfDUS/>
..sorry to not put the code here, but to be honest I couldnt figure out how to ;) and anyways, JSFiddle is a nice way to play with it.
References
<https://gist.github.com/1032746>
<http://code.google.com/p/html5wow/source/browse/src/demos/photo-gallery/js/utils.js>
[Get image data in JavaScript?](https://stackoverflow.com/questions/934012/get-image-data-in-javascript)
<http://jsdo.it/tsmallfield/typed_array> |
1,004,696 | A perl script I'm writing needs to parse a file that has continuation lines like a Makefile. i.e. lines that begin with whitespace are part of the previous line.
I wrote the code below but don't feel like it is very clean or perl-ish (heck, it doesn't even use "redo"!)
There are many edge cases: EOF at odd places, single-line files, files that start or end with a blank line (or non-blank line, or continuation line), empty files. All my test cases (and code) are here: <http://whatexit.org/tal/flatten.tar>
Can you write cleaner, perl-ish, code that passes all my tests?
```
#!/usr/bin/perl -w
use strict;
sub process_file_with_continuations {
my $processref = shift @_;
my $nextline;
my $line = <ARGV>;
$line = '' unless defined $line;
chomp $line;
while (defined($nextline = <ARGV>)) {
chomp $nextline;
next if $nextline =~ /^\s*#/; # skip comments
$nextline =~ s/\s+$//g; # remove trailing whitespace
if (eof()) { # Handle EOF
$nextline =~ s/^\s+/ /;
if ($nextline =~ /^\s+/) { # indented line
&$processref($line . $nextline);
}
else {
&$processref($line);
&$processref($nextline) if $nextline ne '';
}
$line = '';
}
elsif ($nextline eq '') { # blank line
&$processref($line);
$line = '';
}
elsif ($nextline =~ /^\s+/) { # indented line
$nextline =~ s/^\s+/ /;
$line .= $nextline;
}
else { # non-indented line
&$processref($line) unless $line eq '';
$line = $nextline;
}
}
&$processref($line) unless $line eq '';
}
sub process_one_line {
my $line = shift @_;
print "$line\n";
}
process_file_with_continuations \&process_one_line;
``` | 2009/06/17 | [
"https://Stackoverflow.com/questions/1004696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71978/"
] | How about slurping the whole file into memory and processing it using regular expressions. Much more 'perlish'. This passes your tests and is *much* smaller and neater:
```
#!/usr/bin/perl
use strict;
use warnings;
$/ = undef; # we want no input record separator.
my $file = <>; # slurp whole file
$file =~ s/^\n//; # Remove newline at start of file
$file =~ s/\s+\n/\n/g; # Remove trailing whitespace.
$file =~ s/\n\s*#[^\n]+//g; # Remove comments.
$file =~ s/\n\s+/ /g; # Merge continuations
# Done
print $file;
``` | If you don't mind loading the entire file in memory, then the code below passes the tests.
It stores the lines in an array, adding each line either to the previous one (continuation) or at the end of the array (other).
```
#!/usr/bin/perl
use strict;
use warnings;
my @out;
while( <>)
{ chomp;
s{#.*}{}; # suppress comments
next unless( m{\S}); # skip blank lines
if( s{^\s+}{ }) # does the line start with spaces?
{ $out[-1] .= $_; } # yes, continuation, add to last line
else
{ push @out, $_; } # no, add as new line
}
$, = "\n"; # set output field separator
$\ = "\n"; # set output record separator
print @out;
``` |
275,956 | I have to find in a folder the files not having certain permissions (755). The sub-directory has other sub-directories containing in total millions of files, and the `find ./ -not -perm 755` command it just takes too long.
Is there a more efficient / faster command to do this task ( like ls combined with grep or so ) ? | 2016/04/12 | [
"https://unix.stackexchange.com/questions/275956",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/137578/"
] | If your intent is to make all the files and directories have 755 permissions, you could simply perform a recursive chmod:
```
chmod -R 755 $directory
```
If you need files to be mode 644, you might be better with
```
chmod -R u=rwX,go=rw $directory
```
This will use a single process to find the necessary files and update their permissions where necessary.
---
If you need to find files with different permissions for some other reason, then `find` will be your best choice. | If you have mlocate installed it makes this easier, but only if you know part of the file name. Also, unless you make permission changes to the mlocate.db file it requires root.
When installed a cron job should run periodically to update the mlocate database, or you can run updatedb to do it manually. Once there use the command locate . |
55,860 | Is there a program available for Vista, that allows me to set up a folder as an SFTP connection to a remote server?
The use case is to have a folder on my desktop, where I can drag/drop/edit files and have my remote location be updated automatically.
I've googled this to no avail. Thanks! | 2009/10/15 | [
"https://superuser.com/questions/55860",
"https://superuser.com",
"https://superuser.com/users/7868/"
] | DirectNet Drive is free for home use.
<http://directnet-drive.net/index.php> | I might be mistaking it for FTPS (I always confuse the two), but I believe this capability is built into windows explorer. Just open a folder window and type an ftp url (including secure items) into an address bar. Something like this:
```
sftp://user:pass@ftpsite.example.com/
```
You should be able to make a normal windows folder shortcut to that location as well. If you leave off the username and password it should prompt you. |
39,775,686 | I am currently working with Laravel 5.2, trying to display images on click
which I have currently stored in the **Storage** folder. I am trying to display these images in my blade view but every time it loads the page, it gets to an undefined variable exception.
**Controller**:
```
public function createemoji($action,$statusId)
{
$path = storage_path('app/public/images/'.$action.'.gif');
/*$request=new storage();
$request->comment=$path;
$request->user_id=Auth::user()->id;
$request->post_id=$statusId;
$request->save();*/
return redirect()->returnemoji()->with('file'->$path);
}
public function returnemoji($file)
{
return Image::get('$file')->response();
}
```
In my default view I tried using **count()** but everytime it loads the page, it gives me **Undefined variable**. How should I display it? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39775686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6668408/"
] | Try to change this:
```
->with('file'->$path);
```
To this:
```
->with('file', $path);
```
<https://laravel.com/docs/5.3/views#passing-data-to-views> | With function takes two arguments key and value
You can use this
```
return redirect()->returnemoji()->with('file',$path);
``` |
15,907,011 | I wrote a Java project using Java SE.
I want the program to start when Windows starts, how can I do that ? | 2013/04/09 | [
"https://Stackoverflow.com/questions/15907011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2192861/"
] | It's easier in the method syntax, as you aren't constrained to the order of the operations:
```
var query = authors.OrderBy(x => x.surname)
.Select(x => new
{
x.id_author,
fullName = String.Concat(x.name, " ", x.surname)
})
.Where(x => x.fullName == "Jean Paul Olvera");
``` | use the `let` clause:
```
var name = (from x in db.authors
let fullName = String.Concat(x.name," ", x.surname)
where fullname = "Jean Paul Olvera"
orderby x.surname
select new { x.id_author, fullName });
``` |
4,940,867 | "“Excuse me, I hope this isn’t weird or anything,"
How can I fix the encoding on this? | 2011/02/09 | [
"https://Stackoverflow.com/questions/4940867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197606/"
] | What you're running into is the result of the data being written in one encoding, and interpreted as being another. You need to make sure that you're requesting input to be in the same format that you're expecting it to be in. I recommend just sticking with UTF-8 the whole way through unless you need to avoid multibyte characters, in which case you might want to look at forcing ASCII.
Make sure you're telling PHP to use UTF-8 internally:
```
ini_set('default_charset', 'UTF-8');
```
And make sure that you are telling the browser to expect UTF-8 encoded text, both in headers…
```
header("Content-Type:text/html; charset=UTF-8");
```
…and in your meta tags (html5 below)…
```
<meta charset="utf-8">
```
Setting this will tell the browser to sent UTF-8 encoded content to you when a form is submitted, and it'll interpret the results you send back as UTF-8 as well.
You should also make sure both your database storage and connection encoding are in UTF-8 as well. Usually as long as it is just a dumb data store (i.e. it won't be manipulating or interpreting the data in any way) it doesn't matter, but it's better to have it all right than run into problems with it later. | The [`iconv`](http://us.php.net/manual/en/function.iconv.php) function is generally able to deal with this sort of encoding issue. |
12,387,067 | I'm trying to match the second dot in a number to replace it later with a white space in my 'find and replace' function in Aptana.
I tried a lot of expressions, none of them worked for me.
For example I take the number:
48.454.714 (I want to replace the dot between 454 and 714) | 2012/09/12 | [
"https://Stackoverflow.com/questions/12387067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1098122/"
] | Try this regex:
```
(\d{3})\.(\d{3})
```
and replace the first and second capturing group `\1 \2`
as mentioned by FiveO, you might want to match other numbers of digits too. E.g. one to 3 digits: `\d{1,3}` or any number of digits: `\d+` | Try with following regex:
```
\d+\.\d+(\.)\d+
```
And replace it with white space. |
52,182,643 | I have created a setup with GetStream, where i have some flat-feeds that contains data and an aggregated-feed that follows the flat-feeds.
I'm now uploading data to the flat-feeds from my database, with my own timestamp added to the activity. Which make my flat-feed ordered by time.
**Here is my problem:** When i'm following the flat-feeds with my aggregated-feed, the aggregated-feed seems to be sorted by last updated activity. Which i want to be sorted by my timestamp.
**My question:** Is i possible to sort the aggregated-feed by my own timestamp? | 2018/09/05 | [
"https://Stackoverflow.com/questions/52182643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7924849/"
] | Stream aggregated feeds are sorted by the `updated_at` field of the aggregated activity.
At the moment there is no way to change this behaviour.
You can sort the activity groups on the client side before presenting the data to users.
Default aggregation format for aggregated feeds is `{{ verb }}_{{ time.strftime('%Y-%m-%d') }}`
You can change your aggregation format to `{{ <name-of-your-custom-timestamp-field> }}` and sort aggregated feed content retrieval results on `group` attribute. | Thanks for responding.
My solution on this problem was to sort the lists, before i uploaded them to GetStream.
*But i still see a potential issue, if i have to upload "older" items later on...* |
22,574,623 | I'm creating a basic page that should look like Figure 1 in this link: <http://www.w3.org/wiki/HTML_structural_elements>
The only thing is, instead of text for the heading, I want to place an image. I am trying to style the image in CSS to size and center it.
Right under the heading I have an ul which is my navigation bar. Then I have the context which will be a couple paragraphs. Lastly I have the footer.
My problem is, when I try to style the header, I end up having to use "background-image" and the header goes behind the navigation bar rather than the very top of the page.
HTML BODY Example:
```
<body>
<div id="header">
<div id="nav">
</div>
</div>
<div id="content">
</div>
<div id="footer">
</div>
</body>
```
What do I have to type in CSS for the header as an image? | 2014/03/22 | [
"https://Stackoverflow.com/questions/22574623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3427030/"
] | ```html
<html>
<head>
<title>CSS image placement</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css" media="screen">
#headline1 {
background-image: url(images/newsletter_headline1.gif);
background-repeat: no-repeat;
background-position: left top;
padding-top: 68px;
margin-bottom: 50px;
}
#headline2 {
background-image: url(im`enter code here`ages/newsletter_headline2.gif);
background-repeat: no-repeat;
background-position: left top;
padding-top: 68px;
}
</style>
</head>
<body>
<div id="headline1">Some text … </div>
<div id="headline2">Some more text .. </div>
</body>
</html>
``` | Just make a block-level image:
```
<div id="header">
<img src="mypic.png" />
<div id="nav"></div>
</div>
```
CSS:
```
img {
display: block;
margin: 0 auto;
}
``` |
42,794,141 | I have an array called `vel` declared inside `global.h` and defined inside `global.cpp`. When I try to use it inside a function, `get_velocities()`, of another class called `Robot` (inside `Robot.cpp`), it says:
>
> undefined reference to `vel'
>
>
>
Here are the three files:
1) `global.h`
```
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
#include <array>
using std::cout;
using std::cin;
using std::endl;
using std::array;
static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num) + 3;
extern array <float, 3> vel;
#endif // GLOBAL_H_INCLUDED
```
2) `global.cpp`
```
#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"
array <float, 3> vel = {0.0, 0.0, 0.0};
```
3) `Robot.cpp`
```
#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"
Robot::Robot(float a, float b, float c){
//ctor
x = a;
y = b;
theta = c;
}
void Robot::get_velocities(){
v_tx = 1.0;
v_ty = 0.0;
omega_t = 0.0;
vel = {v_tx, v_ty, omega_t};
}
```
**Edit:**
I did read this [question](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) . What I realized was that the global variable requires not just a declaration but also a definition. I have provided this definition inside `global.cpp`. Also when I include `#include "global.cpp"` in `Robot.cpp`, it works (But this is not an acceptable practice). So, I believe this error is due to global.cpp not linking properly.
1) Isn't it a common practice to declare global variables in `global.h` and keep the definitions in `global.cpp`? How do I link them properly? I believe that one way is to create a proper `make` file. However, I am using `codeblocks IDE`. How do I do it in this IDE?
2) Is it better to eliminate `global.cpp` and do all definitions for global variables and functions inside the `main` or the file that uses them? | 2017/03/14 | [
"https://Stackoverflow.com/questions/42794141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4834108/"
] | I'd recommend against renaming the development.services.yml file to services.yml because that would cause all of your development code/config/settings to apply and run on production environments. Instead, use the development files as designed.
Here's our standard setup:
`/sites/default/settings.php` (in version control) contains the following at the very bottom so that we only load development stuff on instances that should have it. e.g. NOT production:
```
/**
* Load local development override configuration, if available.
*
* Keep this code block at the end of this file to take full effect.
*/
if (file_exists(__DIR__ . '/settings.local.php')) {
include __DIR__ . '/settings.local.php';
}
```
Our `/sites/default/settings.local.php` (not in version control) contains at least the following:
```
<?php
/**
* Disable css and js preprocessing.
*/
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
/**
* Disable Render Cache and Dynamic Page Cache.
*/
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
/**
* Enable local development services.
*/
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
/**
* Enable access to rebuild.php.
*/
$settings['rebuild_access'] = TRUE;
```
And finally, our `/sites/development.services.yml` (in version control) file contains this:
```
# Local development services.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
parameters:
http.response.debug_cacheability_headers: true
twig.config:
debug: true
auto_reload: true
cache: false
services:
cache.backend.null:
class: Drupal\Core\Cache\NullBackendFactory
```
This has worked really well for us. | You need to set the `cache` option to **true** on your `development.services.yml` file.
Something like this:
```
services:
cache.backend.null:
class: Drupal\Core\Cache\NullBackendFactory
parameters:
twig.config:
debug: true
auto_reload: true
cache: true
```
After you clear your cache and open some pages that you want to debug you will see that in `files/php/twig` some `.php` files will be created, like the bellow image:
[](https://i.stack.imgur.com/cO3OK.png)
on these pages will debug normally as you debug a `.php` file.
There is an article on the Acquia blog that help you make this configuration and debug using Xdebug and the PhpStorm IDE that you can on the link [Debugging TWIG templates in Drupal 8 with PhpStorm and XDebug](https://dev.acquia.com/blog/debugging-twig-templates-in-drupal-8-with-phpstorm-and-xdebug/25/08/2016/16586) |
963,822 | I want to determine a branch of logarithm such that $f(z)=L(z^3-2)$ is analytic at $0$. I am not really sure how to find a branch but I will explain few things I tried.
Since $z^3-2$ maps $0$ onto $-2$, what needs to be done is to find a branch of logarithm which is analytic at $-2$.So if L is a branch of logarithm, by the chain rule we have that $L(z^3-2)$ is analytic at $0$ since $z^3-2$ is analytic at $0$. I just don't know how to proceed from here. Any help will be appreciated. Thanks | 2014/10/08 | [
"https://math.stackexchange.com/questions/963822",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Here are the steps
$$ f(x)=g(x) $$
$$ ax=\sqrt{x} $$
$$ (ax)^2=(\sqrt{x})^2 $$
$$ a^2x^2=|x| $$
Since $x\gt 0$ and $a\gt 0$, then
$$ a^2x^2=x $$
$$ \frac{x^2}{x}=\frac{1}{a^2} $$
Thus, when $x\gt 0$ and $a\gt 0$, the functions $f(x)$ and $g(x)$ will intersect only when $$x=\frac{1}{a^2}$$ | In this case an algebraic proof is possible; but taking it from a more general point of view, we can consider the function
$$
F(x)=ax-\sqrt{x}
$$
defined for $x\ge0$; it's continuous and $\lim\_{x\to\infty}F(x)=\infty$, because
$$
\lim\_{x\to\infty}(ax-\sqrt{x})=
\lim\_{x\to\infty}x(a-1/\sqrt{x}).
$$
Moreover $F(0)=0$. The derivative is
$$
F'(x)=a-\frac{1}{2\sqrt{x}}=\frac{2a\sqrt{x}-1}{2\sqrt{x}}
$$
which is positive for $\sqrt{x}>1/(2a)$ and negative for $\sqrt{x}<1/(2a)$. Thus $1/(4a^2)$ is the point where $F$ has an absolute minimum.
Since
$$
F(1/(4a^2))=a\frac{1}{4a^2}-\frac{1}{2a}=-\frac{1}{4a}<0
$$
the function $F$ assumes the value zero in one and only one point $x\_0>1/(4a^2)$.
---
Just to make an example in which the technique above would be needed is when we consider
$$
f(x)=ax,\qquad g(x)=\log(1+x)
$$
in $[0,\infty)$ (again with $a>0$).
The situation is the same as above for $F(x)=f(x)-g(x)$ with respect to continuity and limits; also $f(0)=g(0)=0$. But now
$$
F'(x)=a-\frac{1}{1+x}
$$
and so a minimum is at $x=(1-a)/a$, provided $0<a<1$. If $a\ge1$, then $F'(x)>0$ for all $x>0$, so $F$ is increasing.
If $0<a<1$, the minimum is obviously negative (because $F(0)=0$), so there will be another root of $ax=\log(1+x)$ in the interval $((a-1)/a,\infty)$. |
11,934,171 | I'm using Rails 3. When a user submits a form with a text\_field and has & entered in it, the form gets validated. When it isn't valid, Rails returns an error, which I then show to the user. But now the & is translated to `&` . How can I change this behaviour? Thanks. | 2012/08/13 | [
"https://Stackoverflow.com/questions/11934171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401657/"
] | I found the culprit. I was sending my input to a sanitizer method, which replaced all ampersands by `&`. | Maybe try "risky string".html\_safe |
49,615,384 | Originally, I put all of my javascript in the head, but then I noticed that the page load time was very slow - not surprising. So, I moved all of my scripts to the bottom to eliminate the DOM render blocking effects.
On Google's PageInsights page, they say that's no longer the best practice and they recommend putting the scripts in the head and adding async loading
<https://developers.google.com/speed/docs/insights/BlockingJS>
The problem I ran into with that and from my understanding is if you use async, then the script will execute as soon as it completes loading, so you can run into dependency issues - which is precisely what happened with jQuery and scripts that depended on it.
<https://calendar.perfplanet.com/2016/prefer-defer-over-async/>
I found out that there's the defer attribute which is like async but it postpones execution until loading. If that's the case, why am I still hitting these dependency errors?
It doesn't happen every time. It just so happens that sometimes the script(s) that depend on jQuery load quicker than jQuery itself, as shown below.
My question is, what should I do to make sure that everything loads asynchronously but doesn't execute until the completion of loading?
Hopefully, this is a simple fix without a ton of fancy javascript.
[](https://i.stack.imgur.com/PhFyL.png)
[](https://i.stack.imgur.com/MBq43.png) | 2018/04/02 | [
"https://Stackoverflow.com/questions/49615384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9269719/"
] | >
> Note that asynchronous scripts are not guaranteed to execute in specified order and should not use document.write. Scripts that depend on execution order or need to access or modify the DOM or CSSOM of the page may need to be rewritten to account for these constraints.
>
>
>
Simple suggestion: just place your scripts at the bottom, or only use the async tag unless they have no dependencies whatsoever.
Anything that depends on Jquery has a dependency on Jquery being executed (loaded) first.
Also best practice might be chunking a bundle file, micro-organizing the loading sequence, and using a CDN with a cache buster as needed (if you're not using versioning), but that sounds like over-optimization at this point.
Alternatively, if I'm looking at your code right, you need a defer on the `ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js` script line. | You are still downloading your jquery script with async, change it to also be defer.
*Some extra detail on async and defer that you might already know:*
async: downloads your script while browser is rendering, then stops the rendering once download of that one script is finished and executes it, then continues rendering.
defer: downloads your script while the browser is rendering, then wait till the DOM is finished rendering before executing your scripts in the correct order (ONLY if the also have a src attribute).
From [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script):
"**defer**
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.
To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document." |
39,982,373 | Does anybody know of any compatibility issues or quirks with MySQL Community Server/Workbench on macOS Sierra? I recently did an installation on a Mac that had never held MySQL before and it doesn't seem to be working correctly. (Now maybe I just set it up wrong, but the since the installer offers no advanced options that doesn't seem to be the case.)
I can create schemas and tables, but when I go to actually query the table nothing happens. The activity indicator spins endlessly. I took a look at Activity Monitor and it doesn't show `mysqld` actually doing anything—the whole setup just appears to be deadlocked. Any ideas?
Here's what I'm trying to use:
* MySQL Community Server 5.7.15
* MySQL Workbench 6.3.7
* macOS Sierra 10.12 (16A323) | 2016/10/11 | [
"https://Stackoverflow.com/questions/39982373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7002533/"
] | >
> **UPDATE!**
> -----------
>
>
> macOS High Sierra ***needs*** MySQL Workbench [6.3.10](https://dev.mysql.com/downloads/workbench/)
> --------------------------------------------------------------------------------------------------
>
>
> See [*changelog*](https://dev.mysql.com/doc/relnotes/workbench/en/wb-news-6-3-10.html) for 6.3.10 version
>
>
>
---
**SOLVED in version 6.3.9**
---------------------------
Tested on:
>
> macOS Sierra
>
> Version 10.12.3 (16D32)
>
>
>
MySQL
>
> Workbench 6.3.9
>
> Version 6.3.9 build 10690321 CE (64 bits) Community
>
> `----> OK`
>
>
>
Download: [MySQL Workbench 6.3.9](https://dev.mysql.com/downloads/workbench/)
Packages for Sierra (10.12) are compatible with El Capitan (10.11) and are Yosemite (10.10)
>
> [Changelog](https://dev.mysql.com/doc/relnotes/workbench/en/wb-news-6-3-9.html): *among others...*
>
>
> * In some cases, executing a query caused MySQL Workbench to become unresponsive when the host was macOS Sierra. (Bug #25036263, Bug #83658)
>
>
>
---
Original answer in code snippet below:
```html
I ***temporary*** solved changed the ***group*** of the application.
I tried everything, uninstalling, reinstall, change many settings... finally I thought that must be something with the security... was not normal, I check firewall rules, nothing... And just in case, I try with file permission and it was there.
I was installed in the ***admin group***.
Changed to ***staff*** solve the problem.
$ sudo chown <USER>:staff /Applications/MySQLWorkbench.app
> <sup>Where of course, `<USER>` is **your** username</sup>
Ex.
$ sudo chown gmo:staff /Applications/MySQLWorkbench.app
Tested and working!
- Go back to admin group... problem came back.
- Changed to staff again... problem solved.
I hope this is a global solution, please check yours.
###Edit:
Solution not stable, problem came back after a few attempts.
Try with `root:admin`, the same...
---
### UPDATE
*`Workaround until new version is release`*
Roll back to 6.2 version and working good.
Tested on:
> macOS Sierra
> Version 10.12 (16A323)
MySQL
> Workbench 6.3
> Version 6.3.7 build 1199 CE (64 bits) Community
> http://dev.mysql.com/downloads/workbench/6.3.html
> `----> FAILS`
> <sup>*Randomly, even changing group or creating new instances.*</sup>
> Workbench 6.2
> Version 6.2.5.0 build 397 (32 bits) Community
> http://dev.mysql.com/downloads/workbench/6.2.html
> `----> OK`
> <sup>*Work as expected.*</sup>
``` | I had same problem and I digged all internet but dont resolved problem and then I decided use another workbench. I found "DBeaver - Universal Database Manager" official site : <http://dbeaver.jkiss.org/> and free and its tolerable. |
23,539,184 | In Python, I start a new process via `Popen()`, which works fine. Now in the child process I want to find the parent's process ID.
What is the best way to achieve this, maybe I can pass the PID via the `Popen` constructor, but how? Or is there a better way to do so?
PS: If possible I would prefere a solution using only standard libraries. | 2014/05/08 | [
"https://Stackoverflow.com/questions/23539184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2729841/"
] | You can use [`os.getppid()`](https://docs.python.org/2/library/os.html#os.getppid):
>
> `os.getppid()`
>
>
>
> ```
> Return the parent’s process id.
>
> ```
>
>
Note: this works only on Unix, not on Windows. On Windows you can use [`os.getpid()`](https://docs.python.org/2/library/os.html#os.getpid) in the parent process and pass the pid as argument to the process you start with `Popen`.
Windows support for [`os.getppid`](https://docs.python.org/3/library/os.html#os.getppid) was added in Python 3.2. | Use `psutil` ([here](https://github.com/giampaolo/psutil))
```
import psutil, os
psutil.Process(os.getpid()).ppid()
```
works both for Unix & Windows (even if `os.getppid()` doesn't exist on this platform) |
204,196 | I used the following link (<https://webkul.com/blog/how-to-create-a-custom-button-on-record-page-in-lightning-experience/>) to create a Quick Action which opens a box.
I am trying to update the Lightning Component to actually open the Log a Call page.
I need the button to exist on the Contact record rather than the actual Activity component. I know in Classic you can create a custom button and place it on the Contact Page layout, how would you get it done in LEX? | 2018/01/10 | [
"https://salesforce.stackexchange.com/questions/204196",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/30602/"
] | If I understand you correctly - you want to open the `Log A Call` as a dialog - from an action button.
Although you can add a custom Quick action and set it's type as `Log A Call`:
[](https://i.stack.imgur.com/XTuqA.png)
But if you do that - the `Log A Call` opens in the `Activity` panel always, and not as a button on the action buttons:
[](https://i.stack.imgur.com/0Im6o.png)
So actual answer to your question: **today this cannot be done.**
**WORKAROUND**
You can of course develop your own lightning component and do the Log A Call functionality over there, then if you add this lightning component as a quick action - it will display as a button and will open as a modal. | There is a log a call action specific to the Contact page you are on. Screenshot below demonstrate that
[](https://i.stack.imgur.com/A6Z3X.png)
Since, [`Call Logging`](https://help.salesforce.com/articleView?id=activitytimeline_configure_call_task_event_tabs.htm&type=5) is part Lightning Experience activities, therefore, even if you add custom quick action with the action type as **Call a Log** that action will be added to the activity composer (Activity panel). |
520,160 | In this image taken from the [manual](http://nadascientific.com/pub/media/PDF/Catalog/N99-B10-7355_Manual.pdf) of the NaRiKa/Nada Scientific EM-4N e/m apparatus, you can see that the positively-charged electrode (the one electrons are attracted to) is labeled "anode."
[](https://i.stack.imgur.com/p3naT.jpg)
This leads to some student confusion, because they are used to the anode of the battery being the negative terminal.
Some cursory research (for example [this chemistry stack exchange question](https://chemistry.stackexchange.com/questions/68533/which-is-anode-and-which-is-cathode)) makes it clear that this is a complicated issue. It appears that fundamentally (at least in chemistry), the question of which terminal is labeled "anode" has to do with where oxidation occurs. But in this case, we don't have an electrolytic *or* galvanic cell... just a 200-500V DC power supply. So why is the positive terminal the anode here?
I have found some conflicting info:
* "The anode is the positively charged electrode; The anode attracts electrons or anions" ([source](https://www.thoughtco.com/how-to-define-anode-and-cathode-606452))
* "the anode is the source of electrons to the external circuit and the cathode is the sink." ([source](https://chemistry.stackexchange.com/questions/68533/which-is-anode-and-which-is-cathode))
Can anyone provide an explanation suitable for intermediate level physics undergrads that explains why the anode is positive in this case? | 2019/12/17 | [
"https://physics.stackexchange.com/questions/520160",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/155821/"
] | This is a volume obtained by revolving $z= f(\sqrt{x^2+y^2}) = f(r) $ around z-axis. The x coordinate of the center of mass is given by
$$ { \bar x } =\dfrac{\int\int \int(\rho\cdot r\sin \theta\, r\, d\theta \,dr\, dz)}{\int\int\int(\rho\, r\, d\theta \,dr\, dz)} $$
The numerator can be expressed as
$$ {\int\_0^{2 \pi} (\sin \theta \,d\theta) \cdot \int \int(\rho \,r^2 \,dr\, dz)}$$
which vanishes.
Similarly for the y-coordinate the ${\bar y }$ center of mass is zero, $\bar z$ is non-zero, so CM lies on z-axis. | I will only show the case for center of mass because the case for moment of inertia is analogous. We have for the $x$ component of the center of mass:
$$ x\_\text{com} = \frac 1M \int \rho(x,y,z) \cdot x\, \mathrm d^3 x$$
for simplicity I'm going to take $M=1$ in some units as the mass will not play a role in the argument.
Now do a change of coordinates $x \to \tilde x = -x$ and $\tilde y = -y$, $\tilde z = z$ i.e. a reflection along $z$ axis. Then the absolute value of the Jacobian determinant is $1$ and we have $\, \mathrm d^3 x = \, \mathrm d^3 \tilde x$.
$$ \begin{align}\implies x\_\text{com}&= \int \rho(x,y,z) \cdot x\, \mathrm d^3 x= \int \rho(\tilde x, \tilde y,\tilde z) \cdot \tilde x\, \mathrm d^3 \tilde x \\
&= \int \rho(- x, -y, z) \cdot (-x)\, \mathrm d^3 x \\
&=\int \rho(x, y, z) \cdot (-x)\, \mathrm d^3 x = - x\_\text{com}
\end{align}$$
Since $x\_\text{com} = - x\_\text{com}$ we conculude $x\_\text{com}=0$. |
67,468,510 | I have Eclipse recently installed and the version is
Eclipse IDE for Enterprise Java and Web Developers (includes Incubating components)
Version: 2021-03 (4.19.0)
Build id: 20210312-0638
OS: Windows 10, v.10.0, x86\_64 / win32
Java version: 16
Windows Builder is also installed version 1.9.5 and updated
I created new Java Project and for example name it Employee. On Employee I click right click and go to the bottom where I pick other and scroll down to Window Builder and pick Swing Designer- Application window.
Source code in new created java file is ok. Everything is as it should be but when I click on Design tab all windows are blank (Structure, Pallette, Properties) and cannot build anything. As I can see while googleing many people have this problems and there was no idea how to fix it.
I tried reinstalling eclipse and window builder but no luck.
[](https://i.stack.imgur.com/zLBMJ.jpg)
[](https://i.stack.imgur.com/FoPIC.jpg)
[](https://i.stack.imgur.com/GzMuA.jpg) | 2021/05/10 | [
"https://Stackoverflow.com/questions/67468510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15785120/"
] | For anyone looking for answer I just realized how to fix this. Go to window builder site and install version 1.9.4.
When opening new project please open in Java 11 only. Will not work in newest jdk
So project in jdk 11 and only 1.9.4 window builder version | version 1.9.5 has completely removed from <https://www.eclipse.org/windowbuilder/download.php>.
Downloaded and installed the latest version **Current(1.9.7)**.
Worked for me. |
68,506,567 | In [bootstrap-vue](https://bootstrap-vue.org/docs/components/pagination#pagination) pagination there is no slot for change main color of pagination.
[](https://i.stack.imgur.com/s0APj.png)
you see there is only blue color for it.
is there any way to change it to my required color? | 2021/07/24 | [
"https://Stackoverflow.com/questions/68506567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7693832/"
] | When you do a bitwise operation on Series objects or arrays, you get an array of booleans, each of whose elements is True or False. Those are basically 0 or 1, and in fact more convenient in most cases:
```
df['col6'] = (df['col4'] > 1) & (df['col5'] > 1)
df['col7'] = df['col6']
```
That last one is not a clever trick. If two numbers are both >1, then of course their sum must be >2. If you absolutely want the integers 0 and 1 instead of booleans, use `Series.astype`:
```
df['col6'] = ((df['col4'] > 1) & (df['col5'] > 1)).astype(int)
``` | try:
```
c1=df['col4'].gt(1) & df['col5'].gt(1)
#your 1st condition
c2=c1 & df['col4'].add(df['col5']).gt(2)
#your 2nd condition
```
Finally:
```
df['col6']=c1.astype(int)
df['col7']=c2.astype(int)
```
OR
via numpy's `where()` method:
```
c1=df['col4'].gt(1) & df['col5'].gt(1)
c2=c1 & df['col4'].add(df['col5']).gt(2)
df['col6']=np.where(c1,1,0)
df['col7']=np.where(c2,1,0)
``` |
243,031 | I have read somewhere that the gate capacitance (Cgs, Cgd) of a MOSFET is calculated as below:
*Strong inversion:*
>
> Cgs=(2/3)Cox.W.L + Cov
>
>
>
*Non-saturated:*
>
> Cgs=Cgd=(1/2)Cox.W.L + Cov
>
>
>
where Cov is overlap capacitance.
Could anyone explain where the formulas come from? | 2016/06/27 | [
"https://electronics.stackexchange.com/questions/243031",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/91853/"
] | Reading in the tea leaves here, I'd surmise that for the case of:
>
> your equation 2)\$C\_{gs}=C\_{gd}=\frac{1}{2}C\_{ox}WL + C\_{ov}\$
>
>
>
They are taking the gate to channel capacitance and dividing equally between the S & D.
In the case of:
>
> your equation 1)\$C\_{gs}=\frac{2}{3}C\_{ox}WL + C\_{ov}\$
>
>
>
It looks like they are lumping the pinched off part of the channel which is attached to the source.
In your equation #2, while this is not strictly wrong, it is the wrong way to look at it. It would be best to think in terms of gate to channel.
In your equation #1, that might only hold true in one particular channel condition. Once the channel pinches off the drain doesn't under go massive capacitance changes.
I'd be suspicious.
From the book "Operation and modelling of the MOS transistor" by Yannis Tsividis (recommended reading !!) the following equations from section 8.3.2 (page 391 in the 2nd edition). For strong inversion:
$$ C\_{gs} = C\_{ox} \dfrac{2(1+2\eta)}{3(1+\eta)^2} $$
$$ C\_{gd} = C\_{ox} \dfrac{2(\eta^2 + 2\eta)}{3(1+\eta)^2} $$
\$ \eta = \$ degree of non-saturation. With \$ \eta = 1\$ at \$V\_{ds}=0\$.
So in the case with the channel fully pinched off \$ \eta = 0\$. We get the case of your equation #1. | This might help you out.
[](https://i.stack.imgur.com/FpEeX.png)
**Reference:**
B. Razavi, *Design of Analog CMOS Integrated Circuits*, McGraw-Hill, Boston, 2001 |
67,712,252 | My data is dataset diamond:
```
+-----+-------+-----+-------+-----+-----+-----+----+----+----+
|carat| cut|color|clarity|depth|table|price| x| y| z|
+-----+-------+-----+-------+-----+-----+-----+----+----+----+
| 0.23| Ideal| E| SI2| 61.5| 55.0| 326|3.95|3.98|2.43|
| 0.21|Premium| E| SI1| 59.8| 61.0| 326|3.89|3.84|2.31|
| 0.23| Good| E| VS1| 56.9| 65.0| 327|4.05|4.07|2.31|
| 0.29|Premium| I| VS2| 62.4| 58.0| 334| 4.2|4.23|2.63|
| 0.31| Good| J| SI2| 63.3| 58.0| 335|4.34|4.35|2.75|
```
I am trying to use a loop to count the number of diamonds in each of the following ranges:
[0,1) [1, 2) [2, 3) [3, 4) [4, 5) [5, 6) without pandas. So using filter() and count() I need to determine desired counts and return message:
```
The number of diamonds with carat size in range [0, 1) is xxxx.
```
My code far now is :
```
for x in diamonds['carat'] :
int1 = filter(lambda x: x>=0 and x<1, x).count()
int2 = filter(lambda x: x>=1 and x<2, x).count()
int3 = filter(lambda x: x>=2 and x<3, x).count()
int4 = filter(lambda x: x>=3 and x<4, x).count()
int5 = filter(lambda x: x>=4 and x<5, x).count()
int6 = filter(lambda x: x>=5 and x<6, x).count()
print('The number of diamonds with carat size in range [0, 1) is' int1)
```
but I get message:
AttributeError: 'GroupedData' object has no attribute 'filter'
The result I need is something like:
```
Intervals Count
(0 1) 30
......
```
by using only loop filter and count and not importing sql or panda
Any ideas? | 2021/05/26 | [
"https://Stackoverflow.com/questions/67712252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1997567/"
] | I would not recommend generating the attributes independently from each other (Green Cloak Guy has provided an instructive answer on how this can be done better).
That said, if for some reason you want to do it nonetheless, you can distribute the differences across the attributes as follows:
```
import random
strength = random.randint(1, 10)
perception = random.randint(1, 10)
endurance = random.randint(1, 10)
charisma = random.randint(1, 10)
intelligence = random.randint(1, 10)
agility = random.randint(1, 10)
luck = random.randint(1, 10)
list_attributes = [strength, perception, endurance, charisma, intelligence, agility, luck]
sum_attributes = sum(list_attributes)
diff = 40 - sum_attributes
if diff != 0:
diff_partial = diff/len(list_attributes)
for i, attribute in enumerate(list_attributes):
list_attributes[i] = attribute + diff_partial
strength, perception, endurance, charisma, intelligence, agility, luck = list_attributes
```
Keep in mind that, since `random` returns `float` values, your updated attributes will be `float`s as well. In case you need them as `int`, you could, for example, use `int()` inside the `for` loop. | I would just generate the seven stats, and depending on the sum total, add or subtract randomly until the sum equals 40...
```
import random
stats = []
## Generate the stats
for x in range(7):
stats.append(random.randint(1,10))
## If the sum total is 40, leave em.
if sum(stats) == 40:
pass
## If it is less than 40, add +1's randomly until you reach 40.
elif sum(stats) < 40:
while sum(stats) != 40:
stat = random.randint(0,6)
if stats[stat] != 10:
stats[stat] = stats[stat] + 1
## If it is more than 40, subtract randomly until you reach 40.
elif sum(stats) > 40:
while sum(stats) != 40:
stat = random.randint(0,6)
if stats[stat] != 1:
stats[stat] = stats[stat] - 1
strength = stats[0]
perception = stats[1]
endurance = stats[2]
charisma = stats[3]
intelligence = stats[4]
agility = stats[5]
luck = stats[6]
``` |
23,040,120 | i have a java multi-threaded program that is running. i am running it on a tomcat server. when the threads are still running, some executing tasks, some still waiting for some thing to return and all kinds of things, assume i stop the server all of a sudden in this scenario.. when i do i get a warning on the tomcat terminal saying a thread named x is still running and the server is being stopped so this might lead to a memory leakage. what is the OS actually trying to tell me here? can someone help me understand this?? i am running this program on my system several times and i have stopped the server abruptly 3 times and i have seen this message when ever i do that. have i runined my server? (i mean my system). did i do something very dangerous????
please help.
Thanks in advance! | 2014/04/13 | [
"https://Stackoverflow.com/questions/23040120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781031/"
] | >
> when i do i get a warning on the tomcat terminal saying a thread named x is still running and the server is being stopped so this might lead to a memory leakage. what is the OS actually trying to tell me here?
>
>
>
Tomcat (not the OS) is surmising from this extra thread that some part of your code forked a thread that may not be properly cleaning itself up. It is thinking that maybe this thread is forked more than once and if your process runs for a long time, it could fill up usable memory which would cause the JVM to lock up or at least get very slow.
>
> have i ruined my server? (i mean my system). did i do something very dangerous????
>
>
>
No, no. This is about the tomcat process itself. It is worried that this memory leak may stop its ability to do its job as software -- nothing more. Unless you see more than one thread or until you see memory problems with your server (use jconsole for this) then I would only take it as a warning and a caution. | It sounds like your web server is forking processes which are not terminated when you stop the server. Those could lead to a memory leak because they represent processes that will never die unless you reboot or manually terminate them with the `kill` command.
I doubt that you will permanently damage your system, unless those orphaned processes are doing something bad, but that would be unrelated to you stopping the server. You should probably do something like `ps aux | grep tomcat` to find the leftover processes and do the following
1. Kill them so they don't take up more system resoures.
2. Figure out why they are persisting when the server is stopped. This sounds like a misbehaving server. |
149,396 | I was reading the [XML Encryption standard](https://www.w3.org/TR/xmlenc-core/#sec-EncryptedKey) and I have some trouble understanding the purpose of encrypting some plain text with a symmetric generated AES or 3DES key that in turn gets encrypted with the public RSA key of the recipient.
If an attacker gets the private key of the recipient and has the network traffic recorded then he or she can decrypt the AES key and then the plaintext encrypted with the AES key. In TLS or in Signal the symmetric key gets negotiated with DH and does not travel encrypted over the wire giving the connection forward secrecy.
Why should I encrypt the symmetric key with the asymmetric one? Does increase confidentiality or performance? When should I use this double encryption?
Thank you | 2017/01/25 | [
"https://security.stackexchange.com/questions/149396",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/45141/"
] | >
> Why should I encrypt the symmetric key with the asymmetric one? Does increase confidentiality or performance? When should I use this double encryption?
>
>
>
You need to do the symmetric encryption because the [maximum size of data RSA can encrypt](https://stackoverflow.com/questions/5583379/what-is-the-limit-to-the-amount-of-data-that-can-be-encrypted-with-rsa) is restricted by the size of its modulus minus some padding. For example a 1024-bit RSA key can only encrypt data that is at most 117-bytes long. Anything larger than that, you would have needed to split the data into modulus-sized blocks (which also open up a number of other cryptographic issues) or use even larger key (and RSA gets slow very quickly as the key size increases).
Diffie Hellman is a **key agreement** protocol, it can only work if both side are connected to each other to exchange some data when the document is being encrypted. The use case in document encryption system like XML Encryption is usually that you are creating a document which can be stored and read at a later date by the recipient, and either side may never be online at the same time when generating/reading the document. This is also why Forward Secrecy is irrelevant for document encryption, as you generally want to be able to read the document later, you can't just discard the session key like you would in ephemeral encryption system like TLS. You have to save the session key with the document somewhere so you can read the document later.
If you want PFS, then I'd suggest transferring your encrypted document over TLS/HTTPS, and if you no longer need the document, just delete the document or at least the encrypted part of the document. | The main idea behind this double encryption is to allow deciphering of the content by many people while controlling who can decipher the content. If you send the symmetric key, anyone with the key will be able to read the final content.
If you send an encrypted key, which only the recipient can decipher, then the key is only available in clear with he private key.
This is less content to crypt than encrypting the plaintext with the public key for each recipient.
If you would avoid the symmetric key you'll have to encrypt the content for each recipient with their public key, this means you need to store the content in plaintext somewhere, having it encrypted with a symmetric key prevent leakage at source while keeping the storage overhead for multiple recipient low.
Of course that doesn't prevent the problem if the attacker get the recipient private key, the extra security comes from storing the content in a non readable form at source.
In brief: the goal is not so to prevent attack on the key, but on the source document itself. |
40,662 | I’m reading *Alice in Wonderland*, and found the following dialogue:
>
> “The master was an old Turtle — we used to call him Tortoise—”
>
>
> “Why did you call him Tortoise, if he wasn’t one?” Alice asked.
>
>
> “We called him a Tortoise because he taught us.”
>
>
>
What is the relationship between “he taught us” and “Tortoise”? Is this some kind of pun or joke? | 2011/09/05 | [
"https://english.stackexchange.com/questions/40662",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/11894/"
] | This is a pun that needs to be understood in its context. Although he was a Turtle, [his pupils called him a Tortoise, because:](http://books.google.com/books?id=ID5P7xbmcO8C&printsec=frontcover&dq=alice+in+wonderland&hl=en&ei=NllkTpnNFoj5mAXysNC6Cg&sa=X&oi=book_result&ct=result&resnum=1&ved=0CCsQ6AEwAA#v=onepage&q=tortoise&f=false)
>
> 'We called him a Tortoise because he taught us!' said the Mock Turtle angrily: 'really you are....'
>
>
>
It's a pun by Caroll.
It seems that Americans don't get this pun, because the American pronunciation of "tortoise" differs from the English pronunciation. Because Carroll was an Englishman and was writing to a British audience, it would have made sense to them.
In British English, "tortoise" is pronounced nearly exactly the same as "taught us", and that's why the students called the Turtle a "tortoise", even if he wasn't. | >
> What is the relationship between "he taught us" and "Tortoise"?
>
>
>
It has to do with the pronunciation of the *au* and *or* sounds. The literally English pronunciation (the pronunciation in the English used in England) of the letter r, is not normally rhotic. If you learn of the non-rhotic pronunciation of the sound *or* and compare it with the English pronunciation of the *au* sound, you will understand. This makes the sounds of these two sounds, the same.
Therefore, the word taught and the "tort" part of the word tortoise, are pronounced the same. A lot of English (and other British) pronunciation is not rhotic.
Edit:
There is another point worth making, in relation to this. Even though the word taught and the "tort" part of the word tortoise rhyme, the words "taught us" and "tortoise" do not always rhyme in British English pronunciation.
There are people who pronounce them exactly the same. There are also people who pronounce tortoise as "tor-tos"; with a non-rhotic r and the *os* sound involving another, common pronunciation of the letter o; as it is in the British pronunciation of the words dog and copper. This, particular pronunciation of the letter o is in the English of England but, not in the English of North America (American English and Canadian English). |
72,938,062 | I am trying to recreate the snake game, however when I call the function which is supposed to create the initial body of the snake nothing appears on the screen.
The same problem happens if I simply create a turtle object in the main file.
Snake:
```
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
def create_snake (self):
for position in STARTING_POSITIONS:
n_segment = Turtle("square")
n_segment.color("white")
n_segment.penup()
print(position)
n_segment.goto(position)
self.segments.append(n_segment)
```
Main:
```
from turtle import Turtle, Screen
from snake import Snake
screen = Screen()
screen.setup(width = 600 , height= 600)
screen.bgcolor("black")
screen.title("SNAKE")
screen.tracer(0)
game_on = True
segments = []
snake = Snake()
turtle = Turtle()
``` | 2022/07/11 | [
"https://Stackoverflow.com/questions/72938062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19186838/"
] | You can actually use `|` for Python 3.9+ to combine all the dictionaries then send unpacked version.
```py
def fun(**kwargs):
print(kwargs)
>>> fun(**a_F| b_100| hello| bye)
{'API parameter a': False, 'API parameter b': 100, 'API parameter c': 'hello', 'API parameter d': 'goodbye'}
```
Or just use `*args` and pass multiple dictionaries:
```py
def fun(*args):
print(args)
>>> fun(a_F,b_100,hello,bye)
({'API parameter a': False}, {'API parameter b': 100}, {'API parameter c': 'hello'}, {'API parameter d': 'goodbye'})
```
Another solution is to use Python decorator and take care of ugly part inside the decorator function:
```py
def decorator(fun):
def wrapper(*args):
from functools import reduce
kwargs = reduce(lambda a, b: a | b, args)
return fun(**kwargs)
return wrapper
@decorator
def main_fun(**kwargs):
print(kwargs)
>>> main_fun(a_F,b_100,hello,z)
{'API parameter a': False, 'API parameter b': 100, 'API parameter c': 'hello', 'parameter 4': 'goodbye'}
``` | To unpack a series of dicts, use `dict.update`, or a nested comprehension:
```
def myf(*dicts):
merged = {k: v for d in dicts for k, v in d.items()}
# do stuff to merged
```
OR
```
def myf(*dicts):
merged = {}
for d in dicts:
merged.update(d)
``` |
63,239,291 | I have some D3 code that works fine. It includes a call like this to fill an area with grey:
```
...
.attr("fill", "rgba(0,0,0,.18)")
...
```
However, if I change that line to the following (where fillSmoke() returns the same string `"rgba(0,0,0,.18)"`), the chart is filled with black, not the desired grey.
```
.attr("fill", function(d, i) {fillSmoke(d,i)})
... and later ...
fillSmoke = (d, i) => {
return "rgba(0,0,0,0.18)"
}
```
I have a sense that D3 must be parsing `"rgba(0,0,0,.18)"` in the first case, but not the second. What can I do to return the desired grey value from fillSmoke()? Thanks.
**Solution:** Change the function body to include `return` (e.g., `{return fillSmoke(d,i)}` Thanks! | 2020/08/04 | [
"https://Stackoverflow.com/questions/63239291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827982/"
] | The second parameter of the `.attr` method can be a function, but it must return the color value you want to use. Right now your function just calls fillSmoke, but returns no value. Fix this by changing the line to:
```
.attr("fill", function(d, i) { return fillSmoke(d,i); })
```
The return statement is needed to return the value -- this works so long as fillSmoke is returning the color value you want. Alternatively, this may work too:
```
.attr("fill", fillSmoke)
```
See [more](https://www.d3indepth.com/datajoins) | This was a silly mistake - the function should have been defined to *return* the fillSmoke() results, like this:
`function(d, i) {return fillSmoke(d,i)}`
Thanks, all. |
1,197,444 | I have tried to do this in many different ways but the most obvious was this:
```
var map2 = new GMap2(document.getElementById("map2"), {size:"100%"});
```
That does not work. | 2009/07/29 | [
"https://Stackoverflow.com/questions/1197444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146758/"
] | Just specifying width:100%; height:100% wasn't enough for me...
But I got it working by using the following BODY code:
```
<body onload="initialize()" style="margin:0px; padding:0px;">
```
And using the following map code:
```
<div id="map" style="width: 100%; height: 100%; position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
```
See the result at <http://arve.epfl.ch/test/>
/shawn | ```
<div class="some-pannel">
<div class="map-wrapper">
<div id="googleMap" style="width:100%;height:100%;"></div>
</div>
</div>
.some-pannel{
position: relative;
width: 123px;
height 321px;
}
.map-wrapper{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
``` |
29,715,598 | because a provider I use, has a quite unreliable MySQL servers, which are down at leas 1 time pr week :-/ impacting one of the sites I made, I want to prevent its outeges in the following way:
* dump the MySQL table to a file In case the connection with the SQL
server is failed,
* then read the file instead of the Server, till the Server is back.
This will avoid outages from the user experience point of view.
In fact things are not so easy like it seems and I ask for your help please.
What I did is to save the data to a JSON file format.
But this got issues because many data on the DB are "in clear" included escaped complex URLs, with long argument's line, that give some issue during the decode process from JSON.
On CSV and TSV is also not workign correctly.
CSV is delimited by Commas or Semilcolon , and those are present in the original content taken from the DB.
TSV format leave double quotes that are not deletable, without avoid to go to eliminate them into the record's fields
Then I tried to serialize each record read from the DB, store it and retrive it serializing it.
But the result is a bit catastrophic, becase all the records are stored in the file.
When I retrieve them, only one is returned. then there is something that blocks the functioning of the program (here below the code please)
```
require_once('variables.php');
require_once("database.php");
$file = "database.dmp";
$myfile = fopen($file, "w") or die("Unable to open file!");
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
fwrite($myfile, serialize($row));
}
fclose($myfile);
mysql_close();
// Retrieving section
$myfile = fopen($file, "r") or die("Unable to open file!");
// Till the file is not ended, continue to check it
while ( !feof($myfile) ) {
$record = fgets($myfile); // get the record
$row = unserialize($record); // unserialize it
print_r($row); // show if the variable has something on it
}
fclose($myfile);
```
I tried also to uuencode and also with base64\_encode but they were worse choices.
Is there any way to achieve my goal?
Thank you very much in advance for your help | 2015/04/18 | [
"https://Stackoverflow.com/questions/29715598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2942741/"
] | If you have your data layer well decoupled you can consider using SQLite as a fallback storage.
It's just a matter of adding one abstraction more, with the same code accessing the storage and changing the storage target in case of unavailability of the primary one.
-----EDIT-----
You could also try to think about some caching (json/html file?!) strategy returning stale data in case of mysql outage.
-----EDIT 2-----
If it's not too much effort, please consider playing with [PDO](http://php.net/manual/en/class.pdo.php), I'm quite sure you'll never look back and believe me this will help you structuring your db calls with little pain when switching between storages.
>
> Please take the following only as an example, there are much better
> way to design this architectural part of code.
>
>
>
Just a small and basic code to demonstrate you what I mean:
```
class StoragePersister
{
private $driver = 'mysql';
public function setDriver($driver)
{
$this->driver = $driver;
}
public function persist($data)
{
switch ($this->driver)
{
case 'mysql':
$this->persistToMysql($data);
case 'sqlite':
$this->persistToSqlite($data);
}
}
public function persistToMysql($data)
{
//query to mysql
}
public function persistSqlite($data)
{
//query to Sqlite
}
}
$storage = new StoragePersister;
$storage->setDriver('sqlite'); //eventually to switch to sqlite
$storage->persist($somedata); // this will use the strategy to call the function based on the storage driver you've selected.
```
-----EDIT 3-----
please give a look at the "[strategy](http://www.phptherightway.com/pages/Design-Patterns.html)" design pattern section, I guess it can help to better understand what I mean. | Have you thought about caching your queries into a cache like APC ? Also, you may want to use `mysqli` or `pdo` instead of mysql (Mysql is deprecated in the latest versions of PHP).
To answer your question, this is one way of doing it.
* `var_export` will export the variable as valid PHP code
* `require` will put the content of the array into the $data variable (because of the `return` statement)
Here is the code :
```
$sql = mysql_query("SELECT * FROM song ORDER BY ID ASC");
$content = array();
// output data of each row
while ($row = mysql_fetch_assoc($sql)) {
// store the record into the file
$content[$row['ID']] = $row;
}
mysql_close();
$data = '<?php return ' . var_export($content, true) . ';';
file_put_contents($file, $data);
// Retrieving section
$rows = require $file;
``` |
29,454,849 | While using Rails 4.1 with Devise 3.3.0 I noticed the following:
When using routes.rb such as
```
devise_scope :user do
get '/login', :to => "devise/sessions#new"
get '/logout', :to => "devise/sessions#destroy"
get '/sign_up', :to => "devise/registrations#new"
end
```
And then on the view of one of these actions:
```
<%= render "devise/shared/links" %>
```
The href path to each generated links to the default Devise paths for each action,
such as /users/sign\_in instead of /login.
How can you override these default paths to ones you specify? | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373836/"
] | For those who are looking for a way to get timestamp, just do it:
>
> moment().[valueOf](https://momentjs.com/docs/#/parsing/utc/)()
>
>
> | You can directly call function **momentInstance.valueOf()**, it will return numeric value of time similar to **date.getTime()** in native java script. |
59,993,305 | Given an array of objects `arr1` how can I filter out to a new array the objects that do not have a property equal to any value in the array of numbers `arr2`
```
const arr1 = [
{
key: 1,
name: 'Al'
},
{
key: 2,
name: 'Lo'
},
{
key: 3,
name: 'Ye'
}
];
const arr2 = [2, 3]
// Failed attempt
const newArr = arr1.filter(obj1 => arr2.some(num1 => num1 !== obj1.key))
console.log(newArr)
// Expected: [{ key: 1, name: 'Al' }]
// Received: [
// { key: 1, name: 'Al' },
// { key: 2, name: 'Lo' },
// { key: 3, name: 'Ye' }
// ]
``` | 2020/01/30 | [
"https://Stackoverflow.com/questions/59993305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7435567/"
] | For situations like this Set is also very cool (and for big arrays more performant):
```
const arr1 = [
{
key: 1,
name: 'Al'
},
{
key: 2,
name: 'Lo'
},
{
key: 3,
name: 'Ye'
}
];
const arr2 = [2, 3]
const arr2Set = new Set(arr2);
const newArr = arr1.filter(obj1 => !arr2Set.has(obj1.key))
console.log(newArr)
``` | You can use `indexOf` like this:
```
const newArr = arr1.filter(obj => arr2.indexOf(obj.key) > -1);
``` |
102,267 | I'm migrating a WordPress site from one server to another, and the entire migration seems fine, except the sidebars aren't moving over properly. The obvious thing that comes to mind is a serialization issue with the MySQL migration, but I'm not making any changes to the database because the domain name isn't changing (or even the server paths for that matter). I'm literally just moving it from one box to another. | 2013/06/07 | [
"https://wordpress.stackexchange.com/questions/102267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10034/"
] | Really everything you need to know is in the docs. See [Moving WordPress « WordPress Codex.](http://codex.wordpress.org/Moving_WordPress)
They cover exporting/importing databases, moving uploads and other content, themes, etc.
For particular issues with moving WP installs, search this site; many have already been answered. | theres a nice plugin called "Duplicator" which does all the stuff for you.
<http://wordpress.org/plugins/duplicator/>
Theres also one called BackupBuddy but it's not free.
<http://ithemes.com/purchase/backupbuddy/> |
7,892,729 | I would have to display in my console log, the duration of each Hibernate query.
Is it possible ? | 2011/10/25 | [
"https://Stackoverflow.com/questions/7892729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284237/"
] | Take a look on this article. <http://www.basilv.com/psd/blog/2008/hibernate-and-logging>
It seems it describes exactly what you need. I hope it is still relevant fore newer versions of Hibernate since hibernate moved to SLF4J. In this case you should perform appropriate configuration of SLF4J instead of Log4j | [log4jdbc](http://code.google.com/p/log4jdbc/) and [log4jdbc-remix](http://code.google.com/p/log4jdbc-remix/) provide extensive logging for JDBC connections, statements, and result sets. These projects provide wrappers around your JDBC driver to do the logging. |
9,751 | I come from Christianity.SE, where I asked [almost the same question](https://christianity.stackexchange.com/q/1630/60). [Isaac Moses](https://judaism.stackexchange.com/users/2/isaac-moses) assured me that the question would not be disrespectful and could be asked here.
---
God's name is written as the Tetragrammaton יהוה (YHWH) in the Torah. The name is not vocalized in the manuscripts and I know it's considered ineffable by Jews and thus not said aloud. For that reason, the original pronunciation hasn't been preserved (as far as I know).
Christians commonly suggest the pronunciations *Yahweh* and *Jehovah* (which should of course be pronounced like "Yehovah"). Long ago I heard it claimed that the vocalization *Jehovah* is based on a misunderstanding, but I don't remember the reasoning.
What is the probable original vocalization? | 2011/09/02 | [
"https://judaism.stackexchange.com/questions/9751",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/853/"
] | In [this recent blog post](http://torahmusings.com/2011/09/jehovahs-witnesses/), Rabbi Ari Enkin paraphrases Israel Rubin in "The How & Why of Jewish Prayer" explaining that the correct pronunciation of the Tetragrammaton was lost during the Second Temple Period. | Once I read an article that suggested a word that sounded like it only consisted of vowels. I'm not familiar with the standard pronunciation notation, so I can only write it in "pseudo code" based on English: ee[eagle]-aa[artist]-uu[without first j sound]-ehh[enter].
Unfortunately I can't remember the author and the title of the article, so it is just a note, not a real answer. |
51,485,787 | I would like to add an ascending number to every 6th item of an array. So far I have this but at the moment it adds an ascending number to every line, not every 6th line. Can someone say how to fix that? Thanks
```
for(var i=0;i<newlist.length;i++){
newlist[i]=counter + "." + " " + newlist[i];
counter++;
}
``` | 2018/07/23 | [
"https://Stackoverflow.com/questions/51485787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228956/"
] | `i++` increments the index by one, `i += 6` increments the index by 6. | Arrays in javascript are 0 based so assuming that you want every 6th element to contain the prefix -
```
for(var i=0;i<newlist.length;i++) {
if ( (i+1) % 6 === 0) {
newlist[i] = ((i+1)/6) + "." + " " + newlist[i];
}
}
``` |
68,441,088 | I am building a personal website and I am getting an error whenever I click on the the redirect link and I am quite puzzled how to proceed.
I am also including my *url.py*, *views.py* and *navbar.html* files (HTML file where the redirect code is) code:
### File *views.py*
```
def product(request):
return render(request = request,
template_name = "main/categories.html",
context ={"categories": ItemCategory.objects.all})
def homepage(request):
return render(request = request,
template_name = "main/categories.html",
context ={"categories": ItemCategory.objects.all})
def about(request):
return render(request = request,
template_name = "main/about.html",
context ={"categories": ItemCategory.objects.all})
def contact(request):
return render(request = request,
template_name = "main/contact.html",
context ={"categories": ItemCategory.objects.all})
```
### File *url.py*
```
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
app_name = "main"
urlpatterns = [
path("", views.homepage, name="homepage"),
path("product/", views.product, name="product"),
path("about/", views.about, name="about"),
path("contact/", views.contact, name="contact"),
path("register/", views.register, name = "register"),
path("logout/", views.logout_request, name = "logout"),
path("login/", views.login_request, name = "login"),
path("<single_slug>", views.single_slug, name="single_slug"),
]
urlpatterns += staticfiles_urlpatterns()
```
### File *navbar.html*
```
<nav>
<div id="nav-wrapper">
<div>
<ul class="center hide-on-med-and-down">
<li>
<a href="{% url 'homepage' %}">Home</a>
</li>
<li>
<a href="about/">About Us</a>
</li>
<li>
<a href="product/">Products</a>
</li>
<li>
<a href="services/">Services</a>
</li>
<li>
<a href="contact/">Contact</a>
</li>
<li>
<a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a>
</li>
</ul>
</div>
</div>
</nav>
```
How can I fix it? | 2021/07/19 | [
"https://Stackoverflow.com/questions/68441088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13870072/"
] | Go to Firebase console, then navigate to the storage tab. You should see something like this:
[](https://i.stack.imgur.com/QNgkc.png)
Click "Configure App Check" and there will be a config page. Ensure that your Firebase Storage is not set to enforce app check.
Of course, the ideal option would be to set up [app check](https://firebase.google.com/docs/app-check). Invertase recently released this [plugin](https://pub.dev/packages/firebase_app_check) for setting it up with Flutter. You can check out the article [here](https://invertase.io/blog/flutterfire-news-google-io-2021#new-plugin-firebase-app-check). | In my case I solved the problem by using the await typecasting. You are not getting the error related to app check token request. You are getting the error for not waiting for the completion of download. Just add the line after await which is required for the UploadTask finished and it works.
```
final Reference storageReference = firebase_storage.FirebaseStorage.instance
.ref()
.child("products")
.child("product_$productId.png");
String downloadURL;
UploadTask uploadTask = storageReference.putFile(mFileImage);
downloadURL = await (await uploadTask).ref.getDownloadURL();
``` |
44,802,363 | I am currently overseas and I am trying to connect to my EC2 instance through ssh but I am getting the error `ssh: connect to host ec2-34-207-64-42.compute-1.amazonaws.com port 22: Connection refused`
I turned on my vpn to New York but still nothing changes. What reasons could there be for not being able to connect to this instance?
The instance is still running and serving the website but I am not able to connect through ssh. Is this a problem with the wifi where I am staying or with the instance itself? | 2017/06/28 | [
"https://Stackoverflow.com/questions/44802363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1851782/"
] | My debugging steps to EC2 connection time out
1. Double check the security group access for port 22
2. Make sure you have your current IP on there and update to be sure it hasn't changed
3. Make sure the key pair you're attempting to use corresponds to the one attached to your EC2
4. Make sure your key pair on your local machine is chmod'ed correctly. I believe it's `chmod 600 keypair.pem` [check this](https://stackoverflow.com/questions/1454629/aws-ssh-access-permission-denied-publickey-issue)
5. Make sure you're in either your .ssh folder on your host OR correctly referencing it: `HOME/.ssh/key.pem`
6. Last weird totally wishy washy checks:
* reboot instance
* assign elastic IP and access that
* switch from using the IP to Public DNS
* add a `:` at the end of user@ip`:`
Totally mystical debugging sets for 6 though. That's part of the "my code doesn't work - don't know why. My code does work - don't know why." Category
**Note:**
If you access your EC2 while you are connected to a VPN, do know that your IP changes! So enable incoming traffic from your VPN's IP on your EC2 security group. | 1. In AWS, navigate to Services > EC2.
2. Under Resources, select Running Instances.
3. Highlight your instance and click Connect.
4. In Terminal, `cd` into the directory containing your key and copy the command in step 3 under "To access your instance."
5. In Terminal, run: `ssh -vvv -i [MyEC2Key].pem ec2-user@xx.xx.xx.xx`(xx.xx.xx.xx = your EC2 Public IP) OR run the command in the example under step 4. |
6,189,708 | I come from C++ and normally `this` is rarely used compared to C#. In my experience, the usage of `this` is strictly limited to scope and/or name resolution.
I have coworkers that insist that using `this` everywhere makes code "more clear". They essentially depend on it for documentation purposes. I disagree with this usage as it is very subjective, redundant, and practically useless as far as documentation is concerned.
There are cases where I see `this.myClassVariable = 100;`. In this case, `this` serves no real use other than (according to my coworkers) to make it very clear that `myClassVariable` is not a static. This is just one example.
Personally, where ever there are no ambiguities, I use `myClassVariable = 100;`. This is more clear and I feel honestly that if your variables are well named, code will be self documenting and 'this' is not needed.
What is the general rule of thumb on using 'this'? I'm asking for use cases that go beyond the obvious requirements (such as resolving ambiguities). There are cases where the usage of `this` is required for code to compile and I'm not necessarily interested in those cases. How do you guys feel about using `this` for documentation? | 2011/05/31 | [
"https://Stackoverflow.com/questions/6189708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157971/"
] | Check here if you are working on emulator: [essentials for creating system apk](https://stackoverflow.com/questions/25532260/building-an-android-apk-with-same-certificate-as-the-system/32135870#32135870)
If you are working on a real device:
1. What you need is the vendor signature that's used to sign all the
modified Android system inside the device.
2. You won't have any system signature of any producer unless they
publish it.
3. So, you will not get the signature or the platform files unless you
have the **vendor/security** folder of the rom inside the device.
You should go for rooting method after your application is ready to be installed.
* Root your phone
* Open a terminal on your pc, go to **platform-tools** folder and start adb executable
* `adb push /path/to/your/apk/your_apk.apk /sdcard/Download`
* Go into adb shell
* `su`
* `mount -o remount,rw /system`
* `cp /sdcard/Download/your_apk.apk /system/app`
* `chmod 666 /system/app/your_apk.apk`
* Reboot your phone
You will have an application which is working with system permissions after rebooting.
**EDIT:** *Not sure if it works for 5.0 +, used to work for 5.0 and lower.* | Building a APK that should be signed with the platform key
```
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Build all java files in the java subdirectory
LOCAL_SRC_FILES := $(call all-subdir-java-files)
# Name of the APK to build
LOCAL_PACKAGE_NAME := LocalPackage
LOCAL_CERTIFICATE := platform
# Tell it to build an APK
include $(BUILD_PACKAGE)
``` |
63,459,377 | I am extremely confused on how to access this data, and get it into MySQL
I have this JSON Data:
```
{
"serial_number": "70-b3-d5-1a-00-be",
"dateTime": "2020-08-14 20:58",
"passReport": [
{
"id": 1,
"passList": [
{
"passType": 1,
"time": "20:58:38"
}
]
}
]
}
```
I can get **serial\_number** & **dateTime** perfectly fine, however I cannot get **passType** & **time** into my database
Here is my code for injesting:
```
//read the json file contents
$jsondata = file_get_contents('php://input');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//mySQL creds & mySQL database & tables
$servername = "localhost";
$username = "my user";
$password = "my pass";
$dbname = "my db";
$serial_number = $data['serial_number'];
$dateTime = $data['dateTime'];
$id = $data['id'];
$passType = $data['passType'];
$time = $data['time'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Insert into Database Tables
$sql = "INSERT INTO mytable (serial_number, dateTime, passType, time)
VALUES('$serial_number', '$dateTime', '$passType', '$time')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
```
I am pretty noobish at PHP, trying to learn! Appreciate any help here. I don't enough knowledge of accessing the data in the array.. Thanks in advance! | 2020/08/17 | [
"https://Stackoverflow.com/questions/63459377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12481660/"
] | Tested your code with just Image("some\_image") as below and it works (Xcode 12 / iOS 14), so the issue is either in `AnimatedImage` or in some other code.
```
VStack{
Image("some_image")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: UIScreen.main.bounds.width - 40)
}
.padding(.horizontal, 20)
.frame(width: UIScreen.main.bounds.width - 40)
``` | I think this change will help you:
```
VStack {
AnimatedImage(url: URL(string: self.mediaLink))
.resizable()
.scaledToFit()
}
.frame(width: UIScreen.main.bounds.width - 40)
``` |
7,057,080 | I'm aware a single workflow instance run in a single thread at a time. I've a workflow with two receive activities inside a pick activity. Message correlation is implemented to make sure the requests to both the activities should be routed to the same instance.
In the first receive branch I've a parallel activity with a delay activity in one branch. The parallel activity will complete either the delay is over or a flag is set to true.
When the parallel activity is waiting for the condition to meet how I can receive calls from the second receive activity? because the flag will be set to true only through through it's branch. I'm waiting for your suggestions or ideas. | 2011/08/14 | [
"https://Stackoverflow.com/questions/7057080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741616/"
] | [ImageMagick](http://www.imagemagick.org/) can construct [animations](http://www.imagemagick.org/Usage/anim_basics/) by assembling several bitmaps into one:
```
convert -delay 100 \
-page first.gif \
-page second.gif \
-page third.gif \
-loop 0 animation.gif
``` | It is also possible to generate animated gifs with [Gimp](http://www.gimp.org/) if you prefer a GUI tool. Plenty of how-to's if you [google it](http://www.google.com/search?rlz=1C1GGGE_elGR409GR415&sourceid=chrome&ie=UTF-8&q=create%20animated%20gif%20with%20gimp#sclient=psy&hl=el&rlz=1C1GGGE_elGR409GR415&source=hp&q=create%20animated%20gif%20with%20gimp&pbx=1&oq=create%20animated%20gif%20with%20gimp&aq=f&aqi=&aql=&gs_sm=s&gs_upl=0l0l0l2719l0l0l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.&fp=dd352a532221861a&biw=1280&bih=897). |
12,018,861 | I have a `DropDownList`, using which I have to store some values from the `CheckBoxList` in the database.
Before I select another index from the `DropDownList`, the values in the `CheckBoxList` has to be stored, prompting the user with an alert "Save before proceeding".
I am able to display the above mention alert message. But the problem is once i change the index it `DropDownList`, the previous selected index is lost.
Can someone kindly help me getting the previous selected value and select the same dynamically in `DropDownList`. Because the value is need to store in database.
The code for displaying alert message is:
```
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
``` | 2012/08/18 | [
"https://Stackoverflow.com/questions/12018861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597829/"
] | With the use of Global variables.
Using the code below. `PreviousIndex` will hold the previous, and `CurrentIndex` will hold current.
```
int PreviousIndex = -1;
int CurrentIndex = -1;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
PreviousIndex = CurrentIndex;
CurrentIndex = myDropdownList.Position; // Or whatever the get position is.
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
``` | So here's what finally worked for me. A combination of the answers above.
You have to track both previous and current selected index/value in the OnLoad handler of the page/control.
```
private int PreviousSelectedIndex
{
get { return (Page.ViewSate["prevIdx"] == null) ? -1 : (int)ViewSate["prevIdx"]; }
set { Page.ViewSate["prevIdx"] = value; }
}
private int CurrentSelectedIndex
{
get { return (Page.ViewSate["currIdx"] == null) ? -1 : (int)ViewSate["currIdx"]; }
set { Page.ViewSate["currIdx"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
PreviousDropDownValue = ddlYourDropDownList.SelectedValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
else if (Page.IsPostBack && CurrentDropDownValue != ddlYourDropDownList.SelectedValue)
{
PreviousDropDownValue = CurrentDropDownValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
}
```
After that you can compare the previous and current values with each other. |
2,634,973 | Can we use DDMS to take a screen capture with a device skin? Right now I'm just getting the exact screen rect area in my screen captures,
Thanks | 2010/04/14 | [
"https://Stackoverflow.com/questions/2634973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246114/"
] | I don't think DDMS tool has any such option;
it captures only the display: the screen area(therefore the name screen capture). | If you are using windows, assuming you have an emulator open with the skin you want, ensure that you have focus on the emulator. Press Alt-PrtScn to screen capture just the focused window, open up MS Paint and past the clipboard contents, you will have the screen shot + skin + window frame. It's up to you to crop that out. |
38,555,618 | In case the ajax take a while to load the dialog and user double clicking the button, two identical dialog will popup on the screen. I want to prevent it from happening.
```
$("#ShowUpCallTag").on('click', function (e) {
$.ajax({
url: '/Ship/CallTags/Dialog/' + $(e.target).data('calltagid'),
type: 'get',
datatype: 'json'
}).done(function (data) {
var dialog = main.ship.calltags.dialog.buildDialog(data);
dialog.open();
});
});
``` | 2016/07/24 | [
"https://Stackoverflow.com/questions/38555618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2124062/"
] | You can use `itertool.islice` for this, eg:
```
from itertools import islice
with open('filename') as fin:
wanted = islice(fin, 1, None) # change 1 to lines to skip
data = [line.split() for line in wanted]
``` | You cannot jump directly to a specific line. You have to read the first n lines:
```
n = 1
with open('data.txt', 'r') as data:
for idx, _ in enumerate(data):
if idx == n:
break
for line in data:
print line.split()
``` |
33,779 | Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful. | 2008/08/29 | [
"https://Stackoverflow.com/questions/33779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635/"
] | [This](http://myitforum.com/cs2/blogs/yli628/archive/2008/07/28/powershell-script-to-retrieve-scheduled-tasks-on-a-remote-machine-task-scheduler-api.aspx) is a good article (be sure to read the other linked article in it) that discusses looking at th scheduled tasks on remote machines. It is not exactly what you were asking for but it should get you headed in the right direction. | Not "native" PowerShell, but if you're running powershell.exe as an administrator then you should have access to the "at" command, which you can use to schedule tasks. |
8,944,097 | Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
```
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
```
my blogFunction.php
```
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
```
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:[here](http://retrovate.co.uk)
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
```
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
```
}
```
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
```
The problem that lies here, is, I click my button once at [my site](http://retrovate.co.uk)
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not. | 2012/01/20 | [
"https://Stackoverflow.com/questions/8944097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1085819/"
] | Add `session_start();` to blogFunction.php | Here's the properly working code...
index.php
```
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
```
blogFunction.php
```
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
```
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps! |
38,441,851 | I have done research on this, and I know that RXJava is using the observable pattern, and Bolts is relying on an executor. What framework would be good for handling tasks that need to be done in sequences?
I've heard of using singleExecutors, queues, chaining asynctasks, and these two frameworks. I've seen more people using bolts vs. rxjava but am curious to hear about peoples experiences between the two.
Thanks! | 2016/07/18 | [
"https://Stackoverflow.com/questions/38441851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2030899/"
] | I've used both in different projects and have done a migration from Bolts to RxJava. The simple answer to your question
>
> What framework would be good for handling tasks that need to be done in sequences?
>
>
>
Is that you could easily use either framework to do this. They both:
* Allow tasks to be chained one after another
* Enable the executor, etc to be specified for each task
* Allow errors to be captured and dealt with at a convenient time
However that is where Bolts functionality ends pretty much whilst RxJava just keeps on giving. The real power of RxJava lies in its operators which amongst other things allow you to transform, combine & filter data.
The learning curve for both frameworks is steep, RxJava is steeper...but it is considerably more powerful.
As an aside the method counts for the two libraries are
```
RxJava - 4605
Bolts - 479
``` | These two libraries solve two different problems.
**Bolts**
Bolts simplifies asynchronous programming by transparently pushing code to a background thread. Bolts also spends a good deal of effort attempting to reduce unsightly code nesting that produces a nested pyramid like format.
Therefore, if you are specifically looking to deal with async (multi-threading) issues, Bolts is on of the more robust solutions. Bolts is also effective at relieving code nesting and callback boilerplate and is probably a great solution for just trying to relieve callback issues.
**RxJava**
RxJava is specifically designed to support a reactive programming paradigm. Reactive programming is an alternative to imperative programming in Java. You might choose to move to a reactive programming paradigm for various reasons - of which there are many. If you want migrate your code to the reactive programming model, or you want to use reactive in your greenfield projects, consider using RxJava - the de facto reactive standard in the Java world.
Reactive does also solve the asynchronous programming problem, as well reduce callback boilerplate via generics. But it should not be used just to solve those problems. For example, Bolts ability to solve the nested pyramid code structure makes it a more viable solution for async programming. On the other hand, if you are using reactive via RxJava, async problems are already solved, so there is no point bringing in Bolts. |
37,409,811 | How to smooth the edges of this binary image of blood vessels obtained after thresholding.
[](https://i.stack.imgur.com/YyNQV.png)
I tried a method somewhat similar to [this method](https://stackoverflow.com/questions/21795643/image-edge-smoothing-with-opencv) but did not quite get the result I expected.
[](https://i.stack.imgur.com/8IAYc.png)
Here's the code:
```
import cv2
import numpy as np
INPUT = cv2.imread('so-br-in.png',0)
MASK = np.array(INPUT/255.0, dtype='float32')
MASK = cv2.GaussianBlur(MASK, (5,5), 11)
BG = np.ones([INPUT.shape[0], INPUT.shape[1], 1], dtype='uint8')*255
OUT_F = np.ones([INPUT.shape[0], INPUT.shape[1], 1],dtype='uint8')
for r in range(INPUT.shape[0]):
for c in range(INPUT.shape[1]):
OUT_F[r][c] = int(BG[r][c]*(MASK[r][c]) + INPUT[r][c]*(1-MASK[r][c]))
cv2.imwrite('brain-out.png', OUT_F)
```
What can be done to improve the smoothing of these harsh edges?
**EDIT**
I'd like to smoothen the edges something like <http://pscs5.tumblr.com/post/60284570543>. How to do this in OpenCV? | 2016/05/24 | [
"https://Stackoverflow.com/questions/37409811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605733/"
] | You can dilate then erode the areas <http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html>.
```
import cv2
import numpy as np
blur=((3,3),1)
erode_=(5,5)
dilate_=(3, 3)
cv2.imwrite('imgBool_erode_dilated_blured.png',cv2.dilate(cv2.erode(cv2.GaussianBlur(cv2.imread('so-br-in.png',0)/255, blur[0], blur[1]), np.ones(erode_)), np.ones(dilate_))*255)
```
[](https://i.stack.imgur.com/NZklL.png)
[](https://i.stack.imgur.com/cKF0x.png)
EDIT whith a scale facor off 4 before the stuff[](https://i.stack.imgur.com/AXbpC.png) | This is algorithm from **sturkmen**'s post above converted to Python
```
import numpy as np
import cv2 as cv
def smooth_raster_lines(im, filterRadius, filterSize, sigma):
smoothed = np.zeros_like(im)
contours, hierarchy = cv.findContours(im, cv.RETR_CCOMP, cv.CHAIN_APPROX_NONE)
hierarchy = hierarchy[0]
for countur_idx, contour in enumerate(contours):
len_ = len(contour) + 2 * filterRadius
idx = len(contour) - filterRadius
x = []
y = []
for i in range(len_):
x.append(contour[(idx + i) % len(contour)][0][0])
y.append(contour[(idx + i) % len(contour)][0][1])
x = np.asarray(x, dtype=np.float32)
y = np.asarray(y, dtype=np.float32)
xFilt = cv.GaussianBlur(x, (filterSize, filterSize), sigma, sigma)
xFilt = [q[0] for q in xFilt]
yFilt = cv.GaussianBlur(y, (filterSize, filterSize), sigma, sigma)
yFilt = [q[0] for q in yFilt]
smoothContours = []
smooth = []
for i in range(filterRadius, len(contour) + filterRadius):
smooth.append([xFilt[i], yFilt[i]])
smoothContours = np.asarray([smooth], dtype=np.int32)
color = (0,0,0) if hierarchy[countur_idx][3] > 0 else (255,255,255)
cv.drawContours(smoothed, smoothContours, 0, color, -1)
return(smoothed)
``` |
182,988 | >
> Let $a$ and $b$ be positive integers. Prove that: If $a^2$ divides $b^2$, then $a$ divides $b$.
>
>
>
Context: the lecturer wrote this up in my notes without proving it, but I can't seem to figure out why it's true. Would appreciate a solution. | 2012/08/15 | [
"https://math.stackexchange.com/questions/182988",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/38003/"
] | The proofs given use the Unique Factorization Theorem, or the existence of GCDs, or some equivalent, but the result is true even in places where there aren't any GCDs, so there must be a proof that doesn't rely on these properties. Here's one that works in the ring $O\_K$ of integers in a number field $K$, whether there are GCDs or not.
If $a,b$ are in $O\_K$ and $a^2$ divides $b^2$, then $b^2=a^2c$ for some $c$ in $O\_K$. So $\sqrt c=b/a$ is in $K$. But $\sqrt c$ is a zero of $x^2-c$, a monic polynomial with algebraic integer coefficients, so $\sqrt c$ is an algebraic integer, so $\sqrt c$ is in $O\_K$, so $a$ divides $b$. | $a^2 \mid b^2 \Rightarrow \frac{a}{d}\cdot\frac{a}{d} \mid \frac{b}{d}\cdot\frac{b}{d}$ with $d = gcd(a,b)$. From $gcd(\frac{a}{d},\frac{b}{d})=1$ follows $\frac{a}{d}=1$ or $a=d \mid b$.
This can easily be extended to $a^m \mid b^n$ where $2 \le n \le m$. |
290,758 | You know how when you get to 10+ tabs open in your browser (in this case Chrome) and you can't tell which tab is which anymore? I'm sure there are some good extension or something - what's the best solution to this problem?
 | 2011/05/30 | [
"https://superuser.com/questions/290758",
"https://superuser.com",
"https://superuser.com/users/3812/"
] | Install [TabsOutliner](https://chrome.google.com/webstore/detail/tabs-outliner/eggkanocgddhmamlbiijnphhppkpkmkl?hl=en) extension -
The ultimate windows & tabs manager for Chrome:

Not only it is show all the tabs and windows, it allow to add notes to them, freely reorganize everything, rescue all of this on Chrome crashes and give possibility to unload tabs without deleting them from tree - "in place" - very cool and handy, a lifesaver for me, and for any other tab addict. | The Chrome extension called [Vimium](https://chrome.google.com/webstore/detail/vimium/dbepggeogbaibhgnhhndojpepiihcmeb/details?hl=en) will let you search and go to any of your open tabs if you press `T`, amongst many other things that it can do.
<http://vimium.github.io> |
681,838 | **What I have**:
freeradius 2.1.10 on debian, configured to use a database.
**How it works now**:
There are many devices on the network and users, the users log on devices to configure them and so on. The users can log on to anything. For example some devices (ciscos) the user account on radius comes along with privileges (`cisco-avpair` attribute) that restrict what that individual can and cannot do on cisco devices.
**What I want freeradius to do in *addition*, for a specific special case**:
There's a special device that only select users should be able to authenticate into. Everyone else should be just denied access. (so, more strict than the cisco example above).
What I think I should be doing is first define my own attribute for example `company-special-privilege` so that I can set that for some users in the database with a value of `0` or `1`. Then define some policy in `policy.conf`.
**What I'm asking**:
Never done policies and I don't understand where they're applied in the rest of the freeradius config (where should I put my `special_access` policy).
Also unsure how to formulate it but the following pseudocode should represent what I want:
```
special_access {
if (request to log in $special_device_ip) {
if ($username company-special-privilege) {
reject #
}
}
}
```
From the above I don't know how to get the device IP or the attribute that the user is set with. I'm not doing a == 1 on the attribute in the second condition in case the user doesn't have the attribute as I don't know what that would imply but any user that doesn't have 1 must be rejected. | 2015/04/10 | [
"https://serverfault.com/questions/681838",
"https://serverfault.com",
"https://serverfault.com/users/116435/"
] | You should put it in `raddb/policy.conf` inside the `policy {}` stanza. Then they can be referenced (by their name) as you would a normal module, in authorize, authenticate, post-auth etc...
Policies in FreeRADIUS are essentially macros, they're not functions, they don't take arguments.
Defining a special attribute to control policy decisions is fine, do it in `raddb/dictionary` unless you have an IANA number and want to spin your own custom dictionary. An easier way may just be to query SQL directly.
I'm not sure what you want to do specifically, but here's an example that may help... Modify as necessary
```
special_access {
if ("%{Called-Station-ID}" == 'special device') {
if ("%{sql:SELECT special_priv FROM table WHERE username = '%{User-Name}'}" != '1') {
reject
}
}
}
``` | Thanks to some info I found on <http://linotp.org/doc/2.6/part-installation/integration/index.html> you can use the following configuration if you use the nas table in the MySQL database.
in the `nas` table you have IP ranges per device group, so if you device is in the specific IP range, the policy will be used:
```
mysql> SELECT * FROM nas WHERE is = '1';
+----+------------------+-------------+-------+------------+----------------------------------+
| id | nasip | shortname | type | secret | description |
+----+------------------+-------------+-------+------------+----------------------------------+
| 1 | 192.168.1.0/24 | restricted | other | ********* | only some users have access |
+----+------------------+-------------+-------+------------+----------------------------------+
```
In the file `sites-enabled/default` you refer to the policy;
```
authorize {
...
update request {
FreeRADIUS-Client-Shortname = "%{Client-Shortname}"
}
my_policy
...
}
```
and in the `policy.conf` you write your policy. This policy check first the `nas` table for the *restricted* prefix and then checks if the user has sufficient rights
```
...
my_policy {
if (FreeRadius-Client-Shortname =~ /^restricted/) {
if ("%{sql:SELECT moreaccess FROM radusergroup WHERE username = '%{User-Name}'}" != '1') {
update reply {
Cisco-AVPair := "shell:priv-lvl=1"
}
}
}
}
...
```
And of course in your `radusergroup` table where you're referring to in your SQL query you add an extra column where you allow specific users with extra rights.
```
mysql> SELECT * FROM radusergroup WHERE username like 'peter%';
+------------------+--------------+----------+------------+
| username | groupname | priority | moreaccess |
+------------------+--------------+----------+------------+
| peter | super-rights | 1 | NULL |
| peter1 | super-rights | 1 | 1 |
| peter2 | super-rights | 1 | 0 |
+------------------+--------------+----------+------------+
```
In this case I wrote the policy like this;
* Normally already get the high privilege: `Cisco-AVPair := "shell:priv-lvl=15"`
* So if the user has a '1' in this case `peter1` is just getting the normal rights.
* If the user doesn't have a '1' (`!= '1'`), it will get the right mentioned in the policy.
+ instead of using `update reply` you can use `reject` to completely block access for this (`peter` and `peter2`) users.
it could get quiet complicated, but this works for me. |
55,402,810 | I have a UIViewController, inside which there is a tableView. I added a RefreshControl. But when I pull, it always jumps for some times, which is not smooth and continuous at all.
I'm using Swift 4 and Xcode 10.1.
```
class ItemsController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, ItemCellDelegate {
......
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action:
#selector(handleRefresh(_:)),
for: UIControl.Event.valueChanged)
refreshControl.tintColor = UIColor.lightGray
return refreshControl
}()
......
override func viewDidLoad() {
// Refresh
self.tableView.refreshControl = self.refreshControl
}
......
@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
loadData()
self.tableView.reloadData()
refreshControl.endRefreshing()
}
......
}
``` | 2019/03/28 | [
"https://Stackoverflow.com/questions/55402810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I also faced that kind of problem. You can use this approach below:
1. Change your **handleRefresh** method like this:
```
@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
if !tableView.isDragging {
refresh() // refresh is another method for your reloading jobs
}
}
```
2. Add **refresh** method.
```
func refresh() {
self.refreshControl.endRefreshing()
self.tableView.reloadData()
}
```
3. Lastly you need to implement **scrollViewDidEndDragging**. If you've pulled down far enough, the refreshControl will be refreshing, so call refresh. Otherwise, you either haven't pulled down far enough, you were dragging on a different part of the table, or you dragged so quickly that the refreshControl ValueChanged event has yet to fire, and it will refresh the table there.
```
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if refreshControl.isRefreshing == true {
refresh()
}
}
``` | try
```
@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
loadData()
self.tableView.reloadData()
DispatchQueue.main.async {
//DispatchQueue.main.asyncAfter(deadline: .now + 0.2) { // or this one with
//short delay
refreshControl.endRefreshing()
}
}
``` |
2,609,552 | Given the following command,
```
echo "1: " | awk '/1/ -F ":" {print $1}'
```
why does AWK output:
```
1:
```
? | 2010/04/09 | [
"https://Stackoverflow.com/questions/2609552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/173446/"
] | `-F` is a command line argument, not AWK syntax. Try:
```bash
echo '1: ' | awk -F ':' '/1/ {print $1}'
``` | You can also use a regular expression as a field separator. The following will print "bar" by using a regular expression to set the number "10" as a separator.
```
echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'
``` |
6,274 | Mi ludas [ĉi tiun ludon](https://eo.wikipedia.org/wiki/Aventuro_(tekstaventuro)) kaj ofte estas frazoj kun *se* kiujn mi trovas strangaj. Ekzemple:
>
> Se vi trinkas la kokakolaon, la gusto ne plaĉas al vi. Sed vi soifas do eltrinkas la tutan boteleton.
>
>
>
>
> Se vi proksimiĝas la vilaĝon, kelkaj vilaĝanoj iras al vi.
>
>
>
La ludo estas tekstaventuro en kiu oni donas komandojn al la programo kaj ĝi klarigas tion kio rezulte okazas. Do la frazoj estas tio kio ja efektive okazas kaj ne estas ia kondiĉo.
Ĉu tiu vortumo estas normala en esperanto aŭ ĉu ĝi estas laŭvorta traduko de vortumo en alia lingvo?
---
**Edit:** mi aldonas plenan protokolon de ludo ĝis la unua frazo por montri kiel funkcias la ludsistemo. Mi tajpas tion kio komenciĝas per `>`.
>
> Vi ferias je la insulo Texel. Hieraŭ vi aŭdis en la trinkejo strangan historion. Du infanoj perdiĝis sur la norda strando, kvankam en la ĉirkaŭaĵo estis multaj plenkreskuloj neniu vidis ilin foriri. Ankaŭ certas ke ili ne naĝis, kelkaj diras ke ili simple fosis kavon. Ĝis nun neniu revidis la infanojn kaj ĉiu timas iri al la marbordo.
>
>
> Kaj kion vi faras nun?
>
> > mi iras norden
>
>
> Bone. En ĉiu direkto nun etendiĝas la dunoj, sed vi jam flaras la maron.
>
>
> Kaj kion vi faras nun?
>
> > mi iras norden
>
>
> Bone. Vi estas sur la strando, la ondoj ne estas ege altaj. Vi vidas kokakolaan boteleton.
>
>
> Kaj kion vi faras nun?
>
> > mi prenas la boteleton
>
>
> Vi prenis la kokakolaan boteleton.
>
>
> Kaj kion vi faras nun?
>
> > mi trinkas ĝin
>
>
> Se vi trinkas la kokakolaon, la gusto ne plaĉas al vi. Sed vi soifas do eltrinkas la tutan boteleton.
>
>
> Kaj kion vi faras nun?
>
> >
>
>
> | 2021/07/06 | [
"https://esperanto.stackexchange.com/questions/6274",
"https://esperanto.stackexchange.com",
"https://esperanto.stackexchange.com/users/13/"
] | Ŝajnas al mi ke tio estas mistraduko, ĉar vi ĵus tajpis vian agon, do la ĝusta vorto estas **kiam** (when).
Probable la gepatra lingvo de la tradukisto uzas la saman vorton por *se* kaj *kiam*. Iam mi legis ke la germana lingvo estas tia, kaj Joop Eggen informis nin en alia respondo ke la nederlanda ankaŭ havas vorton kiu signifas kaj *se* kaj *kiam*. | Post via enigo de frazo, la respondo de la komputilo ne vere certas pri tio, kio okazas nun.
Do ne eblas tute certe diri:
>
> Kiam vi trinkas la kokakolaon, la gusto ne plaĉas al vi.
>
>
>
Fuŝus la etoson diri ion similan al:
>
> Tiuokaze ke vi trinkas/trinkus la kokakolaon, la gusto ne plaĉas al vi.
>
>
>
Do strange, tamen en ĉi tiu formo/reĝimo **se** estas artifika solvo:
* ŝajnigi ke vi scias kio okazas, kaj rakontas plu;
* alie vi estas pardonata pro la "kondiĉe ke"/"se".
**kiam** tamen estas pli natura. Eble oni konsideru ke en la nederlanda lingvo *als* [nl] = *se, kiam*. |
40,112,752 | I have an issue with this code, the full Ajax code runs to the end, and fades out the parent of the deletebtn, here is the code of the deletebtn, post and ajax:
```
<?php
include('php/connect.php');
$roomQuery = "SELECT * FROM rooms";
$roomResult = mysqli_query($conn, $roomQuery);
while($roomRow = mysqli_fetch_array($roomResult)){
echo "<div class='roomParent'>";
echo "<div class='edit_roomRow'><h1> Rum " . $roomRow['ID'] . "</h1>" . "<h4>" . $roomRow['Description'] . "</h4></div><div name='id' id='removepost' value='" . $roomRow['ID'] . "' class='btn btn-danger delete-btn'>Ta bort</div>";
echo "</div>";
}
mysqli_free_result($roomResult);
mysqli_close($conn);
?>
</div>
<script type="text/javascript">
$(".delete-btn").click(function(){
var id = $(this).val();
var parent = $(this).parent();
//Ajax call
$.ajax({
method:"GET",
url: "php/deletepost.php",
data:{ removepost: id },
success: function(){
$(this).val("");
parent.fadeOut("slow")
}});
})
```
And here is the PHP code which the ajax data gets sent to:
```
<?php
require('connect.php');
$deletesql = "DELETE FROM rooms WHERE ID = " . ($_GET['removepost']);
if(isset($_GET['removepost'])){
mysqli_query($conn, $deletesql);
}
?>
```
Code is gonna be fixed from sql injections etc. later, this is just testing | 2016/10/18 | [
"https://Stackoverflow.com/questions/40112752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6058159/"
] | Keeping the same structure, you could do a `$this->Topic->saveAssociated($this->request->data);` and it will add any new (`'id' => NULL` or unset) items in the data array.
About the delete, the only case I know would delete at the same time, would be a HABTM when it's marked as `'unique' => true`. Otherwise, you need to do a `$this->Post->deleteAll(array('Post.topic_id' => $unwanted_topic_id), false);`
I could think of making a new array keeping the ones you want deleted and sending them as condition for the deleteAll function. | **From CakePHP 2 Book**
```
delete(integer $id = null, boolean $cascade = true);
```
>
> Deletes the record identified by $id. By default, also deletes records
> dependent on the record specified to be deleted.
>
>
> For example, when deleting a User record that is tied to many Recipe
> records (User ‘hasMany’ or ‘hasAndBelongsToMany’ Recipes):
>
>
> * if $cascade is set to true, the related Recipe records are also deleted if the model’s dependent-value is set to true.
> * if $cascade is set to false, the Recipe records will remain after the User has been deleted.
>
>
>
**<http://book.cakephp.org/2.0/en/models/deleting-data.html>** |
3,474,805 | Suppose $f:R \to R$ is a continuous function such that $$f(x)=\frac{1}{t}\int^t \_0f(x+y)-f(y)dy$$ for every $x$ and for all $t>0$. Prove that there exists a constant $c$ such that $f(x)=cx$ for every $x$ | 2019/12/13 | [
"https://math.stackexchange.com/questions/3474805",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/728159/"
] | First note that
$$f(0) = \frac{1}{t}\int\_0^t f(0+y) - f(y) \: dy = 0$$
Take the derivative of $f$ w.r.t. $x$
$$f'(x) = \frac{1}{t}\int\_0^t f'(x+y)\:dy = \frac{f(x+t)-f(x)}{t}$$
From here we can deduce that
$$f'(0) = \frac{f(0+t)-f(0)}{t} = \frac{f(t)}{t}$$
$$\implies f(t) = f'(0)\cdot t$$
for all $t>0$. If we want to prove that it holds for negative values as well, take $g(x) = f(-x)$ then consider
$$g'(x) = \frac{f(-x)-f(t-x)}{t}$$
and plug in $x=t$ to get the differential equation
$$t\cdot g'(t) = g(t)$$
which only has $ct$ as a solution. Thus $f(-t)$ is also a linear function for $t>0$ and we are done. | The equation can be written as $\int\_0^{t} [f(x+y)-f(y)-f(x)]dt=0$. Since this holds for all $t >0$ we get $f(x+y)-f(y)-f(x)=0$ whenever $y>0$. Since $f(0)=0$ (letting $t \to 0$ in the given equation we get $f(x)=f(x)-f(0)$ so $f(0)=0$) this holds for $y \geq 0$. Now a standard argument shows that $f(x)=cx$ for all $x \geq 0$ where $c=f(1)$. Now let $x<0$. For $y>0$ large enough we get $f(x+y)=c(x+y)=f(x)+f(y)=f(x)+cy$ which gives $f(x)=cx$. |
4,698,220 | I am working on a Django / Python website. I have a page where I want to display a table of search results. The list of results is passed in to the template as normal.
I also want to make this list of objects accessible to the JavaScript code.
My first solution was just create another view that returned [JSON](http://en.wikipedia.org/wiki/JSON) format. But each page load required calling the query twice. So then I tried only downloading the data using the JSON view and printing the table using JavaScript.
But this is also not desirable as now the presentation layer is mixed into the JavaScript code.
Is there a way to create a JavaScript object from the Python list as the page is rendered? | 2011/01/15 | [
"https://Stackoverflow.com/questions/4698220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576498/"
] | **Solution**
I created a custom template filter, see *[custom template tags and filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)*.
```
from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Library
register = Library()
def jsonify(object):
if isinstance(object, QuerySet):
return mark_safe(serialize('json', object))
return mark_safe(simplejson.dumps(object))
register.filter('jsonify', jsonify)
jsonify.is_safe = True
```
The calls to mark\_safe are important. Otherwise Django will escape it.
In the template:
```
//Without template filter (you'll need to serialise in the view)
var data = jQuery.parseJSON('{{ json_data|safe }}');
alert(data.length);
//Using the template filter
var data2 = jQuery.parseJSON('{{ record_list|jsonify }}');
alert(data2.length);
```
Note the single quotes around the template tag.
Although my next question would be - is it REALLY safe?
Update
------
An updated version working in django 1.8 of the above template tag that also handles being passed a flat values list, ie. values\_list('myfield', flat=True):
```
from django.core.serializers import serialize
from django.db.models.query import QuerySet, ValuesListQuerySet
from django.template import Library
import json
register = Library()
@register.filter( is_safe=True )
def jsonify(object):
if isinstance(object, ValuesListQuerySet):
return json.dumps(list(object))
if isinstance(object, QuerySet):
return serialize('json', object)
return json.dumps(object)
``` | Look [this answer](https://stackoverflow.com/a/15592905/1981384) too.
But it isn't highload way. You must:
a) Create JSON files, place to disk or S3. In case is JSON static
b) If JSON is dynamic. Generate JSON on separately url (like API) in your app.
And, load by JS directly in any case. For example:
`$.ajax('/get_json_file.json')`
P.S.: Sorry for my English. |
258,336 | Some notes before main question:
* My Steam games library is on separate location (**another drive**), and removing games is **not** a solution to this question.
* I have already tried out TikiOne Steam Cleaner, it didn't detect anything to delete in my Steam installation folder.
* I would rather not install Steam on my second drive.
So the main question is - can I somehow reduce Steam installation folder? I mean the one at:
`.../Program Files (x86)/Steam`
Now it is roughly 800 MB in size, and it's a real pain on my 120GB SSD drive, where each GB is worth it's weight in gold (metaphorically speaking).
I'm looking for unused update packages (maybe Steam doesn't delete them after update?), or other backups made by Steam without me even knowing. I also don't know where screenshots are kept, maybe this could be the solution? | 2016/03/10 | [
"https://gaming.stackexchange.com/questions/258336",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/86943/"
] | In addition to deleting your appcache folder, you can try a few other things.
One is running `steam://flushconfig` as described in [this Steam knowledgebase article.](https://support.steampowered.com/kb_article.php?ref=3134-TIAL-4638) If there's any cruft lying around in your steam install, this ought to clean it up.
You mentioned screenshots - they are indeed stored in a subfolder of the Steam install folder, specifically in something like:
`C:\Program Files (x86)\Steam\userdata\<your user id>\760\remote\<game id>\screenshots`
There may be many, many megabytes worth of stuff in here, depending on how frequently you take screenshots. You can safely clean out whatever from this directory, and you could always symlink this directory to some other bulk storage drive if you want.
Finally, my go-to solution for finding large folders and files under Windows is [WinDirStat](https://windirstat.info/). Point this at your SSD, and it will show you were all the large files are lurking. You can also drill down to your Steam folder and see what folders/files are taking up most of the room. | Your statement **`I would rather not install Steam on my second drive.`** is precisely what you should do to be honest.
There is no particular benefit of having Steam on your SSD `C:\` drive.
If you disagree, please tell me why. |
188,821 | I'm building a couple industrial style tables, using black pipe from Home Depot for the legs. The fittings and smaller nipples are all a faded gray color that perfectly complements the black cherry stain I used on the wood. But the longer segments of pipe come in a black color that is too dark and very patchy and uneven. I would really like to remove it and ideally match the color of the fittings.
Based on some research, I tried using mineral spirits to clean them up. This had very little effect. Next I tried sanding. This does break through the black, but is very slow going and the sand paper quickly fills up with black goop. Also this cuts all the way through to the underlying metal, which results in a shinier color than the fittings. There's got to be a better way.
According to [this video](https://www.youtube.com/watch?v=bcf2ovGgnrc), the black stuff is mill scale and can be removed with Jasco paint and epoxy remover. This does look effective from the clip, but the Jasco stuff is $45/gal and seems pretty toxic. Also I'm skeptical that the black stuff is actually mill scale.
Before I drop the money on the Jasco, can anyone tell me what the stuff is and maybe recommend a less toxic way of removing it? I wouldn't mind painting over it if I can figure out how to properly prime the current surface so the paint stays on. | 2020/04/01 | [
"https://diy.stackexchange.com/questions/188821",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/113341/"
] | Simple answer, use PVC pipe cleaner and plenty of cloth rags. The pipe cleaner is basically acetone (don't use the purple primer!) but comes with the convenient applicator. Dissolves the black coating gunk instantly and you can wipe it away quickly with a rag, but act fast. The acetone evaporates quickly and the gunk starts to set again. I just did 12 ft. of pipe this way, and it brings the surface to a grey smooth look that matches the shorter threaded nipples of the same pipe size that usually come wrapped in clear plastic. You will likely need some coating back on top of this, even if you like the smooth grey look and choose not to paint, as it appeared like a tiny bit of rust flashed up on the surface of one pipe. I chose to rub mine down with black shoe polish. No heavy coating, but serves as a decent rust inhibitor for indoor use, and the pipes will be mounted out of reach so no chance it will rub off on someone. I had mixed piping from two different manufacturers, and the PVC pipe cleaner worked excellently on both coatings. | Pure turpentine worked fast and easy. Just saturate a rag and wipe a few times.  |
68,654,502 | In a web application I'm running, I suddenly started getting these odd tokens containing a huge string of periods at the end.
This happens even when I bypass my application code and call the function from the Google OAuth library directly.
Here's an example token:
```
ya29.c.Kp8BCgi0lxWtUt-_[Normal JWT stuff, redacted for security]yVvGk...............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
```
Could this be an upstream issue with Google OAuth? Has anyone else seen tokens like this? | 2021/08/04 | [
"https://Stackoverflow.com/questions/68654502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9694049/"
] | I found the problem is on the Google server-side. It's actually returning the JWT with the trailing "." chars. I'm updating Chilkat to automatically trim the trailing "." chars if found before returning the JWT. | In fact the dots make no difference. You can still use the access\_token to call apis. If you get an error response, you'd better check a further reason. Do you set the correct scope (<https://developers.google.com/identity/protocols/oauth2/scopes>)? Does the
permission of the service account is right? |
12,375,599 | I created a form, and I want to use jquery to store the labels and the user inputted input value into an array. At the bottom of the form, there is a next button instead of submit. When the user presses next, they should see a summary of all of the labels and their input. The HTML is like this:
```
<div class="form-item">
<label>Zip Code:</label>
<input type="text" />
</div>
<div class="form-item">
<label>Address:</label>
<input type="text" />
</div>
```
I believe the best way to go about this is to loop thorugh each `div.form-item` using `each()` like so:
```
$(".form-item").each(function(){
var label = $(this).find('label').text();
var input = $(this).find('input').val();
});
```
Im not sure how to go about collecting multiple chunks of form items using unique variables. I want this to be completely dynamic, so regardless of how many form fields there are, it will work. DO I store them in an array? What is the best way to go about this? | 2012/09/11 | [
"https://Stackoverflow.com/questions/12375599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121630/"
] | You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
```
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
```
This creates a vector of `RR` size `CC` vectors, filled with `0`. | What you have initialized is a *vector of vectors*, so you **definitely have to include a vector to be inserted**("Pushed" in the terminology of vectors) **in the original vector** you have named matrix in your example.
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
Please try this out :
```
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}
``` |
64,289,464 | I'm currently trying to learn how to use Tweepy. I keep getting an 'SyntaxError: invalid syntax' on the print line, and I'm not sure why.
Relevant Code
```
for tweet in api.search(q = 'python', lang="en", rpp=10):
print(f"{tweet.user.name}:{tweet.text}")
``` | 2020/10/10 | [
"https://Stackoverflow.com/questions/64289464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13895583/"
] | If I'm correct you want to run some job at a specific time of day or week on a NodeJS server. These jobs are called `Cron Jobs`. there are npm modules for Cron Jobs.
1. [cron](https://www.npmjs.com/package/cron)
2. [node-cron](https://www.npmjs.com/package/node-cron)
you can use these modules to run your jobs then fetch the data and then I think you can easily filter the data and with the help of [nodemailer](https://www.npmjs.com/package/nodemailer) npm module you can send the mail.
[Here](https://medium.com/javascript-in-plain-english/how-to-schedule-cron-jobs-in-node-js-897215e2e5d3) you can see an example for the Cron jobs in the NodeJS server. | You can create a function which will fetch data from firebase and also send the email. To send the email, you will need to install `nodemailer` and also turn ON "Less Secure App Access" for the sender email address. Searching those keywords on google will lead you there.
You could do something like
```
async function sendMail() {
// fetch required data from database
let transport = mailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'your_source_email_address',
pass: 'password'
},
});
const message = {
from: '', // Sender address
to: ['email1', 'email2'...], // List of recipients
subject: '', // Subject line
html: '<!DOCTYPE html>' +
'<html lang="en">' +
'<head>' +
'<meta charset="UTF-8">' +
'<meta name="viewport" content="width=device-width, initial-scale=1.0">' +
'</head>' +
'<body>' +
Your data to be displayed in silmilar html format or link an html file.
'</body>' +
'</html>'
};
}
```
As for scheduling it for every Monday at 10:00, you can install `node-cron` and configure it like this in your entry file:
```
const cron = require('node-cron');
...
...
cron.schedule('0 10 * * Monday', async () => {
await sendMail(
}, {
scheduled: true,
timezone: 'your_time_zone'
});
```
More info for your timezone and examples for scheduling are available on their [npm page](https://www.npmjs.com/package/node-cron).
Hope this helps. Cheers! |
17,078,280 | I'm attempting to use DOCX4J to parse and insert content into a template. As part of this template I have loops which I need to copy everything inbetween two markers, and repeat all that content X times.
The relavant code is as follows:
```
public List<Object> getBetweenLoop(String name){
String startTag = this.tag_start + name + "_LOOP" + this.tag_end;
String endTag = this.tag_start + name + this.tag_end;
P begin_loop = this.getTagParagraph(startTag);
P end_loop = this.getTagParagraph(endTag);
ContentAccessor parent = (ContentAccessor) this.getCommonParent(begin_loop, end_loop);
List<Object> loop = new ArrayList<Object>();
boolean save = false;
//Cycle through the content for the parent and copy all the objects that
//are between and including the start and end-tags
for(Object item : parent.getContent()){
if(item.equals(begin_loop) || item.equals(end_loop))
save = (save) ? false : true;
if(save || item.equals(end_loop)){
loop.add(XmlUtils.deepCopy(item));
}
if(item.equals(end_loop)){
//Here I want to insert everything copied X times after the current item and then exit the for loop.
//This is the part I'm not sure how to do since I don't see any methods "Insert Child", etc.
}
}
return loop;
}
```
getTagParagraph successfully returns the object representing the paragraph for the tag sent. This works beautifully.
getCommonParent returns the shared parent between the two supplied tags. This works beautifully.
My problem is, as commented, how to insert the newly copied items into the appropriate place. | 2013/06/13 | [
"https://Stackoverflow.com/questions/17078280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543770/"
] | If you're looking to insert all the objects you have stored in your `loop` collection, you simply need to do something like this (in the conditional you've commented):
```
item.getContent().addAll(loop);
```
`item` represents the `end_loop` object (a paragraph or whatever), and inserts all the objects you've collected into the `loop` collection. (`addAll` may require an int argument too, I can't recall, but if it does that's just the desired index within the overall `MainDocumentPart.getContent()` JAXB document representation). | @Ben, thank-you!
If you know of any instances where below wouldn't work, please let me know.
I had actually just figured out something very similar, but ended up changing a lot more code. Below is what I put together.
```
public void repeatLoop(String startTag, String endTag, Integer iterations){
P begin_loop = this.getTagParagraph(startTag);
P end_loop = this.getTagParagraph(endTag);
ContentAccessor parent = (ContentAccessor) this.getCommonParent(begin_loop, end_loop);
List<Object> content = parent.getContent();
Integer begin_pointer = content.indexOf(begin_loop);
Integer end_pointer = content.indexOf(end_loop);
List<Object> loop = new ArrayList<Object>();
for(int x=begin_pointer; x <= end_pointer; x = x + 1){
loop.add(XmlUtils.deepCopy(content.get(x)));
}
Integer insert = end_pointer + 1;
for(int z = 1; z < iterations; z = z + 1){
content.addAll(insert, loop);
insert = insert + loop.size();
}
}
``` |
145,327 | I have two servers that have a nearly identical (software) configuration. We are upgrading the web servers to run windows server 2008 R2, one already is however the main one (that currently has sites) is on WS2008.
Now, the old server is ns.mydomain.com and the new server is ns1.mydomain.com. Since dns automatically fails over to ns1.mydomain.com I'd like a way to move all the vhosts to the new server.
Is there an automatic way to move / recreate all the vhosts on the new server?
I have figured out how to migrate the DNS records already [DNS Migration](http://blogger.xs4all.nl/zanstra/archive/2004/11/26/windnsbackup.aspx) and since both servers are on the same private network migrating the website data isn't a large issue. Every site is running PHP & MySQL and the MySQL server is external so the records won't have to be moved.
Thanks | 2010/05/26 | [
"https://serverfault.com/questions/145327",
"https://serverfault.com",
"https://serverfault.com/users/14367/"
] | Check out the [IIS Web Deployment tool](http://www.iis.net/download/webdeploy), that should get you started with migrating the IIS sites and settings. | why don't you just clone the server by using tool like clonezilla, which makes it much easier to do |
24,031,064 | I have an input textfield for which some validations are applied. the user cannot enter numbers and special characters in the field. everything is fine but i want to allow space in between the words. how to do it.
Here is the code...
```
<input type="text" id="text1" onKeyPress="return IsAlpha(event);"/>
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(32); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
``` | 2014/06/04 | [
"https://Stackoverflow.com/questions/24031064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2446535/"
] | Answering my own question, I found a workaround thanks to this guy :
<http://www.doctrine-project.org/jira/browse/DDC-3120>
He's far better than me when it comes to explaining, but this is what I have now, and it works like a charm! :)
```
{
if ($this->_prototype === null) {
$this->_prototype = @unserialize(sprintf('O:%d:"%s":0:{}', strlen($this->name), $this->name));
if ($this->_prototype === false) {
$this->_prototype = @unserialize(sprintf('C:%d:"%s":0:{}', strlen($this->name), $this->name));
}
}
return clone $this->_prototype;
}
``` | 1. Check your PHP version by "php -v" on command line. E.g. PHP 5.6.10
2. Edit the file /vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php::newInstance()
Add your PHP\_VERSION\_ID here
```
if (PHP_VERSION_ID === 50610 ) {
.
}
```
It's a temporary solution, since we don't edit `vendor` directory. |
28,265,613 | I have a problem with VHDL ALU code. I have to make simple ALU with 4 operations with 4-bit operands. I implemented these operations correctly and they work well. For executing I use E2LP board. For choosing the operation I selected 4 JOY buttons,one for each operation. Problem is that when I press button to execute operation and depress it I want result to stay on LEDs while I don't select any other operation, but that's not happening. For first 5 LEDs this works fine, but upper 3 not.This only works for one operation. My simulation results are correct. Here is code an schema of project.Thank you in advance.
```
---------------------------------------------------------------------------------- Control logic
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
Port ( --clk : in STD_LOGIC;
in_saberi : in STD_LOGIC;
in_mnozi : in STD_LOGIC;
in_ili : in STD_LOGIC;
in_rotiraj : in STD_LOGIC;
out_saberi : out STD_LOGIC;
out_mnozi : out STD_LOGIC;
out_ili : out STD_LOGIC;
out_rotiraj : out STD_LOGIC);
end upravljanje;
architecture Behavioral of upravljanje is
signal tmps : std_logic := '1';
signal tmpm : std_logic := '1';
signal tmpi : std_logic := '1';
signal tmpr : std_logic := '1';
begin
logika : process(in_saberi,in_mnozi,in_ili,in_rotiraj)
begin
if (in_saberi='0' and in_mnozi='1' and in_ili='1' and in_rotiraj='1') then
tmps <= in_saberi;
tmpm <= in_mnozi;
tmpi <= in_ili;
tmpr <= in_rotiraj;
elsif (in_mnozi='0' and in_saberi='1' and in_ili='1' and in_rotiraj='1') then
tmps <= in_saberi;
tmpm <= in_mnozi;
tmpi <= in_ili;
tmpr <= in_rotiraj;
elsif (in_saberi='1' and in_mnozi='1' and in_ili='0' and in_rotiraj='1') then
tmps <= in_saberi;
tmpm <= in_mnozi;
tmpi <= in_ili;
tmpr <= in_rotiraj;
elsif (in_saberi='1' and in_mnozi='1' and in_ili='1' and in_rotiraj='0') then
tmps <= in_saberi;
tmpm <= in_mnozi;
tmpi <= in_ili;
tmpr <= in_rotiraj;
elsif (in_saberi='1' and in_mnozi='1' and in_ili='1' and in_rotiraj='1') then
tmps <= tmps;
tmpm <= tmpm;
tmpi <= tmpi;
tmpr <= tmpr;
else
tmps <= '1';
tmpm <= '1';
tmpi <= '1';
tmpr <= '1';
end if;
end process logika;
out_saberi <= tmps;
out_mnozi <= tmpm;
out_ili <= tmpi;
out_rotiraj <= tmpr;
end Behavioral;
--------------------------------------------------------------------------
-- this is for operation add
entity sabirac is
Port ( clk : in STD_LOGIC;
data1 : in STD_LOGIC_VECTOR (3 downto 0);
data2 : in STD_LOGIC_VECTOR (3 downto 0);
saberi : in STD_LOGIC;
result : out STD_LOGIC_VECTOR (7 downto 0));
end sabirac;
architecture Behavioral of sabirac is
signal c : std_logic_vector (5 downto 0) := "000000";
signal tmp : std_logic_vector (7 downto 0) := "00000000";
begin
sabiranje : process(clk,saberi)
begin
if (saberi='0') then
tmp(0) <= data1(0) xor data2(0);
c(0) <= data1(0) and data2(0);
tmp(1) <= data1(1) xor data2(1) xor c(0);
c(1) <= (data1(1) and data2(1)) or (data1(1) and c(0)) or (data2(1) and c(0));
tmp(2) <= data1(2) xor data2(2) xor c(1);
c(2) <= (data1(2) and data2(2)) or (data1(2) and c(1)) or (data2(2) and c(1));
tmp(3) <= data1(3) xor data2(3) xor c(2);
if(data1(3) = data2(3)) then
c(3) <= (data1(3) and data2(3)) or (data1(3) and c(2)) or (data2(3) and c(2));
tmp(4) <= c(3);
tmp(5) <= c(3);
tmp(6) <= c(3);
tmp(7) <= c(3);
else
c(3) <= data1(3) xor data2(3) xor c(2);
tmp(4) <= c(3);
tmp(5) <= c(3);
tmp(6) <= c(3);
tmp(7) <= c(3);
end if;
else
tmp <= "ZZZZZZZZ";
end if;
end process sabiranje;
result <= tmp;
end Behavioral;
-----------------------------------------------------------------------------
entity mul is
Port (
clk : in STD_LOGIC;
pomnozi : in STD_LOGIC;
data1 : in STD_LOGIC_VECTOR (3 downto 0);
data2 : in STD_LOGIC_VECTOR (3 downto 0);
result : out STD_LOGIC_VECTOR (7 downto 0));
end mul;
architecture Behavioral of mul is
begin
mnozenje : process (clk,pomnozi)
begin
if (pomnozi='0') then
result <= std_logic_vector(signed(data1) * signed(data2));
else
result <= "ZZZZZZZZ";
end if;
end process mnozenje;
end Behavioral;
--------------------------------------------------------------------------
entity rotate is
Port ( clk : in STD_LOGIC;
rotiraj : in STD_LOGIC;
data1 : in STD_LOGIC_VECTOR (3 downto 0);
data2 : in STD_LOGIC_VECTOR (3 downto 0);
result : out STD_LOGIC_VECTOR (7 downto 0));
end rotate;
architecture Behavioral of rotate is
signal tmp : std_logic_vector (3 downto 0) := "0000";
signal tmp2 : std_logic_vector (7 downto 0) := "00000000";
begin
rotacija : process(clk,rotiraj)
begin
if (rotiraj='0') then
tmp <= std_logic_vector(rotate_left(unsigned(data1),to_integer(unsigned(data2))));
tmp2(0) <= tmp(0);
tmp2(1) <= tmp(1);
tmp2(2) <= tmp(2);
tmp2(3) <= tmp(3);
tmp2(4) <= '0';
tmp2(5) <= '0';
tmp2(6) <= '0';
tmp2(7) <= '0';
else
tmp2 <= "ZZZZZZZZ";
end if;
end process rotacija;
result <= tmp2;
end Behavioral;
--------------------------------------------------------------------------
-- Logic OR operation
entity logicko_ILI is
Port ( clk : in STD_LOGIC;
data1 : in STD_LOGIC_VECTOR (3 downto 0);
data2 : in STD_LOGIC_VECTOR (3 downto 0);
logili : in STD_LOGIC;
result : out STD_LOGIC_VECTOR (7 downto 0));
end logicko_ILI;
architecture Behavioral of logicko_ILI is
signal c : std_logic_vector (5 downto 0) := "000000";
signal tmp : std_logic_vector (7 downto 0) := "00000000";
begin
logicko : process(clk,logili)
begin
if (logili = '0') then
tmp(0) <= data1(0) or data2(0);
tmp(1) <= data1(1) or data2(1);
tmp(2) <= data1(2) or data2(2);
tmp(3) <= data1(3) or data2(3);
tmp(4) <= '0';
tmp(5) <= '1';
tmp(6) <= '1';
tmp(7) <= '1';
else
tmp <= "ZZZZZZZZ";
end if;
end process logicko;
result <= tmp;
end Behavioral;
``` | 2015/02/01 | [
"https://Stackoverflow.com/questions/28265613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4517445/"
] | Change `special rates` to `special_rates`. | Add an `_` to special rates to bring it in line with your multiple word naming convention e.g.`(member_type_name)`.
Also numbers don't need single quotes
```
INSERT INTO membership_type(member_type_name,benefits,special_rates)
VALUES ('silver', 'Free WI-fi', 0.9)
``` |
41,714,415 | Can I get list of my app push notifications from native Notification Center app? When the my app starts, I want to show notifications which were received while my app is not running. | 2017/01/18 | [
"https://Stackoverflow.com/questions/41714415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5805520/"
] | If you don't want to miss any notification.
You can use Pushkit silent push notification.
Once you receive pushkit payload and your app you can schedule local notification and also keep in `NSUserDefault`.
Using silent push notification your app will be active in background even app is in terminated state. It will be active upto your local notification sound plays ( Max 30 seconds ). You can also keep data in `SQLite` in that duration.
Once you open app from icon or from notification you can check your `NSUserDefauls` or `SQLite` and do further things.
**Note** - With normal push notification, your app would get active in background or terminated state, so you can not write any code to keep data within app which cam along with push notification
**Reference** - <https://github.com/hasyapanchasara/PushKit_SilentPushNotification>
Let me know if further clarification is required. | as said by Tian:
there is no api to get a list of notifications your app missed.
**no way.**
---
you only get the one the user clicked to launch your app. |
28,593,542 | I have a list of words in Pandas (DF)
```
Words
Shirt
Blouse
Sweater
```
What I'm trying to do is swap out certain letters in those words with letters from my dictionary **one letter at a time**.
so for example:
```
mydict = {"e":"q,w",
"a":"z"}
```
would create a new list that first replaces all the "e" in a list one at a time, and then iterates through again replacing all the "a" one at a time:
```
Words
Shirt
Blouse
Sweater
Blousq
Blousw
Swqater
Swwater
Sweatqr
Sweatwr
Swezter
```
I've been looking around at solutions here: [Mass string replace in python?](https://stackoverflow.com/questions/1919096/mass-string-replace-in-python)
and have tried the following code but it changes all instances "e" instead of doing so one at a time -- any help?:
```
mydict = {"e":"q,w"}
s = DF
for k, v in mydict.items():
for j in v:
s['Words'] = s["Words"].str.replace(k, j)
DF["Words"] = s
```
this doesn't seem to work either:
```
s = DF.replace({"Words": {"e": "q","w"}})
``` | 2015/02/18 | [
"https://Stackoverflow.com/questions/28593542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3682157/"
] | This answer is very similar to Brian's [answer](https://stackoverflow.com/a/28706233/2395605), but a little bit sanitized and the output has no duplicates:
```
words = ["Words", "Shirt", "Blouse", "Sweater"]
md = {"e": "q,w", "a": "z"}
md = {k: v.split(',') for k, v in md.items()}
newwords = []
for word in words:
newwords.append(word)
for c in md:
occ = word.count(c)
pos = 0
for _ in range(occ):
pos = word.find(c, pos)
for r in md[c]:
tmp = word[:pos] + r + word[pos+1:]
newwords.append(tmp)
pos += 1
```
Content of `newwords`:
```
['Words', 'Shirt', 'Blouse', 'Blousq', 'Blousw', 'Sweater', 'Swqater', 'Swwater', 'Sweatqr', 'Sweatwr', 'Swezter']
```
Prettyprint:
```
Words
Shirt
Blouse
Blousq
Blousw
Sweater
Swqater
Swwater
Sweatqr
Sweatwr
Swezter
```
*Any errors are a result of the current time. ;)*
---
Update (explanation)
====================
>
> **tl;dr**
>
>
> The main idea is to find the occurences of the character in the word one after another. For each occurence we are then replacing it with the replacing-char (again one after another). The replaced word get's added to the output-list.
>
>
>
I will try to explain everything step by step:
```
words = ["Words", "Shirt", "Blouse", "Sweater"]
md = {"e": "q,w", "a": "z"}
```
Well. Your basic input. :)
```
md = {k: v.split(',') for k, v in md.items()}
```
A simpler way to deal with replacing-dictionary. `md` now looks like `{"e": ["q", "w"], "a": ["z"]}`. Now we don't have to handle `"q,w"` and `"z"` differently but the step for replacing is just the same and ignores the fact, that `"a"` only got one replace-char.
```
newwords = []
```
The new list to store the output in.
```
for word in words:
newwords.append(word)
```
We have to do those actions for each word (I assume, the reason is clear). We also append the world directly to our just created output-list (`newwords`).
```
for c in md:
```
`c` as short for `character`. So for each character we want to replace (all keys of `md`), we do the following stuff.
```
occ = word.count(c)
```
`occ` for `occurrences` (yeah. `count` would fit as well :P). `word.count(c)` returns the number of occurences of the character/string `c` in `word`. So `"Sweater".count("o") => 0` and `"Sweater".count("e") => 2`.
We use this here to know, how often we have to take a look at `word` to get all those occurences of `c`.
```
pos = 0
```
Our startposition to look for `c` in `word`. Comes into use in the next loop.
```
for _ in range(occ):
```
For each occurence. As a continual number has no value for us here, we "discard" it by naming it `_`. At this point where `c` is in `word`. Yet.
```
pos = word.find(c, pos)
```
Oh. Look. We found `c`. :) `word.find(c, pos)` returns the index of the first occurence of `c` in `word`, starting at `pos`. At the beginning, this means from the start of the string => the first occurence of `c`. But with this call we already update `pos`. This plus the last line (`pos += 1`) moves our search-window for the next round to start just behind the previous occurence of `c`.
```
for r in md[c]:
```
Now you see, why we updated `mc` previously: we can easily iterate over it now (a `md[c].split(',')` on the old `md` would do the job as well). So we are doing the replacement now for each of the replacement-characters.
```
tmp = word[:pos] + r + word[pos+1:]
```
The actual replacement. We store it in `tmp` (for debug-reasons). `word[:pos]` gives us `word` up to the (current) occurence of `c` (exclusive `c`). `r` is the replacement. `word[pos+1:]` adds the remaining word (again without `c`).
```
newwords.append(tmp)
```
Our so created new word `tmp` now goes into our output-list (`newwords`).
```
pos += 1
```
The already mentioned adjustment of `pos` to "jump over `c`".
---
**Additional question from OP:** *Is there an easy way to dictate how many letters in the string I want to replace [(meaning e.g. multiple at a time)]?*
Surely. But I have currently only a vague idea on how to achieve this. I am going to look at it, when I got my sleep. ;)
```
words = ["Words", "Shirt", "Blouse", "Sweater", "multipleeee"]
md = {"e": "q,w", "a": "z"}
md = {k: v.split(',') for k, v in md.items()}
num = 2 # this is the number of replaces at a time.
newwords = []
for word in words:
newwords.append(word)
for char in md:
for r in md[char]:
pos = multiples = 0
current_word = word
while current_word.find(char, pos) != -1:
pos = current_word.find(char, pos)
current_word = current_word[:pos] + r + current_word[pos+1:]
pos += 1
multiples += 1
if multiples == num:
newwords.append(current_word)
multiples = 0
current_word = word
```
Content of `newwords`:
```
['Words', 'Shirt', 'Blouse', 'Sweater', 'Swqatqr', 'Swwatwr', 'multipleeee', 'multiplqqee', 'multipleeqq', 'multiplwwee', 'multipleeww']
```
Prettyprint:
```none
Words
Shirt
Blouse
Sweater
Swqatqr
Swwatwr
multipleeee
multiplqqee
multipleeqq
multiplwwee
multipleeww
```
I added `multipleeee` to demonstrate, how the replacement works: For `num = 2` it means the first two occurences are replaced, after them, the next two. So there is no intersection of the replaced parts. If you would want to have something like `['multiplqqee', 'multipleqqe', 'multipleeqq']`, you would have to store the position of the "first" occurence of `char`. You can then restore `pos` to that position in the `if multiples == num:`-block.
If you got further questions, feel free to ask. :) | Because you need to replace letters one at a time, this doesn't sound like a good problem to solve with pandas, since pandas is about doing everything at once (vectorized operations). I would dump out your DataFrame into a plain old list and use list operations:
```
words = DF.to_dict()["Words"].values()
for find, replace in reversed(sorted(mydict.items())):
for word in words:
occurences = word.count(find)
if not occurences:
print word
continue
start_index = 0
for i in range(occurences):
for replace_char in replace.split(","):
modified_word = list(word)
index = modified_word.index(find, start_index)
modified_word[index] = replace_char
modified_word = "".join(modified_word)
print modified_word
start_index = index + 1
```
Which gives:
```
Words
Shirt
Blousq
Blousw
Swqater
Swwater
Sweatqr
Sweatwr
Words
Shirt
Blouse
Swezter
```
Instead of printing the words, you can append them to a list and re-create a DataFrame if that's what you want to end up with. |
50,236,778 | *My understanding on `LiveData` is that, it will trigger observer on the current state change of data, and not a series of history state change of data.*
Currently, I have a `MainFragment`, which perform `Room` write operation, to change **non-trashed data**, to **trashed data**.
I also another `TrashFragment`, which observes to **trashed data**.
Consider the following scenario.
1. There are currently 0 **trashed data**.
2. `MainFragment` is the current active fragment. `TrashFragment` is not created yet.
3. `MainFragment` added 1 **trashed data**.
4. Now, there are 1 **trashed data**
5. We use navigation drawer, to replace `MainFragment` with `TrashFragment`.
6. `TrashFragment`'s observer will first receive `onChanged`, with 0 **trashed data**
7. Again, `TrashFragment`'s observer will secondly receive `onChanged`, with 1 **trashed data**
What is out of my expectation is that, item (6) shouldn't happen. `TrashFragment` should only receive latest **trashed data**, which is 1.
Here's my codes
---
TrashFragment.java
------------------
```
public class TrashFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
noteViewModel = ViewModelProviders.of(getActivity()).get(NoteViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
noteViewModel.getTrashedNotesLiveData().removeObservers(this);
noteViewModel.getTrashedNotesLiveData().observe(this, notesObserver);
```
MainFragment.java
-----------------
```
public class MainFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
noteViewModel = ViewModelProviders.of(getActivity()).get(NoteViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
noteViewModel.getNotesLiveData().removeObservers(this);
noteViewModel.getNotesLiveData().observe(this, notesObserver);
```
NoteViewModel .java
-------------------
```
public class NoteViewModel extends ViewModel {
private final LiveData<List<Note>> notesLiveData;
private final LiveData<List<Note>> trashedNotesLiveData;
public LiveData<List<Note>> getNotesLiveData() {
return notesLiveData;
}
public LiveData<List<Note>> getTrashedNotesLiveData() {
return trashedNotesLiveData;
}
public NoteViewModel() {
notesLiveData = NoteplusRoomDatabase.instance().noteDao().getNotes();
trashedNotesLiveData = NoteplusRoomDatabase.instance().noteDao().getTrashedNotes();
}
}
```
---
Code which deals with Room
--------------------------
```
public enum NoteRepository {
INSTANCE;
public LiveData<List<Note>> getTrashedNotes() {
NoteDao noteDao = NoteplusRoomDatabase.instance().noteDao();
return noteDao.getTrashedNotes();
}
public LiveData<List<Note>> getNotes() {
NoteDao noteDao = NoteplusRoomDatabase.instance().noteDao();
return noteDao.getNotes();
}
}
@Dao
public abstract class NoteDao {
@Transaction
@Query("SELECT * FROM note where trashed = 0")
public abstract LiveData<List<Note>> getNotes();
@Transaction
@Query("SELECT * FROM note where trashed = 1")
public abstract LiveData<List<Note>> getTrashedNotes();
@Insert(onConflict = OnConflictStrategy.REPLACE)
public abstract long insert(Note note);
}
@Database(
entities = {Note.class},
version = 1
)
public abstract class NoteplusRoomDatabase extends RoomDatabase {
private volatile static NoteplusRoomDatabase INSTANCE;
private static final String NAME = "noteplus";
public abstract NoteDao noteDao();
public static NoteplusRoomDatabase instance() {
if (INSTANCE == null) {
synchronized (NoteplusRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
NoteplusApplication.instance(),
NoteplusRoomDatabase.class,
NAME
).build();
}
}
}
return INSTANCE;
}
}
```
Any idea how I can prevent from receiving `onChanged` twice, for a same data?
---
Demo
----
I created a demo project to demonstrate this problem.
As you can see, after I perform write operation (Click on **ADD TRASHED NOTE** button) in `MainFragment`, when I switch to `TrashFragment`, I expect `onChanged` in `TrashFragment` will only be called once. However, it is being called twice.
[](https://i.stack.imgur.com/uLsLE.gif)
Demo project can be downloaded from <https://github.com/yccheok/live-data-problem> | 2018/05/08 | [
"https://Stackoverflow.com/questions/50236778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72437/"
] | I snatched Vasiliy's fork of your fork of the fork and did some actual debugging to see what happens.
>
> Might be related to the way ComputableLiveData offloads onActive() computation to Executor.
>
>
>
Close. The way Room's `LiveData<List<T>>` expose works is that it creates a `ComputableLiveData`, which keeps track of whether your data set has been invalidated underneath in Room.
```
trashedNotesLiveData = NoteplusRoomDatabase.instance().noteDao().getTrashedNotes();
```
So when the `note` table is written to, then the InvalidationTracker bound to the LiveData will call `invalidate()` when a write happens.
```
@Override
public LiveData<List<Note>> getNotes() {
final String _sql = "SELECT * FROM note where trashed = 0";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return new ComputableLiveData<List<Note>>() {
private Observer _observer;
@Override
protected List<Note> compute() {
if (_observer == null) {
_observer = new Observer("note") {
@Override
public void onInvalidated(@NonNull Set<String> tables) {
invalidate();
}
};
__db.getInvalidationTracker().addWeakObserver(_observer);
}
```
Now what we need to know is that `ComputableLiveData`'s `invalidate()` will *actually* refresh the data set, if the LiveData is *active*.
```
// invalidation check always happens on the main thread
@VisibleForTesting
final Runnable mInvalidationRunnable = new Runnable() {
@MainThread
@Override
public void run() {
boolean isActive = mLiveData.hasActiveObservers();
if (mInvalid.compareAndSet(false, true)) {
if (isActive) { // <-- this check here is what's causing you headaches
mExecutor.execute(mRefreshRunnable);
}
}
}
};
```
Where `liveData.hasActiveObservers()` is:
```
public boolean hasActiveObservers() {
return mActiveCount > 0;
}
```
So `refreshRunnable` actually runs only if there is an active observer (afaik means lifecycle is at least started, and observes the live data).
---
---
This means that when you subscribe in TrashFragment, then what happens is that your LiveData is stored in Activity so it is kept alive even when TrashFragment is gone, and retains previous value.
However, when you open TrashFragment, then TrashFragment subscribes, LiveData becomes active, ComputableLiveData checks for invalidation (which is true as it was never re-computed because the live data was not active), computes it asynchronously on background thread, and when it is complete, the value is posted.
So you get two callbacks because:
1.) first "onChanged" call is the previously retained value of the LiveData kept alive in the Activity's ViewModel
2.) second "onChanged" call is the newly evaluated result set from your database, where the computation was triggered by that the live data from Room became active.
---
So technically this is by design. If you want to ensure you only get the "newest and greatest" value, then you should use a fragment-scoped ViewModel.
You might also want to start observing in `onCreateView()`, and use `viewLifecycle` for the lifecycle of your LiveData (this is a new addition so that you don't need to remove observers in `onDestroyView()`.
If it is important that the Fragment sees the latest value even when the Fragment is NOT active and NOT observing it, then as the ViewModel is Activity-scoped, you might want to register an observer in the Activity as well to ensure that there is an active observer on your LiveData. | This is what happens under the hood:
```
ViewModelProviders.of(getActivity())
```
As you are using **getActivity()** this retains your NoteViewModel while the scope of MainActivity is alive so is your trashedNotesLiveData.
When you first open your TrashFragment room queries the db and your trashedNotesLiveData is populated with the trashed value (At the first opening there is only one onChange() call). So this value is cached in trashedNotesLiveData.
Then you come to the main fragment add a few trashed notes and go to the TrashFragment again. This time you are first served with the cached value in
trashedNotesLiveData while room makes async query. When query finishes you are
brought the latest value. This is why you get two onChange() calls.
So the solution is you need to clean the trashedNotesLiveData before opening
TrashFragment. This can either be done in your getTrashedNotesLiveData() method.
```
public LiveData<List<Note>> getTrashedNotesLiveData() {
return NoteplusRoomDatabase.instance().noteDao().getTrashedNotes();
}
```
Or you can use something like this [SingleLiveEvent](https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java)
Or you can use a MediatorLiveData which intercepts the Room generated one and returns only distinct values.
```
final MediatorLiveData<T> distinctLiveData = new MediatorLiveData<>();
distinctLiveData.addSource(liveData, new Observer<T>() {
private boolean initialized = false;
private T lastObject = null;
@Override
public void onChanged(@Nullable T t) {
if (!initialized) {
initialized = true;
lastObject = t;
distinctLiveData.postValue(lastObject);
} else if (t != null && !t.equals(lastObject)) {
lastObject = t;
distinctLiveData.postValue(lastObject);
}
}
});
``` |
34,388,514 | I've tried to solve my problem by googling, but every time someone has the same problem also has complicated code. I a noob and I have no idea why It keeps having an error called "TypeError: not all arguments converted during string formatting" Even though I tried converting some of the variables to int. (I'm probably solving it the wrong way). Can someone give a heads up without giving me the answer?
```
x = range(2, 20)
number = 0
y = raw_input()
flag = True
while flag == True:
for elem in x:
if y % elem == 0:
print elem
else:
flag = False
``` | 2015/12/21 | [
"https://Stackoverflow.com/questions/34388514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When you run docker using `-p 7180` and `-p 8888`, it will allocate a random port on your windows host. However, if you use -p 7180:7180 and -p 8888:8888, assuming those ports are free on the host, it will map them directly.
Otherwise you can execute `docker ps` and it will show you which ports it mapped the 7180 and 8888 to. Then in your host browser you can enter
```
http://192.168.99.100:<docker-allocated-port>
```
instead of
```
http://192.168.99.100:7180
```
If its all on your local machine, you shouldn't need the port forwarding. | I was just trying to spin up the Cloudera quickstart docker myself, and it turns out this seems to do the trick:
<http://127.0.0.1:8888>
Note the http, not https, and that I use 127.0.0.1 (or localhost)
Note that this assumes that the internal 8888 port is mapped to your 8888 port.
Suppose docker inspect yields something like
```
"8888/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "32769"
}
```
Then you would want
<http://127.0.0.1:32769> |
13,543,998 | I have been working on a rails app for a while now and want to recreate the model without going through all the migration stages (i.e. from scratch) now that I finally have a final design for how I want it to be built.
How do I do this without having to have to recreate my entire project? | 2012/11/24 | [
"https://Stackoverflow.com/questions/13543998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1121806/"
] | If I am understanding correctly about what you want,
```
rake db:reset
```
will recreate your database from your db/schema.rb. Make sure that you have run all the migrations before running it.
However, rails manage the database using the migration files in db/migrate. Everytime you make changes to the database you will need to do it through them or you will get into trouble. These files should be retained and whenever you deloy your app to a new machine, running db:migrate should be fine. | I'm not sure if this is what you want, but you could delete all your migration files and copy everything from db/schema.rb to a new migration. |
2,608,201 | I'm not sure how to handle the trig functions with different arguments when computing this limit using L'Hospital's rule.
$$\lim\_{x \rightarrow 0} \frac {x^2\cos(\frac {1} {x})} {\sin(x)}.$$
I have come up with the correct numerical answer via a different method, but am unsure if the logic would hold true for all cases (maybe I arrived at the correct answer by chance).
Here is my working:
>
> Let $g(x)=x^2\cos(\frac 1 x)$ and $h(x) = \frac 1 {\sin x} = \csc x$.
>
>
> We know that the following holds true for all $x$: $$-1 \le \cos (\frac 1 x) \le 1$$
> Since $x^2 \ge 0$ for all x:
> $$-x^2 \le x^2\cos (\frac 1 x) \le x^2$$
> Taking limits as $x \rightarrow \infty$ gives:
> $$ \lim\_{x\rightarrow 0}(-x^2)\le \lim\_{x\rightarrow 0}(x^2\cos (\frac 1 x)) \le \lim\_{x\rightarrow 0}(x^2)$$
> By the sandwich rule (or squeeze theorem):
> $$ 0 \le \lim\_{x\rightarrow 0}(x^2\cos (\frac 1 x)) \le 0$$
> $$ \Rightarrow \lim\_{x\rightarrow 0}(x^2\cos (\frac 1 x)) $$
> And hence, due to the algebra of limits:
> $$\lim\_{x \rightarrow 0} \frac {x^2\cos(\frac {1} {x})} {\sin(x)} = 0.$$
>
>
> | 2018/01/16 | [
"https://math.stackexchange.com/questions/2608201",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/332245/"
] | $$
\frac {x^2\cos\frac 1 x} {\sin x} = x\cdot \frac x {\sin x} \cdot \cos\frac 1 x
$$
Now use the fact that $-1 \le \cos \frac 1 x \le 1$ and $x\to0$ and one further fact not mentioned in your question:
$$
\frac x {\sin x} \to 1 \text{ as } x\to0.
$$
Without that last fact or something else other than what's in your question, you haven't dealt with the fact that $\sin x \to0.$ | Use *asymptotic analysis*: you know $\sin x \sim\_0 x$, hence $\dfrac{x^2}{\sin x} \sim\_0 \dfrac{x^2}x=x $.
Furthermore, $\Bigl\vert\cos\dfrac1x \Bigr\vert \le 1$, so
$$\smash{\dfrac{x^2\cos\dfrac1x}{\sin x}} = O(x)\to 0.$$ |
58,336 | Noise canceling headphones are quite expensive (up to 300 USD) compared to normal headphones, but can boost productivity by creating a sound isolation in noisy environments. Would it be ethically justifiable to buy those for non-research purpose (i.e., it's not needed for experiments)?
On one hand, I feel like good office furniture like chairs and desks are fully justifiable for the well-being and productivity of the research team members. But, this argument seems like a slippery slope, since I could also say that having a high-end espresso machine or special dark chocolate bars also could boost research productivity. In a corperate environment, I would have no problem in purchasing some of these, and I would consider them to be ethical, but in an academic environment, I find it difficult to find the ethical boundary since the funds are intended for research.
The fact that noise canceling headphones will likely be used for listening to music both while working on research and not, especially during travel, also adds to my ambivalence. But then research purpose laptops are also used this way often, and I don't have a problem with that.
**EDIT**: I'm not looking for alternate solutions. Just an ethical evaluation. It seems there's no real answer to this question. I appreciate everybody's response. I will choose the most balanced response as an answer but you should really read all the answers. | 2015/11/17 | [
"https://academia.stackexchange.com/questions/58336",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/386/"
] | Anything could be ethically justified in the right situation. If the only research scientist that has the ability to unlock the science that provides a way to defeat the evil empire from destroying the universe is rendered incompetent unless availed of free prostitution services to liberate his imagination through sexual release, then free prostitutes would be a legitimate expense item in the budget. If saving the universe wasn't a legitimate goal of the research, providing free prostitutes would likely be construed as defrauding the funds provider and, depending upon the prevailing law, subject the funds administrator to criminal prosecution for violation of the funding terms or other laws.
So, when attempting to determine whether to buy something with earmarked funds, one should first run the purchase through a series of exclusionary gates:
1. Determine what is formally approved in writing. If the funds are acquired through a grant directly from a federal government agency granter, the applicable rules regarding expenditures might be found in the terms attending the offering, the administrative code of the granter agency, and the Office of Management and Budget. If you want a horse's mouth answer, contact the entity that will audit the grant. Grant offerings can provide wide latitude in making expenses but take it from someone who has been there, the auditors, post expense, can deny the expense and backcharge the expense even when it appears to have been totally in compliance with the goals of the grant. Auditors, probably moreso when acting as a third party contractor for the granter agency, are likely to find at least one thing wrong with everything they audit so that it looks like they're doing their job. In other words, government auditors sometimes function like cops with a quota. The more an expense formally adheres to written guidelines, the less likely they'll declare it inappropriate. Novel interpretations of the rules that seem legitimate in light of the overall goal might be logically interpreted as appropriate by most everyone but are still more likely to be denied. Auditors don't enjoy much imagination when it comes to entertaining unique ways of interpretation, even when same is done in perfectly good faith and in the best interest of obtaining the outcome envisioned by the granter.
If the funds are from a government agency but funneled through another such as a state agency, then the state laws and administrative codes might have to be referenced as well. If the state law conflicts with the federal law, their exists potential for denying expenses as a result. Chargebacks are chargebacks regardless of whether your right or wrong in discharging your administrative duties.
2. If the funds are provided in-house, consult up the chain of command for formal written guidelines and other guidance. There may be formal guidelines already in place and available to the institution's employees, contractors, and/or others who spend, administer, or invoice the institution's funds or those of it's funding sources. Once again, the auditors will likely be the final authority on what is considered appropriate. If they're guidance is available without rustling any feathers in the chain of command, it would likely provide the best source of information about how to make a decision. If you do contact them, you might be the first to ever take the time to do so so don't be surprised if they're surprised at your call. Also, if you discover that NOBODY really has an idea about the policy, including the auditors, then document that as well so that you can show that you made a good faith effort to discover the truth. The risk is that if you dig too deeply and find that NOBODY is doing it right, you might make some of the higher up incompetents uncomfortable with your questions. You'll have to use your own judgment about whether it's safe to poke around the place with questions that could make somebody look bad.
3. Take it from someone who knows, any item that has utility outside the work environment is more likely to eventually come up missing. Employees tend to take things home with them to work after hours, an admirable behavior when done in compliance with the rules. Same tend to forget to bring things back to work sometimes, a less admirable behavior. The more utility the item has outside the workplace, and the more expensive the item is, the more likely it is to become lost in the name of enhancing productivity.
4. When in doubt, err on the side of caution, or not. I remember Bill Gates missing an important speaking engagement because he got stuck in a traffic jam. The blame was rolled downhill to those attending to the details of delivering him to same on time. They were chastised by the higher ups for not renting a jet helicopter to fetch him out of the traffic jam and ensure his timely arrival at the speaking engagement. Likely, had Gates managed to barely arrive on time by ground transportation, anyone suggesting wild spending on a helicopter to avert a potential disaster would have been chastised as financially irresponsible. If the research is successful, expenses will more likely be viewed as appropriate. If unsuccessful, you might be called onto the carpet for buying rubber bands.
Only you have a feel for the terrain in your particular situation so you might have to go on instinct, but then again, that's why you make the big bucks, right? Just remember to document your good logic for the expenditure so that your ready for a fight if it is called into question. If your prepared to defend it, any expenditure has a better chance of approval than one that you are at a loss for words to explain. If you rely on the assertions of others to justify the expenditure, document who they are, what they said, and when. If it's a career life or death, you might even tape record it, if and when legal to do so. When it hits the fan, people that told you it was ok to do it the wrong way will forget they ever had a conversation with you, assuming they remember you at all. | Let me answer your question in an extreme case:
Some labs purchase this type of headphones, at high prices probably. Because they can't do work without it.
Their experiments require a step of long time sonication which is really harmful to human ears. Therefore, researchers in order to protect themselves have to wear these headphones just like how people wear gloves.
I guess my example can avoid the ethical controversies, even if some people do use it to concentrate on work while they propose to buy it for the sake of protection against sonication noise.
And that's how some labs use their money, whether you like it or not.
Current situation is that a lot of labs and institutes can find a lot of reasonable proposals to get what they need, though, for another project.
And, sadly, that's how labs run sometimes: you use your current excuses/publications to ask for what you need for another unrelated project, the result of which will in turn be used to get funding for another one.
If someone else were standing in your shoes, they could probably get the headphone in the name of sonication, and do good work, and produce more scientific values than the headphone they asked for. |
186,942 | I have this script:
```
select name,create_date,modify_date from sys.procedures order by modify_date desc
```
I can see what procedures were modified lately.
I will add a "where modify\_date >= "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 matching) stored procedures
Can i do this somehow?
thanks
---
ok. i have the final version:
<http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html>
you guys helped a lot
thanks | 2008/10/09 | [
"https://Stackoverflow.com/questions/186942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26472/"
] | No cursor necessary (modify as desired for schemas, etc):
```
DECLARE @dt AS datetime
SET @dt = '10/1/2008'
DECLARE @sql AS varchar(max)
SELECT @sql = COALESCE(@sql, '')
+ '-- ' + o.name + CHAR(13) + CHAR(10)
+ 'DROP PROCEDURE ' + o.name + CHAR(13) + CHAR(10)
+ 'GO' + CHAR(13) + CHAR(10)
+ m.definition + CHAR(13) + CHAR(10)
+ 'GO' + CHAR(13) + CHAR(10)
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS o
ON m.object_id = o.object_id
INNER JOIN sys.procedures AS p
ON m.object_id = p.object_id
WHERE p.modify_date >= @dt
PRINT @sql -- or EXEC (@sql)
``` | This is best done in a more suitable language than SQL. Despite its numerous extensions such as T-SQL, PL/SQL, and PL/pgSQL, SQL is not the best thing for this task.
Here is a link to a similar question, and my answer, which was to use SQL-DMO or SMO, depending on whether you have SQL 2000 or 2005.
[How to copy a database with c#](https://stackoverflow.com/questions/174515/how-do-you-copy-a-ms-sql-2000-database-programmatically-using-c#175062) |
5,790,180 | I search for a word and I get the results with facet as follows:
```
<lst name="itemtype">
<int name="Internal">108</int>
<int name="Users">73</int>
<int name="Factory">18</int>
<int name="Supply Chain Intermediaries">6</int>
<int name="Company">1</int>
<int name="Monitor/Auditor firm">0</int>
</lst>
```
Then I wrote the condition like `fq=itemtype:Factory`. I get the results. But I am not getting the results for `fq=itemtype:Supply Chain Intermediaries`.
I am thinking the problem rests with the spaces in the condition (Supply Chain Intermediaries). I tried with `urlencode` (to replace spaces with `%20`) also. But it's of no use. Can you guys please help me to solve this?
### Update:
For single value it is working fine. I build the query like this:
```
http:localhost:8080/solr/select/?q=adidas&version=2.2&indent=on&facet=on&start=0&rows=20&fq={!raw f=itemtype}Supply Chain Intermediaries
```
But i need to write for multiple values. The original Query with out **raw** is as follows
```
http://localhost/solr/select/?q=adidas&version=2.2&indent=on&facet=on&start=0&rows=20&fq=(itemtype:Company itemtype:Supply Chain Intermediaries)
```
Can you guys please help me to solve this. | 2011/04/26 | [
"https://Stackoverflow.com/questions/5790180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644882/"
] | How is your itemtype field analysed?
If it is of type string , then use:
```
fq=itemtype:"Supply Chain Intermediaries"
```
Otherwise you can also try:
```
fq=itemtype:(Supply Chain Intermediaries)
```
Assuming `OR` is the default operator in your config and `text` is the default search field, your query will get translated to:
```
fq=itemtype:Supply OR text:(Chain Intermediaries)
```
Chain and Intermediaries are searched against default search field. | I have tried different solutions mentioned here, but none of them worked. However I solved it like this:
```
fq=itemtype: *Supply\ Chain\ Intermediaries*
```
Here space will be escaped with `\`
The above string will match with the strings `Lorem Supply Chain Intermediaries Ipsum`
If you are having a word starts with `Supply Chain Intermediaries Ipsum`
then just give
```
fq=itemtype: Supply\ Chain\ Intermediaries*
``` |
60,170,262 | I am solving this problem:
>
> Given a string str containing alphanumeric characters, calculate sum
> of all numbers present in the string.
>
>
>
**Input:**
The first line of input contains an integer T denoting the number of test cases. Then T test
cases follow. Each test case contains a string containing alphanumeric characters.
**Output:**
Print the sum of all numbers present in the string.
**Constraints:**
>
> 1 <= T<= 105
>
>
> 1 <= length of the string <= 105
>
>
>
Example:
**Input:**
```
4
1abc23
geeks4geeks
1abc2x30yz67
123abc
```
**Output:**
```
24
4
100
123
```
I have come up with the following solution:
```
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++)
{
if (isdigit(a[i])){
while(isdigit(a[i])){
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
```
This code is working fine.
BUT if loop termination condition is changed from **i < l** to **a[i]!='\0'**, then code doesn't work. Why? | 2020/02/11 | [
"https://Stackoverflow.com/questions/60170262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820554/"
] | I would loop backwards over the string. No nested loops. Just take the 10s exponent as you move left
You have the length of the string, so there should be no reason to check for NUL char yourself
(untested code, but shows the general idea)
```
#include <math.h>
l=strlen(a);
int exp;
exp = 0;
for(i = l-1; i >= 0; i--)
{
if (isdigit(a[i])) {
rev = a[i]-48; // there are better ways to parse characters to int
rev = (int) pow(10, exp) * rev;
sum += rev; // only add when you see a digit
} else { exp = -1; } // reset back to 10^0 = 1 on next loop
exp++;
}
```
Other solutions include using regex to split the string on all non digit characters, then loop and sum all numbers | You will have to change the logic in your while loop as well if you wish to change that in your for loop condition because it's quite possible number exists at the end of the string as well, like in one of your inputs `1abc2x30yz67`. So, correct code would look like:
**Snippet:**
```
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i]!='\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
```
On further inspection, you need the condition of **i < l** anyways in your while loop condition as well.
```
while(i < l && isdigit(a[i])){
```
**Update #1:**
To be more precise, the loop `while(isdigit(a[i])){` keeps going till the end of the string. Although it does not cause issues in the loop itself because `\0` ain't a digit, but `a[i] != '\0'` in the for loop condition let's you access something beyond the bounds of length of the string because we move ahead 1 more location because of `i++` in the for loop whereas we already reached end of the string inside the inner while loop.
**Update #2:**
You need an additional check of `a[i] == '\0'` to decrement `i` as well.
```
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i] != '\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
if(a[i] == '\0') i--; // to correctly map the last index in the for loop condition
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
```
**Update #3:**
You can completely avoid the while loop as well as shown below:
```
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100005];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++) {
if (isdigit(a[i])){
rev = rev * 10 + (a[i]-48);
}else{
sum += rev;
rev = 0;
}
}
printf("%d\n",sum + rev); // to also add last rev we captured
}
return 0;
}
``` |
4,729 | I'm a young member (as of April 15, 2015 I've been here for 45 days) and I've noticed a lot of questions that get closed for being opinion based or off topic.
This is especially true with [shopping questions](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/).
Looking at the newest 30 questions, 10 of them are low score, on hold, or marked as duplicate.
Looking at those first 30 questions, there aren't too many people with new accounts (< 100) who have non-closed questions.
This makes me think that we may be scaring off new users from ever joining or contributing because they don't want to have their question rejected.
---
Now, I see nothing wrong with flagging those sorts of questions. All of the reasons given as to why we should do so are sound (in my opinion).
What I think the problem is looking at the newest question page and seeing all of the negative numbers and flags makes possibly good new users not want to post.
These are my thoughts and I'd like to hear others.
---
I do think we might be able to fix this problem rather easily. That is, if we see a poster with a reputation less than 1,000 or some other constraint and they tag it as [equipment-recommendation](https://photo.stackexchange.com/questions/tagged/equipment-recommendation) or [lens-recommendation](https://photo.stackexchange.com/questions/tagged/lens-recommendation) that we pop a banner and say:
"Hold on, we do not give shopping advice, are you sure this isn't that type of question?"
and allow the users to say
"Yes, this is not a shopping question. I've done my homework."
It might be tedious for beginners, but it might make the newest question page look a lot less daunting.
---
### \*\*2015/04/17 EDIT\*\*
[mattdm](https://photo.meta.stackexchange.com/users/1943/mattdm) as recommended starting a [photo-shopping](https://photo.meta.stackexchange.com/q/4732/38156) SE. It might be worth while checking it out. I've said my piece on it; however, I'm very glad that I'm not the only one who realizes this problem.
I do think we can solve this, but I just don't know how. | 2015/04/15 | [
"https://photo.meta.stackexchange.com/questions/4729",
"https://photo.meta.stackexchange.com",
"https://photo.meta.stackexchange.com/users/38156/"
] | For what it's worth, I'm probably what you'd call a new member and a relative newcomer to serious photography. I've asked a few questions and got valuable actionable answers on a level that I could understand. I've also learned a great deal from the other questions and answers addressing things that I wanted to learn and also some things that I didn't know that I needed to know. I've seen the closed questions, the off topic replies etc. and have not found them objectionable or offputting at all. This keeps the questions and answers valuable to a community and a great source for focused answers. | >
> This makes me think that we may be scaring off new users from ever joining or contributing because they don't want to have their question rejected.
>
>
>
An alternative interpretation is that the people who come here to ask shopping questions are coming for the wrong reason in the first place. Finding that this site isn't what they're looking for, they move on to other sites that are more in line with what they want. There's nothing wrong with this -- we don't need to be all things to all people, and we don't need to feel badly if not everyone decides to join the Photo.SE community.
Questions like yours pop up *all the time* on StackExchange meta sites. Search meta.stackoverflow.com, for example, and you'll find lots of questions like [*Why do people scare off new users?*](https://meta.stackoverflow.com/q/253100/643383). It's certainly good to keep the community friendly and inviting, but it's a two-way street: new users also need to invest a little (and it really doesn't take much) effort to ask good questions, find out about community standards, etc. I think Photo.SE does a pretty good job of being friendly (you stayed, right?), and I don't think unclear standards are a big problem here. |
288,388 | I know that 1.11 /fill and /setblock use block data instead of block data. However, when I try to fill an area with sticky pistons facing up, it days that my data values are incorrect. I've tried the following with various capitalizations:
```
/fill x1 y1 z1 x2 y2 z2 sticky_piston {facing:up}
/fill x1 y1 z1 x2 y2 z2 sticky_piston {direction:up}
/fill x1 y1 z1 x2 y2 z2 sticky_piston direction:up
```
From what I've read, {direction:up} or perhaps {Direction:up} should be correct. What am I missing? | 2016/10/17 | [
"https://gaming.stackexchange.com/questions/288388",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/161585/"
] | Block states should be in the format `variable=value`:
```
/fill x1 y1 z1 x2 y2 z2 sticky_piston facing=up
```
Block states are also still just an alternative to numeric data values. You can use data values if you wish:
```
/fill x1 y1 z1 x2 y2 z2 sticky_piston 1
```
From the curly brackets (`{`,`}`) and colon (`:`), it looks like you may be getting confused with NBT, which is separate from data values/block states. | The way that you would do this would be /fill x1 y1 z1 x2 y2 z2 sticky\_piston[facing=up]. Curly brackets and colons aren't for NBT data these days. If you want to learn more about /fill, here is a video that might help you: |
10,357,266 | I am displaying information as a checkbox with `ThreeState` enabled, and want to use a nullable boolean in simplest way possible.
Currently I am using a nested ternary expression; but is there a clearer way?
```
bool? foo = null;
checkBox1.CheckState = foo.HasValue ?
(foo == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
```
*\* Note that the checkbox and form is read-only.* | 2012/04/27 | [
"https://Stackoverflow.com/questions/10357266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161052/"
] | That's how I would do it.
I would add an extension method to clean it up a bit.
```
public static CheckState ToCheckboxState(this bool booleanValue)
{
return booleanValue.ToCheckboxState();
}
public static CheckState ToCheckboxState(this bool? booleanValue)
{
return booleanValue.HasValue ?
(booleanValue == true ? CheckState.Checked : CheckState.Unchecked) :
CheckState.Indeterminate;
}
``` | More clear is an arguable statement. For example I could say that this is more clear.
```
if(foo.HasValue)
{
if(foo == true)
checkBox1.CheckState = CheckState.Checked;
else
checkBox1.CheckState = CheckState.Unchecked;
}
else
checkBox1.CheckState = CheckState.Indeterminate;
```
Another option would be to create a method just for this:
```
checkBox1.CheckState = GetCheckState(foo);
public CheckState GetCheckState(bool? foo)
{
if(foo.HasValue)
{
if(foo == true)
return CheckState.Checked;
else
return CheckState.Unchecked;
}
else
return CheckState.Indeterminate
}
```
However I like your code. |
68,820,920 | I am trying to use participant record IDs on the y axis in my ggplot. The record IDs skip around (e.g. 1, 3, 10, 100). My question is three-fold:
1. I'd like to display each ID on the y axis, but when I convert to `as.numeric(as.character(record_id)))`, the axis is ordered but doesn't take into account that the record IDs skip around.
2. If I convert to as.character, it's the right concept but I can't figure out how to sort so it doesn't appear as 1, 10, 100, 3, even when using `str_order`.
So far, using `ggplot(sincevax_reshape, aes(x=value, y=as.character(sort(as.numeric(record_id)))))` has gotten me the look of the y axis but not the correct sort.
3. Once I get the record IDs to be properly sorted on the Y axis, is there a way to increase the vertical spacing between each so the Y axis isn't so crowded/clustered?
```
record_id variable value
6 10 Sample -182
7 11 Sample -233
14 21 Sample -189
16 23 Sample -232
17 24 Sample -214
21 30 Sample -197
23 32 Sample -133
24 33 Sample -203
28 39 Sample -165
29 41 Sample -226
1105 3 Today 106
1106 4 Today 163
1107 6 Today 79
1108 7 Today 113
1109 9 Today 133
1110 10 Today 177
1111 11 Today 118
```
End goal is something like this without all the blank space at the top:
[](https://i.stack.imgur.com/b335K.png) | 2021/08/17 | [
"https://Stackoverflow.com/questions/68820920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16368087/"
] | You could try converting the numbers to factors:
```r
library(ggplot2)
df$record_id <- factor(df$record_id, levels = df$record_id)
ggplot(df, aes(x = value, y = record_id)) +
geom_col()
```

Created on 2021-08-17 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)
**Data used**
```r
df <- structure(list(record_id = c(10L, 11L, 21L, 23L, 24L, 30L, 32L,
33L, 39L, 41L), variable = c("Sample", "Sample", "Sample", "Sample",
"Sample", "Sample", "Sample", "Sample", "Sample", "Sample"),
value = c(-182L, -233L, -189L, -232L, -214L, -197L, -133L,
-203L, -165L, -226L)), class = "data.frame", row.names = c("6",
"7", "14", "16", "17", "21", "23", "24", "28", "29"))
``` | One option in the spirit of your first proposal might be to assign your nonconsecutive numeric IDs a rank based on their value, e.g.:
```
df$record_id_rank <- rank(df$record_id)
```
Note that rank will generate float values in the case of duplicate IDs, which it sounds like you may have in your long data. In that case, you can reduce ties to their integer:
```
df$record_id_rank <- floor(df$record_id_rank)
```
Then, you can plot `df$record_id_rank` on your y-axis as others have above. (If you want the axis labels to the real IDs, not the sequential numbering, I believe you can map within ggplot.) |
64,872 | I can't figure out how can I get event. I was trying with "contract.NewVoting().watch{}" but it says that watch is not a function.
I found out that watch has been removed and there is EventEmitter instead.
Here is a part of my not working yet code:
Solidity:
```
contract AddNewVotingBuilder is BaseBuilder
{
function build()
external
{
emit NewVoting(address(new AddNewVoting()));
}
}
```
Truffle:
```
console.log("building add voting contract...");
await deployer.deploy(AddNewVotingBuilder);
let builder = await BaseBuilder.at(AddNewVotingBuilder.address);
await builder.build(); // doesn't work even without await
await builder.NewVoting()
.on('data', event => console.log(event));
```
It completely ignores the code and doesn't show the event.
How can I make it working? | 2019/01/01 | [
"https://ethereum.stackexchange.com/questions/64872",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/47855/"
] | If you're on version 5 of Truffle you can use `getPastEvents()` from Web3js :
for example something like:
`await builder.getPastEvents( 'NewVoting', { fromBlock: 0, toBlock: 'latest' } )`
ref: <https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#getpastevents> | Listening for events is something you do in the background, so you should make sure you are watching for the events before calling the function that emits the event.
Change the code to:
```js
console.log("building add voting contract...");
await deployer.deploy(AddNewVotingBuilder);
let builder = await BaseBuilder.at(AddNewVotingBuilder.address);
builder.NewVoting()
.on('data', event => console.log(event));
await
builder.build();
``` |
11,253,329 | I'm trying to compile a *very* big, multi-project Android project using command line Ant. I was originally using Ant 1.8.3, but have since upgraded to 1.8.4 (in vain, it turns out). While I do have Eclipse installed (Indigo, updated today), the nature of this project precludes using Ant from within Eclipse for this.
The code seems to generate just fine, but when it gets to the "dex" phase of the operation it gets one of two errors, depending on my `ANT_OPTS`: "GC Overhead Limit Exceeded" or "Java Heap Space".
I googled and checked Stack. After finding various links (c.f. [here](https://www.jfire.org/modules/phpwiki/index.php/Development%20Troubleshooting), [here](http://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html), [this Stack question](https://stackoverflow.com/questions/11148947/dojo-1-7-build-out-of-memory-errors), and [this stack question as well](https://stackoverflow.com/questions/2288463/java-out-of-heap-space-error)), I modified my Ant options. (Many links cover what happens when this happens executing the Java code; my problem is actually in the Ant process that creates the Android APK for upload).
My `ANT_OPTS` environment variable is currently:
```
-Xms4g -Xmx4g -Xmn256m -XX:PermSize=256m -XX:MaxPermSize=1024m -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled -XX:ParallelGCThreads=8
```
I tried turning off the GC Overhead Limit altogether using `-XX:-UseGCOverheadLimit`
, but all that does is give me a Java Heap Space error instead of the GC Overhead Limit error. I've asked my co-workers about this, but they're also out of ideas.
Oh, one more "detail": I can use Eclipse to compile and load the project, and that seems to work "just fine"; however, the sheer number of projects required for this "meta-project" suggests that I try to get the Ant script working.
**System Info:**
* OS: Windows 7 64 bit
* Java: Sun, 1.6, 64 bit
* Physical Memory: 8Gb
* Android: SDK Tools: R20; Platform Tools: R12 (Updated today, 28 Jun)
Is there something else I can do? Another keyword to search for? Someplace else to look? | 2012/06/28 | [
"https://Stackoverflow.com/questions/11253329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/584746/"
] | A partial answer to this one. Thanks goes to the current respondents, who helped me track this down.
There are, apparently, *two* (possibly three?) different places where the Java VM opts need to be changed, depending on exactly where the error occurs. In this case, the `ANT_OPTS` are *not* getting passed to Dex.
I was able to solve the error by editing the DX batch file, changing:
```
set defaultXmx=-Xmx1024M
```
to
```
set defaultXmx=-Xmx4096M
```
The **Obvious However**: I should never need to change the dx batch file. Anyone happen to know the "right" way to change the Java Options being passed to Dex by Ant? | Watch out for wrong directories, invalid symbolic links, or missed files. For example, if your build.xml relies on a symbolic link that points to a folder that does not exist, the “GC Overhead Limit Exceeded” error may be triggered when in reality it doesn't has nothing to do with memory or garbage collection issue. |
67,154,325 | I have a YAML file that I need to iterate and return a specific value for a variable, I am unable to use jq so the only available tool I have is bash. The YAML file looks like this:
```
abc:
NAME: Bob
OCCUPATION: Technician
def:
NAME: Jane
OCCUPATION: Engineer
```
YAML keys are known and will be iterated over, but say I want to get key `abc` `OCCUPATION` value of `TECHNICIAN`, through googling I managed to construct an awk statement that gives what I want, but it seems rather convoluted. Is there a more elegant way to write this out?
Current implementation is
```
> awk 'BEGIN{OFS=""} /^[^ ]/{ f=/^abc:/; next } f{ if (sub(/:$/,"")) abc=$2; else print abc,$1 $2}' test.yml| grep "OCCUPATION:" | cut -d':' -f2
Technician
```
If I could use `jq` it would have been much simpler but alas, I am stuck with base bash! | 2021/04/18 | [
"https://Stackoverflow.com/questions/67154325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3674993/"
] | This answer is also a bit convoluted, but I can't think of anything simpler. With GNU sed:
```
sed -n '/abc/,/^.*OCCUPATION/{s/.*OCCUPATION\(.*\):\ \(.*\)/\2/p}' test.yaml
```
Explanation: Find the lines between "abc" and "OCCUPATION" (lines 1 to 3) then from the OCCUPATION line, print the second captured group (the value "Technician") and don't print anything else.
*This works regardless of the number of abc elements, but if there is no OCCUPATION value for abc, this will print the next persons's OCCUPATION (in this case, "Engineer") without any warning/error.*
For BSD sed:
```
sed -n '/abc/,/^.*OCCUPATION/ s/.*OCCUPATION\(.*\):\ \(.*\)/\2/p' test.yaml
``` | With `awk` you can try this:
```
awk -F'[[:blank:]]+' '$1 == "" {if (s == "abc:" && $2 == "OCCUPATION:") print $3; next} {s=$1}' file
Technician
```
or the two values:
```
awk -F'[[:blank:]]+' '$1 == "" {if (s ~ /^(abc:|def:)$/ && $2 == "OCCUPATION:") print $3; next} {s=$1}' file
Technician
Engineer
``` |
26,728,022 | Given an array of objects, what is the best way to find the object with a particular key in JS?
Using jQuery and underscoreJS is fine. I'm just looking for the easiest / least code answer.
**Example:**
An array of objects, where each object has a "name". Find the object with a particular "name".
`var people = [{name: "A"}, {name: "B"}, {name: "C"}];`
**My current solution:**
Pass in the array, the key (e.g. "name"), and the value (e.g. "C").
```
function getObject(myArray, searchKey, searchValue) {
myArray.forEach(function(element){
if (element[searchKey] == searchValue) {
return element;
}
});
}
``` | 2014/11/04 | [
"https://Stackoverflow.com/questions/26728022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1001938/"
] | You should go with [grep](http://api.jquery.com/jquery.grep/) of jQuery
```
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
var obj1= jQuery.grep(people,function(n,i){return (n.name=='A')})
``` | I'm surprised not to find the obvious answer here, so: To do that with Underscore, you'd use [`_.find`](https://underscorejs.org/#find):
```
function getObject(myArray, searchKey, searchValue) {
return _.find(myArray, function(entry) { return entry[seachKey] === searchValue; });
}
```
You don't need Underscore for this, though; JavaScript's array type has `find` (as of ES5):
```
function getObject(myArray, searchKey, searchValue) {
return myArray.find(function(entry) { return entry[searchKey] === searchValue; });
}
```
As of ES2015+, you can make it more concise with an arrow function and destructuring:
```
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
```
Live example of that last one:
```js
function getObject(myArray, searchKey, searchValue) {
return myArray.find(({[searchKey]: value}) => value === searchValue);
}
const people = [{name: "A"}, {name: "B"}, {name: "C"}];
console.log(getObject(people, "name", "C"));
``` |
70,318 | >
> Now faith is **the substance** of things hoped for, the evidence of
> things not seen. (Hebrews 11:1, KJV)
>
>
> ἕστιν δὲ πίστις ἐλπιζομένων **ὑπόστασις** πραγμάτων ἔλεγχος οὐ
> βλεπομένων (TR)
>
>
>
What is this "substance" (ὑπόστασις) of things hoped for? If something is "hoped for," it seems it would be something entirely unmaterialized, unrealized, and intangible. How could it have any "substance"? | 2021/10/22 | [
"https://hermeneutics.stackexchange.com/questions/70318",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/42955/"
] | I agree that the Latin meaning of "substance" is closest to the Greek ὑπόστασις, but the English word has a somewhat different meaning from the Latin.
BDAG might be helpful here. That lexicon gives this meaning and comment:
>
> (1) **the essential or basic structure/nature of an entity,
> *substantial nature, essence, actual being, reality*** ... (b) of things: among the meanings that can be authenticated for Heb 11:1 a
> strong claim can be made for ***realization*** ... in faith hoped for
> become realized, or things hoped for take on (see 3, and 4
> below) reality ...
>
>
>
Among the modern versions, the most popular appears to be:
>
> Now faith is the **assurance** of things hoped for ...
>
>
>
This is consistent with the material in BDAG. | Elisha's servant had an interesting experience in 2 Kings 6:
>
> 15 When the servant of the man of God got up and went out early the next morning, an army with horses and chariots had surrounded the city. “Oh no, my lord! What shall we do?” the servant asked.
>
>
>
The servant saw the physical army of the king of Aram. Their mission was to capture Elisha.
>
> 16 “Don’t be afraid,” the prophet answered. “Those who are with us are more than those who are with them.”
>
>
>
Elisha saw something that his servant did not see. A greater army was protecting them. They were invisible to the servant but visible to Elisha. In any case, they were real.
>
> 17 And Elisha prayed, “Open his eyes, Lord, so that he may see.” Then the Lord opened the servant’s eyes, and he looked and saw the hills full of horses and chariots of fire all around Elisha.
>
>
>
Now, the servant saw the reality.
>
> 18 As the enemy came down toward him, Elisha prayed to the Lord, “Strike this army with blindness.” So he struck them with blindness, as Elisha had asked.
>
>
>
There were no conventional physical fights between the two armies. The job of the heavenly army was to strike the Aramean soldiers with blindness.
This was a miracle. An act from the heavenly realm caused a result in the physical realm.
Now, let's head for the NT, Hebrews 11:
>
> 1 Now faith is the substance of things hoped for, the evidence of things not seen.
>
>
>
Faith is this physically invisible substance that supports the things hoped for.
We can't see it physically. Nevertheless, it is there and it is real. It may even have mass :)
This is similar to the concept of [dark matter](https://starchild.gsfc.nasa.gov/docs/StarChild/universe_level2/darkmatter.html):
>
> Dark matter is composed of particles that do not absorb, reflect, or emit light, so they cannot be detected by observing electromagnetic radiation. Dark matter is material that cannot be seen directly. We know that dark matter exists because of the effect it has on objects that we can observe directly.
>
>
> |
23,345,355 | i have this multiple checkbox.
```
<div ng-repeat="setting in settings">
<input type="checkbox" name="setting.name" ng-model="setting.value">{{setting.name}}
```
and in the controller
```
$scope.settings = [{
name: 'OrderNr',
value: ''
}, {
name: 'CustomerNr',
value: ''
}, {
name: 'CatalogName',
value: ''
}, {
name: 'OrderDate',
value: ''
}, {
name: 'OrderState',
value: ''
}];
```
when i click the save button, i call this function for store data in local storage
```
$scope.saveSetting = function() {
var json = angular.toJson($scope.settings);
localStorageService.add('settings',json);
};
```
how can i keep my settings when i reload the page? | 2014/04/28 | [
"https://Stackoverflow.com/questions/23345355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3374467/"
] | What about using $cookies.
Have a look at [angularjs docs](https://docs.angularjs.org/api/ngCookies/service/%24cookies)
Basically all you need to do is inject the service in the controller as a dependency and use it as an object.
In your controller:
```
$scope.saveSetting = function() {
$cookies.settings = $scope.settings;
};
```
And to use them:
```
$scope.loadSetting = function() {
$scope.settings = $cookies.settings;
};
```
Please let me know if it works for you. | I would use ngStorage directive. I use it in my app. You would simply set the settings to your storage using ngStorage and then also set the initial value for your settings via ngStorage when the controller loads.
<https://github.com/gsklee/ngStorage> |
27,522,555 | According to <http://developer.android.com/training/basics/activity-lifecycle/recreating.html>
>
> The system may also destroy your activity if it's currently stopped and hasn't been used in a long time.
>
>
>
Exactly how long is this time? For example, when the user pressed the home button. | 2014/12/17 | [
"https://Stackoverflow.com/questions/27522555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2986001/"
] | There is no way of knowing how long that will be. When use presses home button activity is stopped and at that moment on it can be destroyed at any time.
From Android Activity documentation:
If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
<http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle> | If you want to carry out an experiment, you can create a weak reference to the activity and pull it, say, from a separate thread. When the activity is garbage-collected, the reference will become null. |
2,562,250 | We have a javascript function we use to track page stats internally. However, the URLs it reports many times include the page numbers for search results pages which we would rather not be reported. The pages that are reports are of the form:
```
http://www.test.com/directory1/2
http://www.test.com/directory1/subdirectory1/15
http://www.test.com/directory3/1113
```
Instead we'd like the above reported as:
```
http://www.test.com/directory1
http://www.test.com/directory1/subdirectory1
http://www.test.com/directory3
```
Please note that the numbered 'directory' and 'subdirectory' names above are just for example purposes and that the actual subdirectory names are all different, don't necessarily include numbers at the end of the directory name, and can be many levels deep.
Currently our JavaScript function produces these URLs using the code:
```
var page = location.hostname+document.location.pathname;
```
I believe we need to use the JavaScript replace function in combination with some regex but I'm at a complete loss as to what that would look like. Any help would be much appreciated!
Thanks in advance! | 2010/04/01 | [
"https://Stackoverflow.com/questions/2562250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191205/"
] | You can use a regex for this:
```
document.location.pathname.replace(/\/\d+$/, "");
```
Unlike `substring` and `lastIndexOf` solutions, this will strip off the end of the path if it consists of digits only. | What you can do is find the last index of "/" and then use the substring function. |
30,665,416 | I'm trying to understand why the following doesn't work. As far as I understand it shouldn't give me a box shadow if the `form__group` element is a child of `.modal` yet it does.
```
div:not(.modal) .form__group:hover {
box-shadow: inset 10px 0 0 #ccc;
}
```
<http://codepen.io/anon/pen/mJmddj> | 2015/06/05 | [
"https://Stackoverflow.com/questions/30665416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461864/"
] | Your HTML is:
```
<div class="modal">
<div class="modal__body">
<div class="form__group">
Hover on me for the box shadow - it shouldn't be there
</div>
</div>
</div>
```
When you remove the modal div, you get:
```
<div class="modal__body"> <!-- fits the "div:not(.modal)" -->
<div class="form__group">
Hover on me for the box shadow - it shouldn't be there
</div>
</div>
```
Since `.modal__body` is not `.modal` does it fit your statement.
Solution is to add `.modal__body` to the selector:
```
div:not(.modal) .modal__body .form__group:hover {
box-shadow: inset 10px 0 0 #ccc;
}
```
<http://codepen.io/anon/pen/wadvKZ> | "Selector form\_\_group is never used This inspection detects unused CSS classes or IDs within a file. " |
4,336,687 | In [SQL and Relational Theory](http://oreilly.com/catalog/9780596523084) (C.J. Date, 2009) chapter 4 advocates avoiding duplicate rows, and also to avoid `NULL` attributes in the data we store. While I have no troubles avoiding duplicate rows, I am struggling to see how I can model data without making use of `NULL`. Take the following, for example - which is a bit from work.
We have an `artist` table, which has, amongst other columns, a `gender` column. This is a foreign key to the `gender` table. However, for some artists, we don't know their gender - for example we've been given a list of new music which has no descriptions of the artist. How, without using `NULL` is one meant to represent this data? The only solution I see is to add a new gender, "unknown", to the `gender` table.
While I am thoroughly enjoying this book, I was really disappointed when the chapter concluded with:
>
> Of course, if nulls are prohibited, then missing information will have to be handled by some other means. Unfortunately, those other means are much too complex to be discussed in detail here.
>
>
>
Which is a real shame - because this was the solution I was waiting to read about! There is a reference to read the appendix which has lots of publications to read, but I was hoping for a little bit more of a down to earth summary before I dived into reading these.
---
I'm getting a few people commenting that they don't understand why I wish to avoid 'NULL' so I will quote the book again. Take the following query:
```
SELECT s.sno, p.pno
FROM s, p
WHERE s.city <> p.city
OR p.city <> 'Paris'
```
Now, take the example that s.city is London, and p.city is Paris. In this case, London <> Paris, so the query is true. Now take the case that p.city is not Paris, and is infact *xyz*. In this case, (London <> *xyz*) OR (*xyz* <> Paris) is also True. So, given any data - this query is true. However, if xyz is 'NULL' the scenario changes. In this case both of these expressions are neither True *nor* False, they are in fact, Unknown. And in this case because the result is unknown you will *not* get any rows returned.
The move from 2 value logic to 3 value logic can easily introduce bugs like this. Infact, I just introduced one at work which motivated this very post. I wanted all rows where the `type != 0` However, this actually ends up matching `type == 0 OR type IS NULL` - confusing behavior.
Whether or not I model my data with or without `NULL` in the future is unclear, but I'm very curious what the other solutions are. (I too have always been of the argument that if you don't know, you should use `NULL`). | 2010/12/02 | [
"https://Stackoverflow.com/questions/4336687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74497/"
] | **NULLs are required - theres no need to replace them**
The enitre definition of NULL is that its unknown - simply replacing this with arbitrary type is doing the same thing, so why?
For the comments below:
Just tried this - neither is true:
```
declare @x char
set @x = null
if @x = @x
begin
select 'true'
end
if @x <> @x
begin
select 'false'
end
```
I can only take this to mean that because null is unknown then it can't be said that it equals or does not equal - hence both statements are false | I disagree with the author and would claim that NULL is actually the CORRECT way to handle missing data for optional fields. In fact, it's the reason that NULL exists at all...
For your specific problem regarding gender:
* Are you sure you want a gender table and incur the cost of an extra join for every query? For simple enumerated types it's not unreasonable to make the field an int and define 1=male, 2=female, NULL=unknown. |
31,002,979 | Edit: I added some Information I thought to be unnecessary, but is not.
I have two branches, A and B. After making three commits in A that changes file.c I want to cherry-pick them into B, there is also a file.h which was changed in A~1
```
> git cherry-pick A~2
Success
> git cherry-pick A~1
error: could not apply 81e0723...
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
> git status
You are currently cherry-picking commit 81e0723.
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: some/unrelated/file.txt
both modified: file.c
```
Now when looking at some/unrelated/file.txt it contains the changes to file.h somewhere right in the middle. So this looks like a bug in git. So I will now undo the changes some/unrelated/file.txt manually and add them to file.h. | 2015/06/23 | [
"https://Stackoverflow.com/questions/31002979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3037258/"
] | It's possible the cherry-pick is changing a function that had also been changed earlier in `B`'s history, so the changes specifically in `A~1` are to lines that already looked different from what's in the `B` version and git can't see where in `B` the cherry-pick's changes apply.
It's also possible that the context git finds for the changes has evil twins lying in wait elsewhere in the code (say, multiple lines with nothing but standalone closing braces), and other changes have put the real corresponding original in your code far enough from where it was in `A~1^` that the hunt for the context in `B` finds something else instead. The manual suggests aborting the cherry-pick and retrying with `git cherry-pick -Xpatience` might be enough to avoid trouble with those, that spends an ordinarily-unreasonable amount of time trying to avoid getting lost in a sea of braces. [Here's probably a good place to start if you want details on how that really works](https://stackoverflow.com/questions/4045017/what-is-git-diff-patience-for). | Cherry picking is no different than applying a set of patches in order (with the benefit of getting previous commit messages). This necessarily results in new blobs--which you can verify by noting that he commit sha's are different.
When merge time comes, `git` now thinks it's looking at a different history, because technically it is, and hence a merge conflict. |
132,606 | Let $x$ and $y$ be defined such that
```
x=(((-3 + r) r^2 + a^2 (1 + r)) Csc[θ])/(a (-1 + r))
y=Sqrt[(a^2 (a^2 (1 + r)^2 + 2 r^2 (-3 + r^2)) +
a^4 (-1 + r)^2 Cos[θ]^2 - ((-3 + r) r^2 +
a^2 (1 + r))^2 Csc[θ]^2)/(a^2 (-1 + r)^2)]
```
Where for each value of $0<a<1$ and $0<\theta<\frac{\pi}{2}$ we can plot a **circle like figure** using
```
ParametricPlot[{{x, y}, {x, -y}}, {r, -10, 10}]
```
Now, let $R\_{s}$ to be the radius of a circle that passes the three points: (A) the top point of the circle like figure, (B) the bottom point of the circle like figure and (C) the right most point of the circle like figure.
[](https://i.stack.imgur.com/OoW8S.png)
My question is there a way to plot $R\_{s}$ in terms of $a$ and $\theta$?
For example
```
ContourPlot[Subscript[R, s], {a, 0, 1}, {θ, 0, π/2}]
```
How would this look like? | 2016/12/02 | [
"https://mathematica.stackexchange.com/questions/132606",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/38538/"
] | ```
x[a_, r_, t_] := (((-3 + r) r^2 + a^2 (1 + r)) Csc[t])/(a (-1 + r))
y[a_, r_, t_] :=
Sqrt[(a^2 (a^2 (1 + r)^2 + 2 r^2 (-3 + r^2)) +
a^4 (-1 + r)^2 Cos[t]^2 - ((-3 + r) r^2 + a^2 (1 + r))^2 Csc[
t]^2)/(a^2 (-1 + r)^2)]
tp[a_, t_] := Module[{
cs, c, ra,
top = u /. Solve[D[y[a, u, t], u] == 0, u, Reals],
yz = v /. Solve[y[a, v, t] == 0, v, Reals], xm, pts, tops},
tops = Last[SortBy[{x[a, #, t], y[a, #, t]} & /@ top, Last]];
xm = Last@Sort[x[a, #, t] & /@ yz];
pts = {{xm, 0}, tops, {1, -1} tops};
cs = Circumsphere[pts];
{c, ra} = List @@ cs;
Graphics[{Gray, cs, Red, PointSize[0.02], Point[pts], Green,
Point[c], {Purple, Line[{c, #}]} & /@ pts, Black,
Text[Framed[ra], {xm/2, 0}, {0, -1}]}]
]
vis[a_, b_] :=
Show[Quiet@tp[a, b],
ParametricPlot[{#, {1, -1} #} &@{x[a, r, b], y[a, r, b]}, {r, 0,
10}], Frame -> True]
```
Visualizing some examples:
```
Manipulate[vis[a, b],
{a, {0.9, 0.95, 0.99}}, {b, Range[0.5, 1.5, 0.2]}]
```
[](https://i.stack.imgur.com/U5E6C.gif) | ok, so you have the parametric plot:
```
pp = ParametricPlot[{{x, y}, {x, -y}}, {r, -10, 10}]
```

We can get the desired points from this plot:
```
pts = Flatten[Cases[pp, Line[pts__] :> pts, Infinity], 1];
xmax = First@MaximalBy[pts, First];
ymax = First@MaximalBy[pts, Last];
ymin = First@MinimalBy[pts, Last];
```
Having these points we can generate a circumsphere:
```
circumsphere = Graphics[{
Circumsphere[{xmax, ymax, ymin}],
PointSize[Large], Red, Point[{xmax, ymax, ymin}]
}]
```

Having the circumsphere, we can get its center:
```
{center} = Cases[circumsphere, Sphere[center_, r_] :> center, Infinity];
```
And finally we can plot all of our information together:
```
Show[
pp,
circumsphere,
Graphics[{
Line[{center, xmax}],
Line[{center, ymax}],
Line[{center, ymin}]
}],
PlotRange -> All
]
```
 |
106,111 | I've got one year of University left and luckily I've managed to stash around **~$18k** in savings that my expenses never cut into. My tuition for my last year will probably be around **$13k**.
I hate the idea of being in debt - but aside from emptying my savings account, the alternative is that **I take OSAP to cover my tuition and pay it back +3.5%** over the course of five years or so. Roughly **$300 a month.** I'm a bit paranoid about money - I keep two checking accounts as buffers with between 500 - 1000 dollars available at short notice in each of them in case of emergency, and then my savings account is there to accrue interest on money I never intend to spend. That's why I hate the idea of **emptying out my savings on tuition** - I feel like I'm removing a large portion of my stack of hay that'd catch my fall.
1. Does anyone think the direction the Ontario Government is moving in
will mean my OSAP payments may get less forgiving rather than more?
2. Am I setting myself up to be bamboozled by my government?
3. Should I bite the bullet and live paycheck-to-paycheck until I get a job in order to avoid that bamboozling?
To note, my prospects seem ok - I'm on a well-paying internship right now for 14 months and they seem willing to take me on once I graduate. Any advice appreciated. Thanks. | 2019/03/06 | [
"https://money.stackexchange.com/questions/106111",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/83134/"
] | The core of the answer here is independent of the specifics of the Canadian education funding system, IMO.
You are approaching the transition to *earning your own living,* and having to operate within the financial constraints which that imposes on you.
Keeping a cash "emergency fund" of a couple of thousand dollars is highly desirable, so long as you see it as covering *relatively short term, low cost emergency situations.*
Beyond that, you need a strategy to handle longer term unexpected events - for example a few *months* during which your are not working (through no fault of your own) but you need to finance somewhere to live, and your day to day living expenses.
I would see your $18k savings as covering that type of scenario. One unbreakable rule of personal finance is simple and obvious, but often ignored when thinking about future plans: *you can only spend your money once.* If you spend that $18k on your education in your final year, you now have *no* cushion of cash to get you through an unforeseen situation in future.
You could take the view that it would be better to defer taking out a loan to cover such a situation until you are forced to do so, but that ignores the fact that being in such a situation will not improve your ability to take out a low cost loan. Student loans generally *are* low cost, compared with other forms of borrowing.
If I were in your position, I would prefer the option of keeping your $18k cash cushion intact, take the student loan, and (as you appear to have done already) have a credible plan to pay the loan off, if nothing else untoward hits you financially.
You might want to consider a different place to park the $18k than a bank savings account - so long as *it is still accessible in a reasonably short time scale (say 1 month) with no penalties.* The main factor in choosing what to do with it is to *preserve* its value (against inflation, etc) rather than to hope to increase it, but with a significant risk of the opposite happening. Assuming your income will exceed your expenditure after you graduate, you have a lifetime ahead of you in which to invest your *surplus* income in the hope of long term gains (i.e. a timescale of 20 or even 50 years) without worrying about short term losses, or the possibility that you have to cash in those investments to meet an emergency. | The endowment effect is a psychological theory that people value things they already have more than the same things if they were thinking of obtaining them.
<https://en.wikipedia.org/wiki/Endowment_effect>
To try and verify you aren't suffering from this think about your situation like this. You are 13k in debt and you receive 18k as a gift. Do you pay off your debt and bank the remaining 5k or bank the whole 18k and keep the debt?
When put like that it is more likely you will want to pay up front rather than take a loan, however other people made good points about the terms of this loan. If it really is an interest free loan that you can repay in full with no penalty before you need to start paying interest then there is no reason not to take it. |
212,439 | I recently experienced a roof leak on a heavy raining day in the east coast.
Picture 1: This is the interior ceiling.
I tore open the ceiling sheetrock and could see that water was dripping from the horizontal wood beams. When I checked with a flashlight between the horizontal beams I can see a tiny hole on the black material (above the beams). Water was leaking from that tiny hole.
Picture 2 : This is the outside/exterior roof of my building from where the water is coming in.
I am assuming its right under the red shingles but not exactly sure.
How do I exactly know where is the leak/hole from outside ?
I guess once I find the hole I can patch it up with flashing cement.
Any advice on what is the best way to fix this leak.
[](https://i.stack.imgur.com/Ce6K9.jpg)[](https://i.stack.imgur.com/UgIop.jpg)
Thanks in advance. | 2020/12/29 | [
"https://diy.stackexchange.com/questions/212439",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/127625/"
] | Your problem is going to be finding where the leak is coming from. I have found leaks that came in more than 10’ from the entry point. The water can travel under the rolled roofing and drip down at a seam then run on the rafters especially double plates prior to finally coming down.
Today I use a FLIR camera I can see the water when it is traveling between boards because of the temp difference.
The only way to patch in wet weather is a patch like Henery’s asphalt or other brands of similar type. I would stick with asphalt as that is the best material and the base of the rolled roofing.
I used to do hot tar as a kid and for patches we used Henery’s you might have the leak up in the valley or to the side that is running down so identifying the entrance point will be the most critical part and sealing that point. Asphalt patch can even handle standing water and most brands I have used can be put on in standing water but you have to work it a bit to get it to seal and it works better on dry surfaces.
I used to use a leaf blower to dry roofs off before sealing it helps. | I would ask a few more questions, like, is this a home you plan on living in for years or just a long term Airbnb that you want to patch ?
Maybe I'm misunderstanding your comment about the hole, but couldn't you just insert a stiff wire at that point and have someone up on the roof look for it?. If not measure the distance from a known exterior wall from inside and add 6-8" outside and you have a closer measure of finding the spot of the leak.
Since you have the end point of the leak... work backwards and start removing the interior framing and that will likely lead you to the wetspot ie the hole in your roof which TBH looks like a drunken toddler was your roofer. You can slowly work your way up, since water really only goes down, you will find many wet boards along the way and you won't have to tear a hole in your roof looking for it. Then patch that hole, reroof that job and if you can salvage the framing otherwise put in new boards.
I recently had to fix a bad dry rot problem that was patched so poorly by the previous owner that they tore off the rotted siding, sheeting and installed a new piece of plywood as a nailer strip. Then they reinstalled new plywood over dry rotted framing, installed siding and sold the house. $22,000 later we found/solved the issue and am suing the previous owner for lack of disclosure of the repair, fraudulently sold a house claiming there was no repair as we now know he knew there was an issue but covered it up in addition I have testimony from neighbors they witnessed the work being done the prior summer.
If you are skittish about swinging a hammer or doing repairs blindly, I have a few options to fix this once you find the leak, you can get someone with 15+ years experience in roofs who will happily supply you five different references of old jobs where the customer is happy. Ask that roofer to come over and give you advice, I've had so much luck making friends with contractors, beer and pizza go a long way to get advice. Its likely that this is a common occurence and the contractor has a way to deal with this that you can benefit from.
Next option you can repeat the mistake of the previous person and try to patch this job by draping a tarp over an area or doing other half measures, this is not undoable but its hit or miss and will waste time. Then you become the same type of person who does a half way job and there is a special place in the underworld for people who half ass things.
I guess a nerdy option would be to draw squares on your roof and use different colored water to pour onto that area, when you get that color water into your wood framing you have at least a vertical start point. |
20,006,871 | I have a basic PHP script that creates a csv file from an array. Here is an example of the code:
```
$array = [
[1,2,3],
[4,5,6]
];
$handle = fopen('test.csv', 'w');
foreach($array as $v)
fputcsv($handle, $v);
fclose($handle);
```
The resulting file always has a blank line at the end of the file, because fputcsv doesn't know that this is the last line. Any (simple) ideas on how to prevent this?
EDIT:
The original question is now irrelevant (to me, but maybe someone will need to do this). fputcsv is supposed to add a new line, even at the end of the document, and this is the expected behavior of all csv files.
I marked the answer that solves the original question, even though it isn't relevant to me anymore.
So in my context, I needed to check if the last line (or any line) of the array is NULL (otherwise PHP will through up a Warning that fputcsv's 2nd parameter is null). Here is my updated script if anyone is interested:
```
$array = [
[1,2,3],
[4,5,6]
];
$handle = fopen('test.csv', 'w');
foreach($array as $v)
if($v != NULL)
fputcsv($handle, $v);
fclose($handle);
``` | 2013/11/15 | [
"https://Stackoverflow.com/questions/20006871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1564018/"
] | I found this solution on another question: <https://stackoverflow.com/a/8354413/1564018>
```
$stat = fstat($handle);
ftruncate($handle, $stat['size']-1);
```
I added these two lines after fputcsv() and they removed the last new line character, removing the blank line at the end of the file. | Add exit(); at the end, after fclose(handle); |
5,253,703 | I'm trying to overflow a buffer in C++ that is a private variable. Where does it live on the stack? Is this possible?
Something like
```
class aClass{
private:
char buffer[SIZE];
public:
}
``` | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Public and private variables are not treated any differently in terms of layout. A class allocated on the stack has it's internal data members allocated on the stack- that's regardless of being private or public.
```
class MyClass {
public:
int PublicInt;
private:
int PrivateInt;
};
int main() {
MyClass instance;
}
```
is equivalent to, in memory terms
```
int main() {
int a, b;
};
``` | Writing past the array can be considered as an example of buffer overflow. You can do this how ever, but I don't know what you are trying to achieve by doing so.
```
void aClass:: bufferOverflow() // Assuming this a member of aClass
{
for( int i=0; i<(SIZE+2), ++i )
buffer[i] = 'a'; // Writing past the 2 locations.
}
```
**Where does it live on the stack?**
Stack it self is a storage location. What do you mean by where it lives on stack. |
43,147,546 | For Example :-
I have saved date in my table in the format of **ddmmyyyy**
Now I need to fetch rows of month **03**
So my query can be
```
Select *
from orders
where date = "%03%"
```
But it will bring values of date 03 and year 2003 too.
Is there anyway to fetch the values where the **03** is in the position of **3rd** and **4th** in the string? | 2017/03/31 | [
"https://Stackoverflow.com/questions/43147546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6608983/"
] | ```
Select * from orders where month(str_to_date(date,'%d%m%Y')) = 03
``` | date is stored in "Y-m-d" format in MySQL, if you have stored your date as a text then you can try
```
SELECT * FROM `orders` WHERE `date` LIKE "__03____";;
``` |
38,233,157 | (With static and dynamic I mean the distinction whether code is susceptible to change)
I have a bit of a weird problem I'm currently stuck on. I'm writing an application which involves some complex interactions between components in which it becomes hard to keep track of the code flow. To simplify this, I'm trying to structure the code by creating 'layers', where each layer has increased functionality compared to the layer above it. Each layer is contained in a package. I'm having the following problem:
Consider the following 2 classes and their subclasses with increased functionality:
Class A:
```
package layer;
class A {
B b;
A() {
b = new B();
}
void foo() {
b.foo();
}
/* More A-class methods here */
}
```
Class B:
```
package layer;
class B {
void foo() {
// Do something
}
/* More B-class methods here */
}
```
Subclass A:
```
package sublayer;
class ASub extends A {
ASub() {
super.b = new BSub(); // This needs a cast to compile
}
}
```
Subclass B:
```
package sublayer;
class BSub extends B {
@Override
void foo() {
// Do something with more functionality
}
}
```
In the end I just want to instantiate and modify classes ASub and BSub, being able to use all methods of superclasses A and B without actually needing to modify code in classes A and B itself.
If I call `new ASub().foo()`, I want the overridden foo() of BSub to execute instead of that of B. Ofcourse I can add a variable `BSub bsub` in ASub and override A's foo() method to call `bsub.foo()`, but this doesnt avoid the creation of the object `b` in the constructor of A, which seems sloppy coding. Any thoughts on this? Any comments are welcome. | 2016/07/06 | [
"https://Stackoverflow.com/questions/38233157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443647/"
] | Final Code:
```
Public Sub replacewordwithline(ByVal input As RichTextBox, ByVal sep As Char, Optional ByVal output As RichTextBox = Nothing)
Dim tb As New TextBox 'Create a new textbox
Dim orgstr As String = input.Text 'Make a backup of the input text
tb.Multiline = True
tb.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\test.txt") 'Set the textbox's text to the text file text
Dim str1 As String() 'Create blank input word list
Dim str3 As String = ""
For Each l2 In input.Lines 'For each line in input...
str3 &= l2 & "#" '...Add a '#' to the end of it
Next
str1 = str3.Split({"#"c}, StringSplitOptions.RemoveEmptyEntries) 'Split the input to words
For Each w1 In str1 'For each word in input
For Each l1 In tb.Lines 'For each line in text file
If l1.Contains(w1) Then 'If line contains input word
Dim str2 As String() = l1.Split({sep}, StringSplitOptions.RemoveEmptyEntries) 'Split text file line
For Each w2 In str2 'For each word in text file line
If w1 = w2 Then 'If input word = text file word
repln(input, getln(input, w1), l1) 'Replace line
End If
Next
End If
Next
Next
Dim bla As Boolean = False
Try
If Not output.Name = "" Then 'If output exists
bla = True
output.Text = input.Text 'Set the output's text to the input's one
input.Text = orgstr 'Reset the input's text to the original
End If
Catch
End Try
If bla = True Then 'Output Exists
For i1 As Integer = 0 To output.Lines.Count - 1 'For each output line
Dim inln As String = input.Lines(i1)
Dim ouln As String = output.Lines(i1)
If Not ouln.Contains(inln) And ouln.Contains(sep.ToString) Then 'If output line doesn't contain input line and contains the seperator
repln(output, i1, inln) 'Replace line
End If
Next
ElseIf bla = False Then 'Output Doesn't Exist
Dim tb1 As New TextBox
tb1.Text = orgstr
For i1 As Integer = 0 To input.Lines.Count - 1 'For each input line
Dim inln As String = tb1.Lines(i1)
Dim ouln As String = input.Lines(i1)
If Not ouln.Contains(inln) And ouln.Contains(sep.ToString) Then 'If input line doesn't contain original string line and contains the seperator
repln(input, i1, inln) ' Replace line
End If
Next
End If
End Sub
Public Sub repln(ByVal tb1 As RichTextBox, ByVal ln As Integer, ByVal strnew As String)
Dim str1 As New List(Of String)
Dim str2 As String = ""
For Each l In tb1.Lines 'Add each line of input to the list
str1.Add(l)
Next
str1.RemoveAt(ln) 'Remove the seleted line
str1.Insert(ln, strnew) 'Fill the gap with the new text
Dim int As Integer = 0
For Each l1 In str1 'Output the list
str2 &= l1 & vbNewLine
Next
str2 = str2.Substring(0, str2.Length - 2) 'Remove the final line
tb1.Text = str2 'Send the edited text to the input
End Sub
Public Function getln(ByVal tb As RichTextBox, ByVal str As String) As Integer
Dim i As Integer = 0
For Each l In tb.Lines 'For each line in input
If l = str Then 'If input line text is the same as the selected string
Return i 'Return input line number
End If
i += 1
Next
End Function
```
Example: `replacewordwithline(RichTextBox1, "-")` will set the text seperator to '-' and will output the result to RichTextBox1.
`replacewordwithline(RichTextBox1, "|", RichTextBox2)` will set the text seperator to '|' and will output the resault to RichTextBox2. The `output` is optional (In this case `RichTextBox2`)
Now with sentense support :)
On the text file if you write something like:
`I'm a potato-I'm a tomatoe`
And on the program:
`I'm a tomatoe` Or `I'm a potato`
The program will output:
`I'm a potato-I'm a tomatoe`
`-` Depends On The Seperator.
---
Duplicate the sub caller:
Ex.
```
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
replacewordwithline(RichTextBox1, "-")
End Sub
```
To
```
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
replacewordwithline(RichTextBox1, "-")
replacewordwithline(RichTextBox1, "-")
End Sub
```
P.S. Sorry for my bad english :) | ```
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
Dim LSOS As Integer = Nothing
Dim linelentgh As Integer = File.ReadAllLines(Application.StartupPath + "\test.txt").Length
Do Until LSOS >= linelentgh
Dim line As String = File.ReadLines(Application.StartupPath + "\test.txt").Skip(LSOS).Take(1).First()
repl(line)
LSOS += 1
Loop
End Sub
Sub repl(ByVal line As String)
Dim thisArray As String() = line.Split("|"c)
For Each wordfromtext As String In Inputs.Text.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
For Each s As String In thisArray
If wordfromtext = s Then
Output.Text = Inputs.Text.Replace(s, line)
End If
Next
Next
End Sub
```
This code works fine, no multiple replacing problems, no words mistakes... but it work just for the first word found on it... |
32,225,604 | I use this git repo: <https://github.com/kudago/smart-app-banner>
I downloaded it with `git clone https://github.com/kudago/smart-app-banner`.
Then I tried to install it from its parent dir with:
```
npm install --save smart-app-banner
```
This always installs the source from the github repo instead of from the local source.
**How do I get the source being install from the local copy instead of from github?** | 2015/08/26 | [
"https://Stackoverflow.com/questions/32225604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055664/"
] | npm install /path
it is as simple as that | If you run npm install without any arguments, it tries to install the current folder.
Go to that folder and type npm Install
or
Just put that downloaded File in Node\_modules folder of your project. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.