qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency. While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (`<% for`), conditionals (`<% if`) and transforms (`<%= myString | uppercase %>`) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components). Templates Inside HTML ===================== One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing `<script>` `type`, e.g. `<script type="text/template">`. For your case: ``` <script type="text/template" data-template="listitem"> <a href="${url}" class="list-group-item"> <table> <tr> <td><img src="${img}"></td> <td><p class="list-group-item-text">${title}</p></td> </tr> </table> </a> </script> ``` On document load, read your template and tokenize it using a simple `String#split` ``` var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g); ``` Notice that with our token, you get it in the alternating `[text, property, text, property]` format. This lets us nicely map it using an `Array#map`, with a mapping function: ``` function render(props) { return function(tok, i) { return (i % 2) ? props[tok] : tok; }; } ``` Where `props` could look like `{ url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }`. Putting it all together assuming you've parsed and loaded your `itemTpl` as above, and you have an `items` array in-scope: ``` $('.search').keyup(function () { $('.list-items').append(items.map(function (item) { return itemTpl.map(render(item)).join(''); })); }); ``` This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with `document.querySelector` and `.innerHTML`. [jsfiddle](https://jsfiddle.net/jkoudys/5hcjo31u/) Templates inside JS =================== A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function. In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the `$.fn.html` method above. ``` const Item = ({ url, img, title }) => ` <a href="${url}" class="list-group-item"> <div class="image"> <img src="${img}" /> </div> <p class="list-group-item-text">${title}</p> </a> `; ``` Then you could easily render it, even mapped from an array, like so: ``` $('.list-items').html([ { url: '/foo', img: 'foo.png', title: 'Foo item' }, { url: '/bar', img: 'bar.png', title: 'Bar item' }, ].map(Item).join('')); ``` Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.
In order to solve this problem, I recognize two solutions: * The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with [`.clone()`](http://api.jquery.com/clone/). ``` $.get('url/to/template', function(data) { temp = data $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); }); ``` Take into account that the event should be added once the ajax has completed to be sure the data is available! * The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery: ``` temp = $('.list_group_item').hide() ``` You can after add a new instance of the template with ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); ``` * Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) [`.detach()`](http://api.jquery.com/detach/) instead of hide. ``` temp = $('.list_group_item').detach() ``` `.detach()` removes elements from the DOM while keeping the data and events alive (.remove() does not!).
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
You could decide to make use of a templating engine in your project, such as: * [mustache](http://mustache.github.io/) * [underscore.js](http://underscorejs.org/) * [handlebars](http://handlebarsjs.com/) If you don't want to include another library, John Resig offers a [jQuery solution](http://ejohn.org/blog/javascript-micro-templating/), similar to the one below. --- Browsers and screen readers ignore unrecognized script types: ``` <script id="hidden-template" type="text/x-custom-template"> <tr> <td>Foo</td> <td>Bar</td> <tr> </script> ``` Using jQuery, adding rows based on the template would resemble: ``` var template = $('#hidden-template').html(); $('button.addRow').click(function() { $('#targetTable').append(template); }); ```
Here's how to use the `<template>` element and jQuery a little more efficiently, since the other jQuery answers as of the time of writing use `.html()` which forces the HTML to be serialized and re-parsed. First, the template to serve as an example: ```html <template id="example"><div class="item"> <h1 class="title"></h1> <p class="description"></p> </div></template> ``` Note that there is no space between the `<template>` tag and its content, nor between the end of the content and `</template>`. If you put space in there, it will be copied too. Now, the JS: ```js // example data const items = [ {name: "Some item", description: "Some description"}, // ... ]; const template = $("template#example").contents(); const templateTitle = template.find("h1.title"); const templateDescription = template.find("p.description"); const target = $("body"); for (const item of items) { // fill in the placeholders templateTitle.text(item.name); templateDescription.text(item.description); // copy the template and add it to the page target.append(template.clone()); } ``` This will add a copy of the template, with placeholders replaced, for every item in the items array. Note that several elements, like `template` and `target`, are only retrieved once.
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
Add somewhere in body ``` <div class="hide"> <a href="#" class="list-group-item"> <table> <tr> <td><img src=""></td> <td><p class="list-group-item-text"></p></td> </tr> </table> </a> </div> ``` then create css ``` .hide { display: none; } ``` and add to your js ``` $('#output').append( $('.hide').html() ); ```
In order to solve this problem, I recognize two solutions: * The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with [`.clone()`](http://api.jquery.com/clone/). ``` $.get('url/to/template', function(data) { temp = data $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); }); ``` Take into account that the event should be added once the ajax has completed to be sure the data is available! * The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery: ``` temp = $('.list_group_item').hide() ``` You can after add a new instance of the template with ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); ``` * Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) [`.detach()`](http://api.jquery.com/detach/) instead of hide. ``` temp = $('.list_group_item').detach() ``` `.detach()` removes elements from the DOM while keeping the data and events alive (.remove() does not!).
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
In order to solve this problem, I recognize two solutions: * The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with [`.clone()`](http://api.jquery.com/clone/). ``` $.get('url/to/template', function(data) { temp = data $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); }); ``` Take into account that the event should be added once the ajax has completed to be sure the data is available! * The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery: ``` temp = $('.list_group_item').hide() ``` You can after add a new instance of the template with ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { $(this).append(temp.clone()) }); }); ``` * Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) [`.detach()`](http://api.jquery.com/detach/) instead of hide. ``` temp = $('.list_group_item').detach() ``` `.detach()` removes elements from the DOM while keeping the data and events alive (.remove() does not!).
Here's how to use the `<template>` element and jQuery a little more efficiently, since the other jQuery answers as of the time of writing use `.html()` which forces the HTML to be serialized and re-parsed. First, the template to serve as an example: ```html <template id="example"><div class="item"> <h1 class="title"></h1> <p class="description"></p> </div></template> ``` Note that there is no space between the `<template>` tag and its content, nor between the end of the content and `</template>`. If you put space in there, it will be copied too. Now, the JS: ```js // example data const items = [ {name: "Some item", description: "Some description"}, // ... ]; const template = $("template#example").contents(); const templateTitle = template.find("h1.title"); const templateDescription = template.find("p.description"); const target = $("body"); for (const item of items) { // fill in the placeholders templateTitle.text(item.name); templateDescription.text(item.description); // copy the template and add it to the page target.append(template.clone()); } ``` This will add a copy of the template, with placeholders replaced, for every item in the items array. Note that several elements, like `template` and `target`, are only retrieved once.
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
You could decide to make use of a templating engine in your project, such as: * [mustache](http://mustache.github.io/) * [underscore.js](http://underscorejs.org/) * [handlebars](http://handlebarsjs.com/) If you don't want to include another library, John Resig offers a [jQuery solution](http://ejohn.org/blog/javascript-micro-templating/), similar to the one below. --- Browsers and screen readers ignore unrecognized script types: ``` <script id="hidden-template" type="text/x-custom-template"> <tr> <td>Foo</td> <td>Bar</td> <tr> </script> ``` Using jQuery, adding rows based on the template would resemble: ``` var template = $('#hidden-template').html(); $('button.addRow').click(function() { $('#targetTable').append(template); }); ```
Use HTML template instead! ========================== Since the accepted answer would represent overloading script method, I would like to suggest another which is, in my opinion, much cleaner and more secure due to XSS risks which come with overloading scripts. I made a [demo](https://codepen.io/DevWL/pen/YrjyWm?editors=1010) to show you how to use it in an action and how to inject one template into another, edit and then add to the document DOM. ### example html ``` <template id="mytemplate"> <style> .image{ width: 100%; height: auto; } </style> <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> </template> ``` ### example js ``` // select var t = document.querySelector('#mytemplate'); // set t.content.querySelector('img').src = 'demo.png'; t.content.querySelector('p').textContent= 'demo text'; // add to document DOM var clone = document.importNode(t.content, true); // where true means deep copy document.body.appendChild(clone); ``` HTML &lttemplate> ================= * +Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render. * +Any content within a template won't have side effects. Scripts don't run, images don't load, audio doesn't play ...until the template is used. * +Content is considered not to be in the document. Using `document.getElementById()` or `querySelector()` in the main page won't return child nodes of a template. * +Templates can be placed anywhere inside of `<head>`, `<body>`, or `<frameset>` and can contain any type of content which is allowed in those elements. Note that "anywhere" means that `<template>` can safely be used in places that the HTML parser disallows. Fall back ========= Browser support should not be an issue but if you want to cover all possibilities you can make an easy check: > > To feature detect `<template>`, create the DOM element and check that > the .content property exists: > > > ``` function supportsTemplate() { return 'content' in document.createElement('template'); } if (supportsTemplate()) { // Good to go! } else { // Use old templating techniques or libraries. } ``` Some insights about Overloading script method ============================================= * +Nothing is rendered - the browser doesn't render this block because the `<script>` tag has `display:none` by default. * +Inert - the browser doesn't parse the script content as JS because its type is set to something other than `"text/javascript"`. * -Security issues - encourages the use of `.innerHTML`. Run-time string parsing of user-supplied data can easily lead to XSS vulnerabilities. Full article: <https://www.html5rocks.com/en/tutorials/webcomponents/template/#toc-old> Useful reference: <https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode> <http://caniuse.com/#feat=queryselector> **CREATING WEB COMPONENTS** Creating custom web components tutorial using HTML templates by Trawersy Media: <https://youtu.be/PCWaFLy3VUo>
18,673,860
I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the `HTML` code below to a container element with some values. Where can I put this HTML to re-use in a smart way? ``` <a href="#" class="list-group-item"> <div class="image"> <img src="" /> </div> <p class="list-group-item-text"></p> </a> ``` JQuery ``` $('.search').keyup(function() { $('.list-items').html(null); $.each(items, function(index) { // APPENDING CODE HERE }); }); ```
2013/09/07
[ "https://Stackoverflow.com/questions/18673860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358522/" ]
Other alternative: [Pure](http://beebole.com/pure/) I use it and it has helped me a lot. An example shown on their website: **HTML** ``` <div class="who"> </div> ``` **JSON** ``` { "who": "Hello Wrrrld" } ``` **Result** ``` <div class="who"> Hello Wrrrld </div> ```
Here's how to use the `<template>` element and jQuery a little more efficiently, since the other jQuery answers as of the time of writing use `.html()` which forces the HTML to be serialized and re-parsed. First, the template to serve as an example: ```html <template id="example"><div class="item"> <h1 class="title"></h1> <p class="description"></p> </div></template> ``` Note that there is no space between the `<template>` tag and its content, nor between the end of the content and `</template>`. If you put space in there, it will be copied too. Now, the JS: ```js // example data const items = [ {name: "Some item", description: "Some description"}, // ... ]; const template = $("template#example").contents(); const templateTitle = template.find("h1.title"); const templateDescription = template.find("p.description"); const target = $("body"); for (const item of items) { // fill in the placeholders templateTitle.text(item.name); templateDescription.text(item.description); // copy the template and add it to the page target.append(template.clone()); } ``` This will add a copy of the template, with placeholders replaced, for every item in the items array. Note that several elements, like `template` and `target`, are only retrieved once.
62,892,222
I recently bought an ssl certificate and i am having a problem with google chrome when i access my website it says 'Your connection is not private NET::ERR\_CERT\_AUTHORITY\_INVALID' here is what i am doing: ``` const express = require("express"); const https = require('https'); const helmet = require("helmet"); const cors = require("cors"); const fs = require("fs"); const path = require("path"); const app = express(); const config = require("./config"); const passport = require("passport"); const credentials = { key: fs.readFileSync('ssl/site.key', 'utf-8'), cert: fs.readFileSync('ssl/site.crt', 'utf-8') + fs.readFileSync('ssl/site.ca-bundle', 'utf-8') }; app.use(helmet()); app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use( require("express-session")({ secret: require("./config.json").app.secretKey, resave: false, saveUninitialized: true, cookie: { secure: false, maxAge: 60 * 60 * 1000 * 24 * 365, }, }) ); app.use(passport.initialize()); app.use(passport.session()); passport.use(require("./service/passport")); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); app.use(express.static(path.join(__dirname, "views"))); app.use("/", require("./api/views")); app.use("/auth", require("./api/auth")); app.use("/answer", require("./api/answer")); app.use("/user", require("./api/views/user.view")); app.use("/courses", require("./api/views/courses.view")); app.use("/question", require("./api/views/question.view")); app.use("/answer", require("./api/views/answer.view")); app.use("/api/user", require("./api/user")); app.use("/api/course", require("./api/course")); app.use("/api/feedback", require("./api/feedback")); app.use("/api/help", require("./api/help")); app.use("/api/questions", require("./api/question")); var httpsServer = https.createServer(credentials, app); httpsServer.listen(config.app.port); console.log(credentials); //app.listen(config.app.port); ``` I have seen that a lot of people had the same problem what should i do?
2020/07/14
[ "https://Stackoverflow.com/questions/62892222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10457357/" ]
Appearently it took some days to have the certification marked as safe here is the code at the end: ``` const express = require("express"); const https = require('https'); const helmet = require("helmet"); const cors = require("cors"); const fs = require("fs"); const path = require("path"); const app = express(); const config = require("./config"); const passport = require("passport"); const credentials = { key: fs.readFileSync('ssl/site.key', 'utf-8'), cert: fs.readFileSync('ssl/site.crt', 'utf-8'), ca: fs.readFileSync('ssl/site.ca-bundle', 'utf-8') }; app.use(helmet()); app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use( require("express-session")({ secret: require("./config.json").app.secretKey, resave: false, saveUninitialized: true, cookie: { secure: false, maxAge: 60 * 60 * 1000 * 24 * 365, }, }) ); app.use(passport.initialize()); app.use(passport.session()); passport.use(require("./service/passport")); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); app.use(express.static(path.join(__dirname, "views"))); app.use('/', require('./api/home')); app.use("/auth", require("./api/auth")); app.use("/answer", require("./api/answer")); app.use('/material', require('./api/material')); app.use("/user", require("./api/user")); app.use("/courses", require("./api/course")); app.use('/feedback', require('./api/feedback')) app.use("/question", require("./api/question")); app.use("/answer", require("./api/answer")); var httpsServer = https.createServer(credentials, app); httpsServer.listen(config.app.port); ``` Also i used the certification that i generated via openssl and not the one i received from the website.
You need to collect the site certificate and the intermediate certificates into a single buffer and pass that combined buffer as the `cert` option to `https.createServer()`. So replace this: ``` const credentials = { key: fs.readFileSync('ssl/key.pem'), cert: fs.readFileSync('ssl/crt.pem'), ca: fs.readFileSync('ssl/ceraut.ca-bundle') }; ``` with this: ``` const credentials = { key: fs.readFileSync('ssl/key.pem'), cert: fs.readFileSync('ssl/crt.pem') + fs.readFileSync('ssl/ceraut.ca-bundle') }; ``` (This assumes that your `ca-bundle` file contains the intermediate certs in the correct order and in PEM format.) It's possible that you might also have to add a newline between the content of the two files if the closing newline from the site cert file has somehow been lost. Don't pass a `ca` option to `createServer()` at all. That option specifies a non-default root cert collection that should be used to validate a received certificate. Your server doesn't need that option. For details see <https://nodejs.org/docs/latest-v10.x/api/tls.html#tls_tls_createsecurecontext_options> or the equivalent for the appropriate Node version, although the precise version probably doesn't matter. The docs for these options have been stable for ages.
13,577,020
Is it bad practice to do this in a view (it's a helper method)? ``` <% get_articles %> ``` If so, where should it live? It seems logical to me to call them in their corresponding controller blocks, but I'm not sure if that's correct or how to do it. Thanks!
2012/11/27
[ "https://Stackoverflow.com/questions/13577020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153022/" ]
If the method lives in a helper, its designed to be called in the view. Really depends on what that method is doing if it should be there. Is it accessing the database? If so, it should be called from the controller and its results stored in a variable to be used by the view. (It also shouldn't be in a helper). If that method simply generates html to be used in the view, then you would output it as ``` <%= get_articles %> ```
No, helper methods are for views. so its not wrong if you call a helper method in your view. Take a look at this [post](http://techspry.com/ruby_and_rails/designing-helpers-in-ruby-on-rails)
9,722
Most fruit pies call for two crusts, whereas most custardy pies do not. However, my apple pies with one crust or two or substantially the same. Is the number of crusts simply traditional?
2010/12/02
[ "https://cooking.stackexchange.com/questions/9722", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/3633/" ]
Yes, it is mainly tradition, appearance, and how you like the ratio of crust to fruit in your pie. You can make any pie open faced, with a full top, or any type of lattice top. The other thing to consider is that a top crust provides some heat insulation to the fruit, so if you don't want the fruit to caramelize as much, it will help with that.
I think it's traditional to some extent, but double crust pies have several advantages for fruit pies. For one, it keeps the fruit covered, so the fruit can simmer, much like cooking in a pot. Second, it keeps the bubbling fruit from seeping over the edges of the pie plate. Third, a top crust adds another surface to keep the pie together when it is being sliced. More surface tension means more structurally sound pie slices.
20,619,458
I need to be able to select 3 distinct picture URL's held in the database but also pull the other data in the row without it affecting the DISTINCT argument... EXAMPLE:: DataBase = ``` ID - PICTURE_URL 01 - domain.com/pic1.jpg 02 - domain.com/pic1.jpg 03 - domain.com/pic1.jpg 04 - domain.com/pic2.jpg 05 - domain.com/pic3.jpg ``` So in the above example the SQL should only PULL either ID 1, 2, or 3 as a result, and 4 & 5 as the other 2 results. OUTPUT = ``` 01 Domain.com/pic1.jpg 04 Domain.com/pic2.jpg 05 Domain.com/pic3.jpg ``` OR ``` 02 Domain.com/pic1.jpg 04 Domain.com/pic2.jpg 05 Domain.com/pic3.jpg ``` OR ``` 03 Domain.com/pic1.jpg 04 Domain.com/pic2.jpg 05 Domain.com/pic3.jpg ``` Because picture\_url all had the same url to a picture stored on the server, so I do not want to select the same 3 pictures. :) Any help on this would be very much appreciated :)
2013/12/16
[ "https://Stackoverflow.com/questions/20619458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3052268/" ]
You can use aggregate function: ``` select min(ID), PICTURE_URL from your_table group by PICTURE_URL ```
Query: **[SQLFIDDLEExample](http://sqlfiddle.com/#!2/d6e4b/4)** ``` SELECT t1.ID, t1.PICTURE_URL FROM Table1 t1 left join Table1 t2 on t1.PICTURE_URL = t2.PICTURE_URL AND t1.ID > t2.ID WHERE t2.ID is null ``` Result: ``` | ID | PICTURE_URL | |----|---------------------| | 1 | domain.com/pic1.jpg | | 4 | domain.com/pic2.jpg | | 5 | domain.com/pic3.jpg | ```
44,758
I'm a 50 yo man doing general core strengthening exercises with adjustable dumbbells at home. Generally each of the exercises I do at medium weight, 3 sets of 10 reps a few times a week. My dumbbell weight settings go up in 5 pound increments. This week I re-checked my maximum weight on all my exercises, increasing most of them, and landed at an awkward point with one of them. My overhead shoulder press now maxes out at 44 pounds on each side (88 pounds total). By my calculation, this gives a per-side heavy lift weight (85%) of 37.4 pounds, and a medium lift weight (75%) of 33.0 pounds. The problem is, both of those numbers are closer to the 35-pound step on my weights than anything else (i.e., my medium and heavy lifts call for the same setting). Trying to do my standard medium exercise at 35 pounds, I can barely complete a single 10-rep set, and fail about halfway through on later ones. What should I do in this situation? * Drop back to the 30-pound setting for 10-rep sets, and wait for some later test to show a higher max weight. * Just use the 35-pound setting, try for 10-rep sets, and wait for that to improve. * Keep the 35-pound weight but reduce the target repetitions. * Something else?
2022/01/14
[ "https://fitness.stackexchange.com/questions/44758", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/36787/" ]
In this scenario, I would look at approaching linear progression with a different metric, perhaps with reps instead of weight. The following is an example of implementing the "Double Progression Method". You're moving from 30 lb x 10 to 35 lb x 10 but that's too big of a jump, you can try 30 lb x 11. If you compare total volume, you're at 300, wanting to move to 350, but you can try 330 instead. Alternately, 35 lb x 9 is going to be 315 which would still be progress when comparing volume. So, my suggestion would be to progress with 35x9 or 30x11, and once those are easier move to 35x10 or 30x12. My preference is to 35x9 since I feel there's value in just handling the heavier dumbbells. This approach doesn't hold true for everything. You can't compare 30x10 to 300x1. In this scenario though, I think it can help to push through.
When the weights don't come in small enough increments, one good option is to vary the reps. I particularly like this approach with weighted dips, but it works for all sorts of exercises, especially upper body pressing. A program aiming for "medium weight, 3 sets of 10 reps a few times a week" depends on sets of 10 and changes the weight to progressively challenge the athlete. Ten reps is roughly equivalent to eight or 12, so one way to work around big weight jumps is to start with 3 sets of 8, then the next workout is 3 sets of 9, then 3x10, then 3x11, then 3x12, then add weight and drop back down to 3x8. Adding sets is another way to stretch out the usefulness of the weight on the lighter side of the jump: after 3x12 do 4x12, then 5x12, then add weight and do 3x8.
2,714,417
I'm running VS 2010 along with Expression Blend 4 beta. I created a MVVM Light project from the supplied templates and I get a System.IO.FileLoadException when I try to view the MainWindow.Xaml in VS 2010 designer window. The template already references System.Windows.Interactivity. Here are the details of the exception: ``` System.IO.FileLoadException Could not load file or assembly 'System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at MS.Internal.Package.VSIsolationProviderService.RemoteReferenceProxy.VsReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.CachingReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.Microsoft.Windows.Design.Metadata.IReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at MS.Internal.Metadata.ClrAssembly.GetRuntimeMetadata(Object reflectionMetadata) at Microsoft.Windows.Design.Metadata.AttributeTableContainer.<MergeAttributesIterator>d__c.MoveNext() at Microsoft.Windows.Design.Metadata.AttributeTableContainer.GetAttributes(Assembly assembly, Type attributeType, Func`2 reflectionMapper) at MS.Internal.Metadata.ClrAssembly.GetAttributes(ITypeMetadata attributeType) at MS.Internal.Design.Metadata.Xaml.XamlAssembly.get_XmlNamespaceCompatibilityMappings() at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata sourceAssembly) at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensions.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata source) at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption() at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier) at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context) at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem() at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem() at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState() at MS.Internal.Host.PersistenceSubsystem.Load() at MS.Internal.Host.Designer.Load() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() ``` System.NotSupportedException An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See <http://go.microsoft.com/fwlink/?LinkId=155569> for more information.
2010/04/26
[ "https://Stackoverflow.com/questions/2714417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148298/" ]
Yes, the issue is that the zip files need to be unblocked before you install. See <http://www.galasoft.ch/mvvm/installing/manually/#unblock> After you unblock the zip file, you can install on top of the existing DLLs, they will be overwritten with the correct version. Greetings, Laurent
If it still doesn't work and you have done what @LBugnion tells to do. Then it is propaly because you run the project from a network location. Try copy the project to a loval drive (could be your desktop). Now it shuold work :D
44,993,914
[![enter image description here](https://i.stack.imgur.com/4kVS3.png)](https://i.stack.imgur.com/4kVS3.png) I entered the Cells in Column A, B, C, D, AND I Want the result as entered in F, G, H, I, so what formula i should insert i the cells
2017/07/09
[ "https://Stackoverflow.com/questions/44993914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8278328/" ]
F3 would be: ``` =IF(ISERROR(MATCH(ROW()-2,A:A,0)),"",ROW()-2) ``` And G3: ``` =IF(LEN(F3),INDEX(B:B,MATCH(F3,A:A,0)),"") ``` copy F3:G3 to H3:I3 and "auto fill" down as you need to [![enter image description here](https://i.stack.imgur.com/pi1uj.png)](https://i.stack.imgur.com/pi1uj.png)
If you want to use a macro instead, then just copy this code into a module in visual basic editor and run it. ``` Sub insertRows() Columns("G:J").EntireColumn.Delete Dim lrow As Long: lrow = Range("A" & Rows.Count).End(xlUp).Row Dim brng As Range: Set brng = Range("A1:D" & lrow) brng.Copy Range("G1"): Range("G1").Value = "After" Dim arng As Range: Set arng = Range("G3:G" & lrow) Dim rng As Range For Each rng In arng If rng <> rng.Offset(, 2) Then If rng > rng.Offset(, 2) Then rng.Resize(, 2).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Else rng.Offset(, 2).Resize(, 2).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End If End If Next rng End Sub ```
44,993,914
[![enter image description here](https://i.stack.imgur.com/4kVS3.png)](https://i.stack.imgur.com/4kVS3.png) I entered the Cells in Column A, B, C, D, AND I Want the result as entered in F, G, H, I, so what formula i should insert i the cells
2017/07/09
[ "https://Stackoverflow.com/questions/44993914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8278328/" ]
F3 would be: ``` =IF(ISERROR(MATCH(ROW()-2,A:A,0)),"",ROW()-2) ``` And G3: ``` =IF(LEN(F3),INDEX(B:B,MATCH(F3,A:A,0)),"") ``` copy F3:G3 to H3:I3 and "auto fill" down as you need to [![enter image description here](https://i.stack.imgur.com/pi1uj.png)](https://i.stack.imgur.com/pi1uj.png)
OMG, this one is difficult but these are the formulas you can try: From `cell F3`: ``` =IF(AND(N(F2)=0,F2<>""),1,IF(AND(NOT(COUNTIF($A$3:$A$22,MIN(INDEX($A$3:$A$22,MATCH(MAX(F$2:F2,H$2:H2),$A$3:$A$22,1)+1),INDEX($C$3:$C$22,MATCH(MAX(F$2:F2,H$2:H2),$C$3:$C$22,1)+1)))),INDEX($A$3:$A$22,MATCH(MAX(F$2:F2,H$2:H2),$A$3:$A$22,1)+1)),"",INDEX($A$3:$A$22,MATCH(MAX(F$2:F2,H$2:H2),$A$3:$A$22,1)+1))) ``` From `cell G3`: ``` =IF(N(F3),INDEX(B:B,MATCH(F3,A:A,0)),"") ``` From `cell H3`: ``` =IF(AND(N(H2)=0,H2<>""),1,IF(AND(NOT(COUNTIF($C$3:$C$22,MIN(INDEX($C$3:$C$22,MATCH(MAX(H$2:H2,F$2:F2),$C$3:$C$22,1)+1),INDEX($A$3:$A$22,MATCH(MAX(H$2:H2,F$2:F2),$A$3:$A$22,1)+1)))),INDEX($C$3:$C$22,MATCH(MAX(H$2:H2,F$2:F2),$C$3:$C$22,1)+1)),"",INDEX($C$3:$C$22,MATCH(MAX(H$2:H2,F$2:F2),$C$3:$C$22,1)+1))) ``` From `cell I3`: ``` =IF(N(H3),INDEX(D:D,MATCH(H3,C:C,0)),"") ``` Basically, the formulas are very similar under both `Debit` and `Credit` columns but just swapping the range references. Try and let me know.
37,264,625
I have obtained an SSL cert from Lets Encrypt and added it to my SSL endpoint on Heroku, but I'm a bit nervous about simply removing Expedited SSL. Is it safe?
2016/05/16
[ "https://Stackoverflow.com/questions/37264625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813273/" ]
No problem with doing that and switching to a new certificate from differente Certificate Authority (CA) such as LetsEncrypt. I always remove the references to the old certificates. A practice I suggest is moving the old certificates to new ones by appending the .backup at the end Based on the [documentation](https://elements.heroku.com/addons/expeditedssl) this is a correct practice as long as DNS is pointed to the right endpoint.
I removed my old Comodo SSL certificate and it worked fine. Make sure you've updated your DNS Target at your domain registrar to point to the SSL endpoint you got when you added the Let's Encrypt cert. (Usually `certified.domain.herokudns.com`)
66,063,248
Nothing will ne happened when I submit product in the the cart. I want to use AJAX without refreshing page. When I submit the console message will be displayed. I'm trying to use AJAX first. Trying to add product in the cart without refreshing page. I need help please :) ***Views Django*** ``` def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) ``` ***Form*** ``` from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) ``` ***HTML Code*** ``` <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> ``` ***JS Code*** ``` $(".buy-product").on('click', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = 1 console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', data: data, success: function(data){ console.log('success') console.log(csrftoken) } }) }) ```
2021/02/05
[ "https://Stackoverflow.com/questions/66063248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11433326/" ]
First, I prefer using anonymous function, then you don't have to create a variable for "this" and can directly use "this" in the function. Can you try this code ? I think there's a problem because your two functions had the same name. ``` <script> import $ from 'jquery'; export default { name: "credit-recharge-component", data() { return { balance2: '' } }, created() { this.onCreate() }, methods: { onCreate: function () { $.ajax({ url: '/Mout/GetBalance', type: 'GET', contentType: 'application/json', success: (data) => { this.balance2 = data; console.log(data) }, error: (error) => { console.log(JSON.stringify(error)); } }); } } }; </script> ```
I believe the problem is the "this" in success function, maybe is not the vue instance. I would try change this arrow function to regular function or to create auxiliar variable. ``` onCreate: function () { var self = this; $.ajax({ url: '/Mout/GetBalance', type: 'GET', contentType: 'application/json', success: (data) => { console.log(self.balance2); self.balance2 = data; console.log(data) }, error: (error) => { console.log(JSON.stringify(error)); } }); } ``` I would log the value in self.balance2 to make sure i had the right "this".
45,909,542
How do I set the options for gulp-htmllint ? I want to exclude any rules pertaining to indent style and id or class style. However, its documentation shows the keys for those has having dashes, ex indent-style or id-class-style, but the dash breaks the code. I tried camelcasing or writing the keys as a string but that didn't seem to make a difference. From what I understand, this is what defines the task, and this is where I have tried to define the rule options: ``` gulp.task('default', function() { return gulp.src('src/index.html') .pipe(htmllint({ indent-style: false, id-class-style: false }, htmllintReporter)); }); ``` And this is the function that defines what you will see in the terminal: ``` function htmllintReporter(filepath, issues) { if (issues.length > 0) { issues.forEach(function (issue) { gutil.log(gutil.colors.cyan('[gulp-htmllint] ') + gutil.colors.white(filepath + ' [' + issue.line + ',' + issue.column + ']: ') + gutil.colors.red('(' + issue.code + ') ' + issue.msg)); }); process.exitCode = 1; } } ```
2017/08/27
[ "https://Stackoverflow.com/questions/45909542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8351238/" ]
Here is an example of the contents of a .htmllintrc file: ``` { "attr-name-style": "dash", "attr-quote-style": "double", "id-class-style": "dash", "indent-style": "spaces", "indent-width": 2, "line-end-style": "lf", "attr-req-value": false, "html-req-lang": true, "title-max-length": 120, "img-req-src": false, "tag-bans": ["!style"] } ``` That literally goes in the same directory as your gulpfile.js or Gruntfile.js-- the same directory as your package.json. (Given super common placement of these files...) You put the above options inside a plain text file and name it ".htmllintrc". There is no file extension, it is literally named just ".htmllintrc". Stolen from: <https://github.com/thisissoon/angular-start/blob/master/.htmllintrc> I am currently enjoying putting together a buildchain for multiple environments. To pass a dev build, regular non-functional html comments are allowed. For a prod build, those unnecessary comments should be removed... How this is relevant is that I am using the same buildchain for all environments and specifying a different options file as needed-- you can pass which options file you want to use and it will override the default .htmllintrc file. > > options.config > > > Type: String Default value: .htmllintrc > > > Configuration file containing htmllint options. > > > <https://github.com/yvanavermaet/gulp-htmllint#optionsconfig>
Never used gulp but just from reading the docs I can see you can define a `.htmllintrc` file and add the options there. ``` { "indent-style": false, "id-class-style": false } ```
476,620
I am running Outlook 2010 connected to an Exchange 2003 server. Often times, the spam that I received is sent to "undisclosed-recipients". I'm guessing that's because my email address (or an email address for a group I am part of) is in the BCC field. Is there a way to find out what BCC address was used to reach me? I looked at the Internet Headers for the message, but am not seeing "Envelope-to", [described in a similar question](https://superuser.com/questions/333590/is-there-anyway-to-identify-which-email-alias-a-sender-used-for-me-if-it-was-lis).
2012/09/18
[ "https://superuser.com/questions/476620", "https://superuser.com", "https://superuser.com/users/143655/" ]
There is no such thing as a "BCC field"; BCC in email is performed by adding the recipient to the envelope but not the headers, which means that they are undetectable unless the email server is explicitly configured to reveal them somehow.
In the internet headers, you should see a line `Received by: xyz for <your email addr>`.
476,620
I am running Outlook 2010 connected to an Exchange 2003 server. Often times, the spam that I received is sent to "undisclosed-recipients". I'm guessing that's because my email address (or an email address for a group I am part of) is in the BCC field. Is there a way to find out what BCC address was used to reach me? I looked at the Internet Headers for the message, but am not seeing "Envelope-to", [described in a similar question](https://superuser.com/questions/333590/is-there-anyway-to-identify-which-email-alias-a-sender-used-for-me-if-it-was-lis).
2012/09/18
[ "https://superuser.com/questions/476620", "https://superuser.com", "https://superuser.com/users/143655/" ]
There is no such thing as a "BCC field"; BCC in email is performed by adding the recipient to the envelope but not the headers, which means that they are undetectable unless the email server is explicitly configured to reveal them somehow.
Here is the simple test case I have created for the BCC field. 1. Create new email with BCC only. [![Screen Shot](https://i.stack.imgur.com/Tq3Kx.png)](https://i.stack.imgur.com/Tq3Kx.png) 2. Check the raw message at received end(Here I sent to Gmail). If you have a close look on the raw message in the screen shot with highlighted **for** then you can see the **BCC** which I have added while sending an email. [![Screen Shot](https://i.stack.imgur.com/51aNJ.png)](https://i.stack.imgur.com/51aNJ.png)
2,638,990
Let $X$ be a $n \times k$ matrix with $n > k$. If the columns of $X$ are orthonormal, then I want to show that the row norms are bounded by 1. My current solutions involves completing $X$ into an orthogonal matrix and then using the fact that $X^T X = X X^T = I$. I would like a more direct argument such as assuming that a row has norm larger than one leads to an immediate contradiction.
2018/02/06
[ "https://math.stackexchange.com/questions/2638990", "https://math.stackexchange.com", "https://math.stackexchange.com/users/431468/" ]
This is just the Pythagorean theorem. Denote the column vectors by $f\_1, \dots, f\_k$ Let $e\_j$ be the usual unit vector with $1$ in the $j$-th position. Then $$ e\_j = \sum\_{l = 1}^k \langle e\_j, f\_l\rangle \ f\_l + u\_j, $$ where $u\_j$ is a vector perpendicular to the span of $f\_1, \dots, f\_k$. Hence $$ 1 = ||e\_j||^2 = \sum\_{l = 1}^k |\langle e\_j, f\_l\rangle |^2 + ||u\_j||^2. $$ Hence $\sum\_{l = 1}^k |\langle e\_j, f\_l\rangle |^2 \le 1$. Note that the $(j, l)$ entry of the matrix is $\langle f\_l, e\_j \rangle$.
The squared row norms of a matrix $X$ with orthonormal columns are also known as the leverage scores of $X$. See section 2.4 of [Sketching as a Tool for Numerical Linear Algebra](https://arxiv.org/abs/1411.4357) for another proof that each of these squared row norms is less than or equal to 1.
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
I love to use explode to get string between two string. this function also works for multiple occurrences. ``` function GetIn($str,$start,$end){ $p1 = explode($start,$str); for($i=1;$i<count($p1);$i++){ $p2 = explode($end,$p1[$i]); $p[] = $p2[0]; } return $p; } ```
There was some great sollutions here, however not perfekt for extracting parts of code from say HTML which was my problem right now, as I need to get script blocks out of the HTML before compressing the HTML. So building on @raina77ow original sollution, expanded by @Cas Tuyn I get this one: ``` $test_strings = [ '0<p>a</p>1<p>b</p>2<p>c</p>3', '0<p>a</p>1<p>b</p>2<p>c</p>', '<p>a</p>1<p>b</p>2<p>c</p>3', '<p>a</p>1<p>b</p>2<p>c</p>', '<p></p>1<p>b' ]; /** * Seperate a block of code by sub blocks. Example, removing all <script>...<script> tags from HTML kode * * @param string $str, text block * @param string $startDelimiter, string to match for start of block to be extracted * @param string $endDelimiter, string to match for ending the block to be extracted * @return array [all full blocks, whats left of string] */ function getDelimitedStrings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, ($contentStart-$startDelimiterLength), ($contentEnd + ($startDelimiterLength*2) +1) - $contentStart); if( $outStart ){ $contents['out'][] = substr($str, ($outStart+$startDelimiterLength+1), $outEnd - $outStart - ($startDelimiterLength*2)); } else if( ($outEnd - $outStart - ($startDelimiterLength-1)) > 0 ){ $contents['out'][] = substr($str, $outStart, $outEnd - $outStart - ($startDelimiterLength-1)); } $startFrom = $contentEnd + $endDelimiterLength; $startFrom = $contentEnd; $outStart = $startFrom; } $total_length = strlen($str); $current_position = $outStart + $startDelimiterLength + 1; if( $current_position < $total_length ) $contents['out'][] = substr($str, $current_position); return $contents; } foreach($test_strings AS $string){ var_dump( getDelimitedStrings($string, '<p>', '</p>') ); } ``` This will extract all wlements with the possible innerHTML aswell, giving this result: ``` array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=4) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) 3 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '1' (length=1) 1 => string '2' (length=1) 2 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) array (size=2) 'in' => array (size=1) 0 => string '<p></p>' (length=7) 'out' => array (size=1) 0 => string '1<p>b' (length=5) ``` You can see a demo here: [3v4l.org/TQLmn](https://3v4l.org/TQLmn)
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
You can do this using regex: ``` function getStringsBetween($string, $start, $end) { $pattern = sprintf( '/%s(.*?)%s/', preg_quote($start), preg_quote($end) ); preg_match_all($pattern, $string, $matches); return $matches[1]; } ```
There was some great sollutions here, however not perfekt for extracting parts of code from say HTML which was my problem right now, as I need to get script blocks out of the HTML before compressing the HTML. So building on @raina77ow original sollution, expanded by @Cas Tuyn I get this one: ``` $test_strings = [ '0<p>a</p>1<p>b</p>2<p>c</p>3', '0<p>a</p>1<p>b</p>2<p>c</p>', '<p>a</p>1<p>b</p>2<p>c</p>3', '<p>a</p>1<p>b</p>2<p>c</p>', '<p></p>1<p>b' ]; /** * Seperate a block of code by sub blocks. Example, removing all <script>...<script> tags from HTML kode * * @param string $str, text block * @param string $startDelimiter, string to match for start of block to be extracted * @param string $endDelimiter, string to match for ending the block to be extracted * @return array [all full blocks, whats left of string] */ function getDelimitedStrings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, ($contentStart-$startDelimiterLength), ($contentEnd + ($startDelimiterLength*2) +1) - $contentStart); if( $outStart ){ $contents['out'][] = substr($str, ($outStart+$startDelimiterLength+1), $outEnd - $outStart - ($startDelimiterLength*2)); } else if( ($outEnd - $outStart - ($startDelimiterLength-1)) > 0 ){ $contents['out'][] = substr($str, $outStart, $outEnd - $outStart - ($startDelimiterLength-1)); } $startFrom = $contentEnd + $endDelimiterLength; $startFrom = $contentEnd; $outStart = $startFrom; } $total_length = strlen($str); $current_position = $outStart + $startDelimiterLength + 1; if( $current_position < $total_length ) $contents['out'][] = substr($str, $current_position); return $contents; } foreach($test_strings AS $string){ var_dump( getDelimitedStrings($string, '<p>', '</p>') ); } ``` This will extract all wlements with the possible innerHTML aswell, giving this result: ``` array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=4) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) 3 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '1' (length=1) 1 => string '2' (length=1) 2 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) array (size=2) 'in' => array (size=1) 0 => string '<p></p>' (length=7) 'out' => array (size=1) 0 => string '1<p>b' (length=5) ``` You can see a demo here: [3v4l.org/TQLmn](https://3v4l.org/TQLmn)
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
One possible approach: ``` function getContents($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); if (false === $contentEnd) { break; } $contents[] = substr($str, $contentStart, $contentEnd - $contentStart); $startFrom = $contentEnd + $endDelimiterLength; } return $contents; } ``` Usage: ``` $sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>'; print_r( getContents($sample, '<start>', '<end>') ); /* Array ( [0] => One [1] => TwoTwo [2] => Four [3] => Five ) */ ``` [**Demo**](https://eval.in/225018).
I needed to find all these occurences between specific first and last tag and change them somehow and get back changed string. So I added this small code to raina77ow approach after the function. ``` $sample = '<start>One<end> aaa <start>TwoTwo<end> Three <start>Four<end> aaaaa <start>Five<end>'; $sample_temp = getContents($sample, '<start>', '<end>'); $i = 1; foreach($sample_temp as $value) { $value2 = $value.'-'.$i; //there you can change the variable $sample=str_replace('<start>'.$value.'<end>',$value2,$sample); $i = ++$i; } echo $sample; ``` Now output sample has deleted tags and all strings between them has added number like this: One-1 aaa TwoTwo-2 Three Four-3 aaaaa Five-4 But you can do whatever else with them. Maybe could be helpful for someone.
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
I love to use explode to get string between two string. this function also works for multiple occurrences. ``` function GetIn($str,$start,$end){ $p1 = explode($start,$str); for($i=1;$i<count($p1);$i++){ $p2 = explode($end,$p1[$i]); $p[] = $p2[0]; } return $p; } ```
I also needed the text outside the pattern. So I changed the answer from raina77ow above a little: ``` function get_delimited_strings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, $contentStart, $contentEnd - $contentStart); $contents['out'][] = substr($str, $outStart, $outEnd - $outStart); $startFrom = $contentEnd + $endDelimiterLength; $outStart = $startFrom; } $contents['out'][] = substr($str, $outStart, $contentEnd - $outStart); return $contents; } ``` Usage: ``` $str = "Bore layer thickness [2 mm] instead of [1,25 mm] with [0,1 mm] deviation."; $cas = get_delimited_strings($str, "[", "]"); ``` gives: ``` array(2) { ["in"]=> array(3) { [0]=> string(4) "2 mm" [1]=> string(7) "1,25 mm" [2]=> string(6) "0,1 mm" } ["out"]=> array(4) { [0]=> string(21) "Bore layer thickness " [1]=> string(12) " instead of " [2]=> string(6) " with " [3]=> string(10) " deviation" } } ```
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
There was some great sollutions here, however not perfekt for extracting parts of code from say HTML which was my problem right now, as I need to get script blocks out of the HTML before compressing the HTML. So building on @raina77ow original sollution, expanded by @Cas Tuyn I get this one: ``` $test_strings = [ '0<p>a</p>1<p>b</p>2<p>c</p>3', '0<p>a</p>1<p>b</p>2<p>c</p>', '<p>a</p>1<p>b</p>2<p>c</p>3', '<p>a</p>1<p>b</p>2<p>c</p>', '<p></p>1<p>b' ]; /** * Seperate a block of code by sub blocks. Example, removing all <script>...<script> tags from HTML kode * * @param string $str, text block * @param string $startDelimiter, string to match for start of block to be extracted * @param string $endDelimiter, string to match for ending the block to be extracted * @return array [all full blocks, whats left of string] */ function getDelimitedStrings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, ($contentStart-$startDelimiterLength), ($contentEnd + ($startDelimiterLength*2) +1) - $contentStart); if( $outStart ){ $contents['out'][] = substr($str, ($outStart+$startDelimiterLength+1), $outEnd - $outStart - ($startDelimiterLength*2)); } else if( ($outEnd - $outStart - ($startDelimiterLength-1)) > 0 ){ $contents['out'][] = substr($str, $outStart, $outEnd - $outStart - ($startDelimiterLength-1)); } $startFrom = $contentEnd + $endDelimiterLength; $startFrom = $contentEnd; $outStart = $startFrom; } $total_length = strlen($str); $current_position = $outStart + $startDelimiterLength + 1; if( $current_position < $total_length ) $contents['out'][] = substr($str, $current_position); return $contents; } foreach($test_strings AS $string){ var_dump( getDelimitedStrings($string, '<p>', '</p>') ); } ``` This will extract all wlements with the possible innerHTML aswell, giving this result: ``` array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=4) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) 3 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '1' (length=1) 1 => string '2' (length=1) 2 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) array (size=2) 'in' => array (size=1) 0 => string '<p></p>' (length=7) 'out' => array (size=1) 0 => string '1<p>b' (length=5) ``` You can see a demo here: [3v4l.org/TQLmn](https://3v4l.org/TQLmn)
I also needed the text outside the pattern. So I changed the answer from raina77ow above a little: ``` function get_delimited_strings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, $contentStart, $contentEnd - $contentStart); $contents['out'][] = substr($str, $outStart, $outEnd - $outStart); $startFrom = $contentEnd + $endDelimiterLength; $outStart = $startFrom; } $contents['out'][] = substr($str, $outStart, $contentEnd - $outStart); return $contents; } ``` Usage: ``` $str = "Bore layer thickness [2 mm] instead of [1,25 mm] with [0,1 mm] deviation."; $cas = get_delimited_strings($str, "[", "]"); ``` gives: ``` array(2) { ["in"]=> array(3) { [0]=> string(4) "2 mm" [1]=> string(7) "1,25 mm" [2]=> string(6) "0,1 mm" } ["out"]=> array(4) { [0]=> string(21) "Bore layer thickness " [1]=> string(12) " instead of " [2]=> string(6) " with " [3]=> string(10) " deviation" } } ```
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
I needed to find all these occurences between specific first and last tag and change them somehow and get back changed string. So I added this small code to raina77ow approach after the function. ``` $sample = '<start>One<end> aaa <start>TwoTwo<end> Three <start>Four<end> aaaaa <start>Five<end>'; $sample_temp = getContents($sample, '<start>', '<end>'); $i = 1; foreach($sample_temp as $value) { $value2 = $value.'-'.$i; //there you can change the variable $sample=str_replace('<start>'.$value.'<end>',$value2,$sample); $i = ++$i; } echo $sample; ``` Now output sample has deleted tags and all strings between them has added number like this: One-1 aaa TwoTwo-2 Three Four-3 aaaaa Five-4 But you can do whatever else with them. Maybe could be helpful for someone.
There was some great sollutions here, however not perfekt for extracting parts of code from say HTML which was my problem right now, as I need to get script blocks out of the HTML before compressing the HTML. So building on @raina77ow original sollution, expanded by @Cas Tuyn I get this one: ``` $test_strings = [ '0<p>a</p>1<p>b</p>2<p>c</p>3', '0<p>a</p>1<p>b</p>2<p>c</p>', '<p>a</p>1<p>b</p>2<p>c</p>3', '<p>a</p>1<p>b</p>2<p>c</p>', '<p></p>1<p>b' ]; /** * Seperate a block of code by sub blocks. Example, removing all <script>...<script> tags from HTML kode * * @param string $str, text block * @param string $startDelimiter, string to match for start of block to be extracted * @param string $endDelimiter, string to match for ending the block to be extracted * @return array [all full blocks, whats left of string] */ function getDelimitedStrings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, ($contentStart-$startDelimiterLength), ($contentEnd + ($startDelimiterLength*2) +1) - $contentStart); if( $outStart ){ $contents['out'][] = substr($str, ($outStart+$startDelimiterLength+1), $outEnd - $outStart - ($startDelimiterLength*2)); } else if( ($outEnd - $outStart - ($startDelimiterLength-1)) > 0 ){ $contents['out'][] = substr($str, $outStart, $outEnd - $outStart - ($startDelimiterLength-1)); } $startFrom = $contentEnd + $endDelimiterLength; $startFrom = $contentEnd; $outStart = $startFrom; } $total_length = strlen($str); $current_position = $outStart + $startDelimiterLength + 1; if( $current_position < $total_length ) $contents['out'][] = substr($str, $current_position); return $contents; } foreach($test_strings AS $string){ var_dump( getDelimitedStrings($string, '<p>', '</p>') ); } ``` This will extract all wlements with the possible innerHTML aswell, giving this result: ``` array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=4) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) 3 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '1' (length=1) 1 => string '2' (length=1) 2 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) array (size=2) 'in' => array (size=1) 0 => string '<p></p>' (length=7) 'out' => array (size=1) 0 => string '1<p>b' (length=5) ``` You can see a demo here: [3v4l.org/TQLmn](https://3v4l.org/TQLmn)
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
One possible approach: ``` function getContents($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); if (false === $contentEnd) { break; } $contents[] = substr($str, $contentStart, $contentEnd - $contentStart); $startFrom = $contentEnd + $endDelimiterLength; } return $contents; } ``` Usage: ``` $sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>'; print_r( getContents($sample, '<start>', '<end>') ); /* Array ( [0] => One [1] => TwoTwo [2] => Four [3] => Five ) */ ``` [**Demo**](https://eval.in/225018).
I also needed the text outside the pattern. So I changed the answer from raina77ow above a little: ``` function get_delimited_strings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, $contentStart, $contentEnd - $contentStart); $contents['out'][] = substr($str, $outStart, $outEnd - $outStart); $startFrom = $contentEnd + $endDelimiterLength; $outStart = $startFrom; } $contents['out'][] = substr($str, $outStart, $contentEnd - $outStart); return $contents; } ``` Usage: ``` $str = "Bore layer thickness [2 mm] instead of [1,25 mm] with [0,1 mm] deviation."; $cas = get_delimited_strings($str, "[", "]"); ``` gives: ``` array(2) { ["in"]=> array(3) { [0]=> string(4) "2 mm" [1]=> string(7) "1,25 mm" [2]=> string(6) "0,1 mm" } ["out"]=> array(4) { [0]=> string(21) "Bore layer thickness " [1]=> string(12) " instead of " [2]=> string(6) " with " [3]=> string(10) " deviation" } } ```
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
One possible approach: ``` function getContents($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); if (false === $contentEnd) { break; } $contents[] = substr($str, $contentStart, $contentEnd - $contentStart); $startFrom = $contentEnd + $endDelimiterLength; } return $contents; } ``` Usage: ``` $sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>'; print_r( getContents($sample, '<start>', '<end>') ); /* Array ( [0] => One [1] => TwoTwo [2] => Four [3] => Five ) */ ``` [**Demo**](https://eval.in/225018).
There was some great sollutions here, however not perfekt for extracting parts of code from say HTML which was my problem right now, as I need to get script blocks out of the HTML before compressing the HTML. So building on @raina77ow original sollution, expanded by @Cas Tuyn I get this one: ``` $test_strings = [ '0<p>a</p>1<p>b</p>2<p>c</p>3', '0<p>a</p>1<p>b</p>2<p>c</p>', '<p>a</p>1<p>b</p>2<p>c</p>3', '<p>a</p>1<p>b</p>2<p>c</p>', '<p></p>1<p>b' ]; /** * Seperate a block of code by sub blocks. Example, removing all <script>...<script> tags from HTML kode * * @param string $str, text block * @param string $startDelimiter, string to match for start of block to be extracted * @param string $endDelimiter, string to match for ending the block to be extracted * @return array [all full blocks, whats left of string] */ function getDelimitedStrings($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); $outEnd = $contentStart - 1; if (false === $contentEnd) { break; } $contents['in'][] = substr($str, ($contentStart-$startDelimiterLength), ($contentEnd + ($startDelimiterLength*2) +1) - $contentStart); if( $outStart ){ $contents['out'][] = substr($str, ($outStart+$startDelimiterLength+1), $outEnd - $outStart - ($startDelimiterLength*2)); } else if( ($outEnd - $outStart - ($startDelimiterLength-1)) > 0 ){ $contents['out'][] = substr($str, $outStart, $outEnd - $outStart - ($startDelimiterLength-1)); } $startFrom = $contentEnd + $endDelimiterLength; $startFrom = $contentEnd; $outStart = $startFrom; } $total_length = strlen($str); $current_position = $outStart + $startDelimiterLength + 1; if( $current_position < $total_length ) $contents['out'][] = substr($str, $current_position); return $contents; } foreach($test_strings AS $string){ var_dump( getDelimitedStrings($string, '<p>', '</p>') ); } ``` This will extract all wlements with the possible innerHTML aswell, giving this result: ``` array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=4) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) 3 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '0' (length=1) 1 => string '1' (length=1) 2 => string '2' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=3) 0 => string '1' (length=1) 1 => string '2' (length=1) 2 => string '3' (length=1) array (size=2) 'in' => array (size=3) 0 => string '<p>a</p>' (length=8) 1 => string '<p>b</p>' (length=8) 2 => string '<p>c</p>' (length=8) 'out' => array (size=2) 0 => string '1' (length=1) 1 => string '2' (length=1) array (size=2) 'in' => array (size=1) 0 => string '<p></p>' (length=7) 'out' => array (size=1) 0 => string '1<p>b' (length=5) ``` You can see a demo here: [3v4l.org/TQLmn](https://3v4l.org/TQLmn)
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
One possible approach: ``` function getContents($str, $startDelimiter, $endDelimiter) { $contents = array(); $startDelimiterLength = strlen($startDelimiter); $endDelimiterLength = strlen($endDelimiter); $startFrom = $contentStart = $contentEnd = 0; while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) { $contentStart += $startDelimiterLength; $contentEnd = strpos($str, $endDelimiter, $contentStart); if (false === $contentEnd) { break; } $contents[] = substr($str, $contentStart, $contentEnd - $contentStart); $startFrom = $contentEnd + $endDelimiterLength; } return $contents; } ``` Usage: ``` $sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>'; print_r( getContents($sample, '<start>', '<end>') ); /* Array ( [0] => One [1] => TwoTwo [2] => Four [3] => Five ) */ ``` [**Demo**](https://eval.in/225018).
You can do this using regex: ``` function getStringsBetween($string, $start, $end) { $pattern = sprintf( '/%s(.*?)%s/', preg_quote($start), preg_quote($end) ); preg_match_all($pattern, $string, $matches); return $matches[1]; } ```
27,078,259
[I found this function](https://stackoverflow.com/a/9826656) which finds data between two strings of text, html or whatever. How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data). ``` function getStringBetween($string, $start, $end) { $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } ```
2014/11/22
[ "https://Stackoverflow.com/questions/27078259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778578/" ]
You can do this using regex: ``` function getStringsBetween($string, $start, $end) { $pattern = sprintf( '/%s(.*?)%s/', preg_quote($start), preg_quote($end) ); preg_match_all($pattern, $string, $matches); return $matches[1]; } ```
I needed to find all these occurences between specific first and last tag and change them somehow and get back changed string. So I added this small code to raina77ow approach after the function. ``` $sample = '<start>One<end> aaa <start>TwoTwo<end> Three <start>Four<end> aaaaa <start>Five<end>'; $sample_temp = getContents($sample, '<start>', '<end>'); $i = 1; foreach($sample_temp as $value) { $value2 = $value.'-'.$i; //there you can change the variable $sample=str_replace('<start>'.$value.'<end>',$value2,$sample); $i = ++$i; } echo $sample; ``` Now output sample has deleted tags and all strings between them has added number like this: One-1 aaa TwoTwo-2 Three Four-3 aaaaa Five-4 But you can do whatever else with them. Maybe could be helpful for someone.
74,434,797
I want to validate that all `values` in a dictionary adhere to a schema while the `keys` can be whatever. Is there a better way to do this than just using a pattern that matches everything: ```json "foo": { "type": "object", "patternProperties": { "^.*$": { "$ref": "#/$defs/bar" } } } ```
2022/11/14
[ "https://Stackoverflow.com/questions/74434797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16543731/" ]
Using `patternProperties` like you're doing is that best way, although you can simplify the regex to an empty string because regexes aren't implicitly anchored in JSON Schema. ```json { "type": "object", "patternProperties": { "": { "$ref": "#/$defs/bar" } } } ``` The other option is to use `additionalProperties`, which is less verbose, but can lead to bugs. ```json { "type": "object", "additionalProperties": { "$ref": "#/$defs/bar" } } ``` The problem with this is that it's only accidentally the behavior you really want. What you want is to validate *all* properties against this schema. `additionalProperties` validates only the properties that aren't declared with `properties` or `patternProperties`. If later someone wants to add an additional constraint to a specific property and adds `properties`, they're going to break this schema unless they rewrite the `additionalProperties` using `patternProperties`. It's one of those small things that's an unlikely to occur, but when it does, it's been known to be a source of bugs.
I would suggest to use the `additionalProperties` keyword where you can also set a schema. More details [here](https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties) Using `patternProperties`, the validator needs to run a RegExp check for each property which takes time.
27,284,007
I have a file with lines like this: ``` r1 1 10 r2 10 1 #second bigger than third (10>1) r3 5 2 # "" "" (5>2) r4 10 20 ``` And I would like to reorder the lines with the second word bigger than the third, changing the [3] possition into [2] possition. Desired output: ``` r1 1 10 r2 1 10 r3 2 5 r4 10 20 ``` I have made a code that reorders the lines, but it only outputs the reordered lines, but not all the lines: ``` with open('test','r') as file, open('reorderedtest','w')as out: for line in file: splitLine = line.split("\t") reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ] if int(splitLine[1]) > int(splitLine[2]): str = " " print str.join(reorderedlist) ``` And it only prints: ``` r2 1 10 r3 2 5 ``` Any ideas to get my desired output?
2014/12/04
[ "https://Stackoverflow.com/questions/27284007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4208026/" ]
The simplest modification to your existing code is this: ``` with open('test','r') as file, open('reorderedtest','w')as out: for line in file: splitLine = line.split("\t") reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ] if int(splitLine[6]) > int(splitLine[7]): str = " " print str.join(reorderedlist) else: print line ```
This will work for any number of columns, where you have `r#` in the first column, then any number of numeric columns following. ``` with open('test.txt') as fIn, open('out.txt', 'w') as fOut: for line in fIn: data = line.split() first = data[0] # r value values = sorted(map(int, data[1:])) # sorts based on numeric value fOut.write('{} {}\n'.format(first, ' '.join(str(i) for i in values)) # write values back out ``` Resulting `out.txt` file ``` r1 1 10 r2 1 10 r3 2 5 r4 10 20 ```
17,767,341
Given a JS as follows: ```js for (c in chars) { for (i in data) { if (data[i].item === chars[c]) { // do my stuff; } else { /* do something else */} } } ``` and data such: ```js var chars = [ 'A', 'B', 'C', 'A', 'C' ]; var data = [ {'item':'A', 'rank': '1'}, {'item':'B', 'rank': '2'}, {'item':'C', 'rank': '3'} // no duplicate ]; ``` Is there a simpler syntax to express that rather than nested `for` loops and inner conditions? I try to match two datasets, more precisely to use `chars`'s keys to iterate `data` and find values.
2013/07/20
[ "https://Stackoverflow.com/questions/17767341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974961/" ]
You could do this: ``` for (i = 0; i < data.length; i++) { if (chars.indexOf(data[i].item) != -1) { // Do something } else { // Do something else } } ``` However, if `chars` is large, I would create an object whose keys are the elements of `chars` and use `if (chars_obj[data[i].item])`. This is more efficient than searching an array every time.
Since you tagged your question jquery, you could use a jquery solution: ```js $.each(chars, function (cndx, chr) { $.each(data, function (dndx, datum) { if (datum.item === chr) { // do my stuff; } else { /* do something else */ } } }); ``` Not any more succinct, but at least you don't have to index.
17,767,341
Given a JS as follows: ```js for (c in chars) { for (i in data) { if (data[i].item === chars[c]) { // do my stuff; } else { /* do something else */} } } ``` and data such: ```js var chars = [ 'A', 'B', 'C', 'A', 'C' ]; var data = [ {'item':'A', 'rank': '1'}, {'item':'B', 'rank': '2'}, {'item':'C', 'rank': '3'} // no duplicate ]; ``` Is there a simpler syntax to express that rather than nested `for` loops and inner conditions? I try to match two datasets, more precisely to use `chars`'s keys to iterate `data` and find values.
2013/07/20
[ "https://Stackoverflow.com/questions/17767341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974961/" ]
An alternative to simplifying the code would be to encapsulate and abstract it away into a utility that accepts callbacks, than reuse that whenever needed, like so: ```js // definition function eachChar(onMatch, onMismatch) { for (c in chars) { for (i in data) { if (data[i].item === chars[c]) { typeof onMatch === 'function' && onMatch(); } else { typeof onMismatch === 'function' && onMismatch(); } } } } // usage examples eachChar(function() { // do something when it's a match }); eachChar(function() { // do something when it's a match }, function() { // do something else when it's not }); ``` See a [**live demo on jsFiddle**](http://jsfiddle.net/J8vUr/2/). --- As a sidenote, you would want to explicitly declare variables used as loop indexes, as to not exposing them in an outer scope (e.g. the *global* scope): ```js // that: for (c in chars) { for (i in data) { // would become this: for (var c in chars) { for (var i in data) { ```
Since you tagged your question jquery, you could use a jquery solution: ```js $.each(chars, function (cndx, chr) { $.each(data, function (dndx, datum) { if (datum.item === chr) { // do my stuff; } else { /* do something else */ } } }); ``` Not any more succinct, but at least you don't have to index.
6,687,806
I've tried to use Eclipse on Linux but was not able to get it to work after about 4 hours of trying and regressed to just inserting echo comments everywhere like I had been doing. Now when I debug my Javascript in IE, I just hit F12 and a few more keys and I'm stepping through the Javascript. I'm back on Windows so I need a Window Solution that is hopeufully simple, I'm not lazy - just pressed for time. It would be cool if once javascript passed control to PHP, the debugger just kept stepping into the PHP, but does this even exist?
2011/07/14
[ "https://Stackoverflow.com/questions/6687806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Sounds like you are looking for something like **[FirePHP](http://www.firephp.org/)** or **[ChromePHP](http://www.chromephp.com/)**. Those are Firefox and Chrome extensions which allow you to display anything that your PHP script output during runtime in either **[Firebug](http://getfirebug.com/)** (needs to be installed in Firefox) or native Chrome Developer Tools (doesn't require any extension in Chrome). Keep in mind though that they are merely capable of displaying messages from your script and don't offer options such as watches, breakpoints etc. A full-blooded PHP debugger / profiler like **[xDebug](http://xdebug.org/)** would still be a better solution in my opinion offering you a much better and leaner way of debugging.
FirePHP is a good dubugger for PHP scripts.
6,687,806
I've tried to use Eclipse on Linux but was not able to get it to work after about 4 hours of trying and regressed to just inserting echo comments everywhere like I had been doing. Now when I debug my Javascript in IE, I just hit F12 and a few more keys and I'm stepping through the Javascript. I'm back on Windows so I need a Window Solution that is hopeufully simple, I'm not lazy - just pressed for time. It would be cool if once javascript passed control to PHP, the debugger just kept stepping into the PHP, but does this even exist?
2011/07/14
[ "https://Stackoverflow.com/questions/6687806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
FirePHP is a good dubugger for PHP scripts.
Netbeans for php, Chrome netbeans extension and configure Netbeans to use internal php web server. It runs out of the box.
6,687,806
I've tried to use Eclipse on Linux but was not able to get it to work after about 4 hours of trying and regressed to just inserting echo comments everywhere like I had been doing. Now when I debug my Javascript in IE, I just hit F12 and a few more keys and I'm stepping through the Javascript. I'm back on Windows so I need a Window Solution that is hopeufully simple, I'm not lazy - just pressed for time. It would be cool if once javascript passed control to PHP, the debugger just kept stepping into the PHP, but does this even exist?
2011/07/14
[ "https://Stackoverflow.com/questions/6687806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Sounds like you are looking for something like **[FirePHP](http://www.firephp.org/)** or **[ChromePHP](http://www.chromephp.com/)**. Those are Firefox and Chrome extensions which allow you to display anything that your PHP script output during runtime in either **[Firebug](http://getfirebug.com/)** (needs to be installed in Firefox) or native Chrome Developer Tools (doesn't require any extension in Chrome). Keep in mind though that they are merely capable of displaying messages from your script and don't offer options such as watches, breakpoints etc. A full-blooded PHP debugger / profiler like **[xDebug](http://xdebug.org/)** would still be a better solution in my opinion offering you a much better and leaner way of debugging.
Netbeans for php, Chrome netbeans extension and configure Netbeans to use internal php web server. It runs out of the box.
69,321,976
I can't seem to figure out why the first console.log is displaying the parameter correctly but the second shows undefined. Console Log Output: ``` text undefined ``` Code: ``` ngOnInit() { this.getPuzzle(); } getPuzzle() { this.restProviderService.getPuzzle(this.gameService.getGameId()).subscribe(puzzle => { this.puzzleType = puzzle.type; this.puzzleValue = puzzle.value; console.log(this.puzzleType); setTimeout(this.handlePuzzle , 3000); }); } handlePuzzle() { console.log(this.puzzleType); if (this.puzzleType == 'text') { new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{ text: 'hello', delay: 2000, x: 2 }], { fontSize: 25, strokeWidth: 1.5, duration: 5000, color: "black" }); } } ```
2021/09/24
[ "https://Stackoverflow.com/questions/69321976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2570937/" ]
When you pass the function `this.handlePuzzle` to `setTimeout` the `this` representing your class is lost, and `handlePuzzle` receives the `setTimeout`'s `this` instead. Use an arrow function instead of passing the function itself: ```js setTimeout(() => this.handlePuzzle(), 3000); ```
Inside JS event listeners `this` refers to the event target. But inside the `handlePuzzle` method (sort of an event listener), you need `this` to refer to the current object instance (as usual in a method). You have 2 solutions: * Use an arrow callback. Arrow callbacks preserve the value of `this`. `setTimeout(()=>this.handlePuzzle(), 3000)` or in your method declaration `handlePuzzle=()=> { console.log(this.puzzleType);` * Use `bind` to set the value of `this`. `setTimeout(this.handlePuzzle.bind(this), 3000);` or, in the constructor `this.handlePuzzle = this.handlePuzzle.bind(this);` For more details, refer to the following article. <https://dev.to/alexdevero/a-quick-guide-to-this-keyword-in-javascript-what-this-is-and-when-7i5>
375,360
I'm trying to associate a previously created style with a layer, according to <https://docs.geoserver.org/latest/en/api/#1.0.0/styles.yaml>, through a NodeJS code. POSTing to: > > http://...:8080/geoserver/rest/layers/camada\_de\_estacoes\_3/styles?default=true > > > Body: ``` { name: "camada_de_estacoes_3", filename: "camada_de_estacoes_3.sld" } ``` PS1: yes, style with same name as layer; PS2: also tried with "[workspace name]:" in front of names of things, no success; PS3: Geoserver version 2.13.2. Response: `status 500 - "name"` What am I doing wrong? Log piece: > > 2020-09-29 12:00:22,490 ERROR [geoserver.rest] - name > com.thoughtworks.xstream.mapper.CannotResolveClassException: name at > com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:81) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:79) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:74) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.SecurityMapper.realClass(SecurityMapper.java:71) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > org.geoserver.config.util.SecureXStream$DetailedSecurityExceptionWrapper.realClass(SecureXStream.java:175) > at > com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:125) > at > com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:47) > at > com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29) > at > com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:133) > at > com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32) > at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1486) at > com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1466) at > com.thoughtworks.xstream.XStream.fromXML(XStream.java:1346) at > org.geoserver.config.util.XStreamPersister.load(XStreamPersister.java:667) > at > org.geoserver.rest.converters.XStreamJSONMessageConverter.readInternal(XStreamJSONMessageConverter.java:59) > > > (...)
2020/09/29
[ "https://gis.stackexchange.com/questions/375360", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/50144/" ]
Seems my `body` was missing a "root property" called `style`. The glue came from switching from "Example Value" to "Model" in the API documentation about this specific endpoint. So, `body` is now: ``` { style: { name: "camada_de_estacoes_3" } } ```
I encountered the same issue in version 2.19 of GeoServer. I logged it as a bug on the GeoServer Jira board. <https://osgeo-org.atlassian.net/browse/GEOS-10771>
4,719,386
I have a Java application that downloads information (Entities) from our server. I use a Download thread to download the data. The flow of the download process is as follows: 1. Log in - The user entity is downloaded 2. Based on the User Entity, download a 'Community' entities List and Display in drop down 3. Based on Community drop down selection, Download and show 'Org Tree' in a JTree 4. Based on Node selection, download Category entities and display in drop down 5. Based on Category selection, download Sub Category entities and display in drop down 6. Based on Sub Category selection download a large data set and save it The download occurs in a thread so the GUI does not 'freeze'. It also allows me to update a Progress Bar. I need help with managing this process. The main problem is when I download entity data I have to find a way to wait for the thread to finish before attempting to get the entity and move to the next step in the app flow. So far I have used a modal dialog to control flow. I start the thread, pop up a modal and then dispose of the modal when the thread is finished. The modal/thread are Observer/Observable the thread does a set changed when it is finished and the dialog disposes. Displaying a modal effectively stops the flow of the application so it can wait for the download to finish. I also tried just moving all the work flow to Observers. All relevant GUI in the process are Observers. Each update method waits for the download to finish and then calls the next piece of GUI which does its own downloading. So far I found these two methods produce code that is hard to follow. I would like to 'centralize' this work flow so other developers are not pulling out their hair when they try to follow it. My Question is: Do you have any suggestions/examples where a work flow such as this can be managed in a way that produces code that is easy to follow? I know 'easy' is a relative term and I know my both my options already work but I would like to get some ideas from other coders while I still have time to change it. Thank you very much.
2011/01/18
[ "https://Stackoverflow.com/questions/4719386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119179/" ]
You might want to look into using the `Future` interface. Stop by <http://download.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html> It has all you might need to make these tasks easier.
You have to create a "model" for your view, representing the current state of your application. For a tree e.g. it is reasonable to show a "Loading"-node when someone openes a treenode, because else the GUI hangs on opening a node. If the loading thread finishes loading the node, the "Loading"-node is replaced with the results of the asynchronous action. This makes it easy to open multiple nodes in parallel, because the worker threads all are just responsible for a single child node. Similar when downloading something: The workers then update a download progress. The downloads-Dialog of Firefox comes to mind here. Good GUIs aren't easy :).
4,719,386
I have a Java application that downloads information (Entities) from our server. I use a Download thread to download the data. The flow of the download process is as follows: 1. Log in - The user entity is downloaded 2. Based on the User Entity, download a 'Community' entities List and Display in drop down 3. Based on Community drop down selection, Download and show 'Org Tree' in a JTree 4. Based on Node selection, download Category entities and display in drop down 5. Based on Category selection, download Sub Category entities and display in drop down 6. Based on Sub Category selection download a large data set and save it The download occurs in a thread so the GUI does not 'freeze'. It also allows me to update a Progress Bar. I need help with managing this process. The main problem is when I download entity data I have to find a way to wait for the thread to finish before attempting to get the entity and move to the next step in the app flow. So far I have used a modal dialog to control flow. I start the thread, pop up a modal and then dispose of the modal when the thread is finished. The modal/thread are Observer/Observable the thread does a set changed when it is finished and the dialog disposes. Displaying a modal effectively stops the flow of the application so it can wait for the download to finish. I also tried just moving all the work flow to Observers. All relevant GUI in the process are Observers. Each update method waits for the download to finish and then calls the next piece of GUI which does its own downloading. So far I found these two methods produce code that is hard to follow. I would like to 'centralize' this work flow so other developers are not pulling out their hair when they try to follow it. My Question is: Do you have any suggestions/examples where a work flow such as this can be managed in a way that produces code that is easy to follow? I know 'easy' is a relative term and I know my both my options already work but I would like to get some ideas from other coders while I still have time to change it. Thank you very much.
2011/01/18
[ "https://Stackoverflow.com/questions/4719386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119179/" ]
I think the most common method to do this in recent versions of Java is to use SwingWorker: <http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html> It allows you to fire off background tasks and gives you a convenient done() method that executes on the Swing EDT.
You have to create a "model" for your view, representing the current state of your application. For a tree e.g. it is reasonable to show a "Loading"-node when someone openes a treenode, because else the GUI hangs on opening a node. If the loading thread finishes loading the node, the "Loading"-node is replaced with the results of the asynchronous action. This makes it easy to open multiple nodes in parallel, because the worker threads all are just responsible for a single child node. Similar when downloading something: The workers then update a download progress. The downloads-Dialog of Firefox comes to mind here. Good GUIs aren't easy :).
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
Microsoft has made it simple to activate Windows 10. On new machines the product key is stored in BIOs and is used automatically by the Windows when connected to the Internet. In Windows 10 hardware activation is used. Your Windows 10 will be automatically activated until you don't make changes to the hardware. If you want to install same version as fresh no problem click I don't have a product key link during installation and it will be activated automatically. You can also switch between 32-bit and 64-bit without need of a key in the same edition. If you want to see OEM details visit Microsoft live and check devices tab. You will get everything there.
Yes Windows 10 key is stored in the BIOS, in the event you need a restore, as long as you use the same version so either Pro or Home, it will activate automatically. You can prove this to your self, by downloading any product key finder on google and the last 5 digits will be displayed for you. Also the code is normally placed on a sticker under the laptop or under the battery. Thanks!
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
Get into command prompt by searching for it or doing the Windows key and R button and typing `cmd` (it should pop up). Then type this command in exactly as is: ``` wmic path softwarelicensingservice get OA3xOriginalProductKey ``` And your product key should pop up right after. voila
Yes Windows 10 key is stored in the BIOS, in the event you need a restore, as long as you use the same version so either Pro or Home, it will activate automatically. You can prove this to your self, by downloading any product key finder on google and the last 5 digits will be displayed for you. Also the code is normally placed on a sticker under the laptop or under the battery. Thanks!
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
``` sudo strings /sys/firmware/acpi/tables/MSDM | tail -1 ``` Use this to view your product key from a live Ubuntu distro on pendrive
Yes Windows 10 key is stored in the BIOS, in the event you need a restore, as long as you use the same version so either Pro or Home, it will activate automatically. You can prove this to your self, by downloading any product key finder on google and the last 5 digits will be displayed for you. Also the code is normally placed on a sticker under the laptop or under the battery. Thanks!
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
Microsoft has made it simple to activate Windows 10. On new machines the product key is stored in BIOs and is used automatically by the Windows when connected to the Internet. In Windows 10 hardware activation is used. Your Windows 10 will be automatically activated until you don't make changes to the hardware. If you want to install same version as fresh no problem click I don't have a product key link during installation and it will be activated automatically. You can also switch between 32-bit and 64-bit without need of a key in the same edition. If you want to see OEM details visit Microsoft live and check devices tab. You will get everything there.
Download & install Magical Jelly Bean Key Finder from here: <https://www.magicaljellybean.com/downloads/KeyFinderInstaller.exe> This app reads the product keys of Windows & many other apps (Photoshop, MS Office, IDM, etc.) from the registry & shows it to you. You can easily find out the product key of your installed windows (any version). In my laptop (Dell Inspiron 1440) the product key of the pre-installed Win7 Pro was written on a sticker at the bottom of my laptop. You can also check at the bottom of your laptop.
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
Get into command prompt by searching for it or doing the Windows key and R button and typing `cmd` (it should pop up). Then type this command in exactly as is: ``` wmic path softwarelicensingservice get OA3xOriginalProductKey ``` And your product key should pop up right after. voila
Microsoft has made it simple to activate Windows 10. On new machines the product key is stored in BIOs and is used automatically by the Windows when connected to the Internet. In Windows 10 hardware activation is used. Your Windows 10 will be automatically activated until you don't make changes to the hardware. If you want to install same version as fresh no problem click I don't have a product key link during installation and it will be activated automatically. You can also switch between 32-bit and 64-bit without need of a key in the same edition. If you want to see OEM details visit Microsoft live and check devices tab. You will get everything there.
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
``` sudo strings /sys/firmware/acpi/tables/MSDM | tail -1 ``` Use this to view your product key from a live Ubuntu distro on pendrive
Microsoft has made it simple to activate Windows 10. On new machines the product key is stored in BIOs and is used automatically by the Windows when connected to the Internet. In Windows 10 hardware activation is used. Your Windows 10 will be automatically activated until you don't make changes to the hardware. If you want to install same version as fresh no problem click I don't have a product key link during installation and it will be activated automatically. You can also switch between 32-bit and 64-bit without need of a key in the same edition. If you want to see OEM details visit Microsoft live and check devices tab. You will get everything there.
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
Get into command prompt by searching for it or doing the Windows key and R button and typing `cmd` (it should pop up). Then type this command in exactly as is: ``` wmic path softwarelicensingservice get OA3xOriginalProductKey ``` And your product key should pop up right after. voila
Download & install Magical Jelly Bean Key Finder from here: <https://www.magicaljellybean.com/downloads/KeyFinderInstaller.exe> This app reads the product keys of Windows & many other apps (Photoshop, MS Office, IDM, etc.) from the registry & shows it to you. You can easily find out the product key of your installed windows (any version). In my laptop (Dell Inspiron 1440) the product key of the pre-installed Win7 Pro was written on a sticker at the bottom of my laptop. You can also check at the bottom of your laptop.
1,095,980
My new laptop's preinstalled Windows 10 was activated as soon as it was connected to the internet. But no product keys were shown to me. There is no product key label on the laptop. Somewhere I read for newer laptops the product key is embedded in Bios. How can I be sure that if I reinstall the Windows using Media Creation Tool ISO file, it will not ask for the unavailable product key and will detect it in Bios (if any keys is embedded there)?
2016/07/01
[ "https://superuser.com/questions/1095980", "https://superuser.com", "https://superuser.com/users/426021/" ]
``` sudo strings /sys/firmware/acpi/tables/MSDM | tail -1 ``` Use this to view your product key from a live Ubuntu distro on pendrive
Download & install Magical Jelly Bean Key Finder from here: <https://www.magicaljellybean.com/downloads/KeyFinderInstaller.exe> This app reads the product keys of Windows & many other apps (Photoshop, MS Office, IDM, etc.) from the registry & shows it to you. You can easily find out the product key of your installed windows (any version). In my laptop (Dell Inspiron 1440) the product key of the pre-installed Win7 Pro was written on a sticker at the bottom of my laptop. You can also check at the bottom of your laptop.
11,532,726
sorry for the poorly titled post. Say I have the following table: ``` C1 | C2 | c3 1 | foo | x 2 | bar | y 2 | blaz | z 3 | something| y 3 | hello | z 3 | doctor | x 4 | name | y 5 | continue | x 5 | yesterday| z 6 | tomorrow | y ``` I'm trying to come up w/ a sql statement which performs the following union: 1st retrieval retrieves all records w/ c3 = 'y' 2nd retrieval retrieves the first instance of a record where c3 <> 'y' and the result is not in the previous union So, for the result, I should see: ``` C1 | C2 1 | foo 2 | bar 3 | something 4 | name 5 | continue 6 | tomorrow ``` So two questions: 1: Am I totally smoking crack where I think I can do this, and 2: (assuming I can), how do I do this?
2012/07/18
[ "https://Stackoverflow.com/questions/11532726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145129/" ]
Rather than iterating through the $object array, since this is a hash, a simple check if the key/value exists/matches should work, i.e.: ``` if (array_key_exists($obj_key, $object)) { if ($object[$obj_key] == $obj_val) { $count++ } } ```
``` if (in_array($obj_key, array_keys($objects, $obj_val)) $count++; ```
6,909,307
My query is similar to this [global.html is unable to load NPAPI plugin from safari-extension builder but its loading from the direct link](https://stackoverflow.com/questions/4519143/global-html-is-unable-to-load-npapi-plugin-from-safari-extension-builder-but-its). How can I load a NPAPI Plugin from a Safari extension?
2011/08/02
[ "https://Stackoverflow.com/questions/6909307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384134/" ]
The simple answer is that you can't. Unlike firefox and chrome extensions, Safari extensions don't allow you to embed npapi plugins in them.
You can create toolbar in Safari extension Load npapi to the toolbar On start extension make it invisible Get toolbar object Get plugin object from toolbar object ``` try { var toolbarWindow = safari.extension.bars[0].contentWindow; safari.extension.bars[0].hide(); var doc = toolbarWindow.document; var plugin = doc.getElementById("plugin"); if (plugin) plugin.samefunction(); } catch(e) { } ``` tested on Safari 5.1, 6.0
57,669,336
I want to change voice in pyttsx3 module to british male voice, which i do have installed since i can see it in language/speech options and in regedit (Microsoft George), and i do have other voices installed, but when i run this code i dont see all voices that are on my PC, one of those voices is british male. Out of 9 voices i have, pyttsx3 only recognizes 4 Any fix for that? Thank you ``` import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') for voice in voices: print("Voice:") print(" - ID: %s" % voice.id) print(" - Name: %s" % voice.name) print(" - Languages: %s" % voice.languages) print(" - Gender: %s" % voice.gender) print(" - Age: %s" % voice.age) ```
2019/08/27
[ "https://Stackoverflow.com/questions/57669336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11982237/" ]
Well it is possible. However you will have to do some changes in registry so proceed below at your own risk. It would be a good practice to backup your registry files or even your system. **STEP 1 Open registry editor:** Press: `Windows Key + R` and run regedit as administrator. **STEP 2 Check for all the available languages:** You should follow this path: `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens` and there you will see all installed voices on your system (except the cortana voices). **STEP 3 Export the voices:** Select the one you want and right click on the folder. For an example: Right click `MSTTS_V110_elGR_Stefanos` and click export. You can save the file with any name you want but the extension should finish as **.reg** **STEP 4 Modify the file:** You will need to modify it so that it's values are into two other locations in the registry. Open the file with any text editor of your choice and do the following: 1. Copy everything except the first line (Windows Registry Editor Version 5.00). 2. Paste everything at the end of the file. 3. Modify the location of first data set:`[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\ MSTTS_V110_elGR_Stefanos(Your voice name here)]` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\ MSTTS_V110_elGR_Stefanos(Your voice name here)]` (Just change the Speech\_OneCore to Speech) And that goes to attributes location aswell `...\Speech\Voices\Tokens\(your voice name)\Attributes` 4. Replace the location of the second data set **(The one you just copy-pasted at the end)** with: `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\(your voice name)]` and it's attributes with `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\(your voice name)\Attributes` For an example: **Original File:** ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" ``` **Modified registry file:** ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" ``` **STEP 5 Import the file:** Save the file and double click on it. There will be a warning window press yes and proceed. **STEP 6 Check:** run the following code: ``` engine = pyttsx3.init() voices = engine.getProperty("voices") for voice in voices: print(voice.id) ``` **Output:** `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0`
The Microsoft downloadable voices seem to be limited. If you go to their regedit path you'll see that the extra downloadable voices like Microsoft George from the GB package are saved onto a different path than the one that is accepted by pyttsx3. On top of this, on further examination, when navigating to the path of these voices (`Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens`), I noticed that none of these have a tts attribute, like the default David, Zyra, and Iriana do. This leads me to believe that they cannot be used for tts.
57,669,336
I want to change voice in pyttsx3 module to british male voice, which i do have installed since i can see it in language/speech options and in regedit (Microsoft George), and i do have other voices installed, but when i run this code i dont see all voices that are on my PC, one of those voices is british male. Out of 9 voices i have, pyttsx3 only recognizes 4 Any fix for that? Thank you ``` import pyttsx3 engine = pyttsx3.init() voices = engine.getProperty('voices') for voice in voices: print("Voice:") print(" - ID: %s" % voice.id) print(" - Name: %s" % voice.name) print(" - Languages: %s" % voice.languages) print(" - Gender: %s" % voice.gender) print(" - Age: %s" % voice.age) ```
2019/08/27
[ "https://Stackoverflow.com/questions/57669336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11982237/" ]
Well it is possible. However you will have to do some changes in registry so proceed below at your own risk. It would be a good practice to backup your registry files or even your system. **STEP 1 Open registry editor:** Press: `Windows Key + R` and run regedit as administrator. **STEP 2 Check for all the available languages:** You should follow this path: `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens` and there you will see all installed voices on your system (except the cortana voices). **STEP 3 Export the voices:** Select the one you want and right click on the folder. For an example: Right click `MSTTS_V110_elGR_Stefanos` and click export. You can save the file with any name you want but the extension should finish as **.reg** **STEP 4 Modify the file:** You will need to modify it so that it's values are into two other locations in the registry. Open the file with any text editor of your choice and do the following: 1. Copy everything except the first line (Windows Registry Editor Version 5.00). 2. Paste everything at the end of the file. 3. Modify the location of first data set:`[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\ MSTTS_V110_elGR_Stefanos(Your voice name here)]` to `[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\ MSTTS_V110_elGR_Stefanos(Your voice name here)]` (Just change the Speech\_OneCore to Speech) And that goes to attributes location aswell `...\Speech\Voices\Tokens\(your voice name)\Attributes` 4. Replace the location of the second data set **(The one you just copy-pasted at the end)** with: `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\(your voice name)]` and it's attributes with `[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\(your voice name)\Attributes` For an example: **Original File:** ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" ``` **Modified registry file:** ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\MSTTS_V110_elGR_Stefanos] @="Microsoft Stefanos - Greek (Greece)" "408"="Microsoft Stefanos - Greek (Greece)" "CLSID"="{179F3D56-1B0B-42B2-A962-59B7EF59FE1B}" "LangDataPath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,\ 00,70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,\ 65,00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,\ 00,5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,53,00,54,00,54,00,53,00,\ 4c,00,6f,00,63,00,45,00,6c,00,47,00,52,00,2e,00,64,00,61,00,74,00,00,00 "VoicePath"=hex(2):25,00,77,00,69,00,6e,00,64,00,69,00,72,00,25,00,5c,00,53,00,\ 70,00,65,00,65,00,63,00,68,00,5f,00,4f,00,6e,00,65,00,43,00,6f,00,72,00,65,\ 00,5c,00,45,00,6e,00,67,00,69,00,6e,00,65,00,73,00,5c,00,54,00,54,00,53,00,\ 5c,00,65,00,6c,00,2d,00,47,00,52,00,5c,00,4d,00,31,00,30,00,33,00,32,00,53,\ 00,74,00,65,00,66,00,61,00,6e,00,6f,00,73,00,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\SPEECH\Voices\Tokens\MSTTS_V110_elGR_Stefanos\Attributes] "Age"="Adult" "DataVersion"="11.0.2016.1016" "Gender"="Male" "Language"="408" "Name"="Microsoft Stefanos" "SayAsSupport"="spell=NativeSupported; alphanumeric=NativeSupported" "SharedPronunciation"="" "Vendor"="Microsoft" "Version"="11.0" ``` **STEP 5 Import the file:** Save the file and double click on it. There will be a warning window press yes and proceed. **STEP 6 Check:** run the following code: ``` engine = pyttsx3.init() voices = engine.getProperty("voices") for voice in voices: print(voice.id) ``` **Output:** `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_elGR_Stefanos HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0`
If you downloaded the language you want to use, it is possible. Use this way: Your downloaded languages goes this path in registry: `Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens` Right click to `Tokens` node then export these languages from this path, save as `lang.reg` file. Then open `lang.reg` file with any text editor then replace text `"Speech_OneCore"` to `"Speech"` then save and close. Double click `lang.reg` file to import. In your python file, use it as follows: ``` import pyttsx3 engine = pyttsx3.init() engine.setProperty('voice',"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\MSTTS_V110_trTR_Tolga") engine.say(text="Merhaba dünya") engine.runAndWait() # to save to a file # engine.save_to_file(text="Merhaba dünya", filename="file.mp3") ```
157,428
``` USE GlobalSales; GO EXEC sp_helpmergepublication GlobalSales EXEC sp_helppublication GlobalSales EXEC sp_helppublication_snapshot GlobalSales GO -- Execute this batch at the Publisher. DECLARE @publication AS sysname; DECLARE @subscriptionDB AS sysname; DECLARE @subscriber AS sysname; SET @publication = N'Mitjab-Notebook\SQL2008'; SET @subscriptionDB = N'GlobalSales'; SET @subscriber = N'SERVER\SQL2008'; -- At the Publisher, register the subscription, using the defaults. USE [GlobalSales] EXEC sp_addsubscription @publication = @publication, @subscriber = @subscriber, @destination_db = @subscriptionDB, @subscription_type = N'pull', @update_mode = N'failover'; GO ``` but i get: Msg 14013, Level 16, State 1, Procedure sp\_MSrepl\_helppublication\_snapshot, Line 29 This database is not enabled for publication.
2010/07/04
[ "https://serverfault.com/questions/157428", "https://serverfault.com", "https://serverfault.com/users/47486/" ]
You can't do replication (as publisher) with the Express Edition
So then enable publication, or run this on the database which is enabled for publication. Take a look in the replication options to configure publication and distribution.
10,728
Do I need a press to make wine from grapes? Are there cheap alternatives? If I need a press is there a cheap way I can make one?
2013/10/10
[ "https://homebrew.stackexchange.com/questions/10728", "https://homebrew.stackexchange.com", "https://homebrew.stackexchange.com/users/3538/" ]
I've made small quantities without a press, but it's very labor intensive. For a 1 gallon batch, it's reasonable but much larger than that you're going to want some automation. The manual process: 1. De-stem the grapes 2. Crush the grapes 3. Red wine? Ferment on the skin. White wine? Skip to 4. 4. Put the crushed grapes in 5 gallon paint strainer bag and express the juice.
I did it all by hand and it didn't take long. I crushed them by hand, a bunch at a time and let the juice run into a muslin bag inside a clean vessel, I let what pulp and skin came off fall into the straining bag. I discarded the rest, stems and all into a waste bucket once the juice stopped flowing. Repeat until bucket empty. Remember that there is a lot of juice locked up in the pulp in the bag and squeeze it out well. The waste went into the composter.
10,728
Do I need a press to make wine from grapes? Are there cheap alternatives? If I need a press is there a cheap way I can make one?
2013/10/10
[ "https://homebrew.stackexchange.com/questions/10728", "https://homebrew.stackexchange.com", "https://homebrew.stackexchange.com/users/3538/" ]
I've made small quantities without a press, but it's very labor intensive. For a 1 gallon batch, it's reasonable but much larger than that you're going to want some automation. The manual process: 1. De-stem the grapes 2. Crush the grapes 3. Red wine? Ferment on the skin. White wine? Skip to 4. 4. Put the crushed grapes in 5 gallon paint strainer bag and express the juice.
For small quantities, a quick blast in a food processor will suffice. For larger quantities, get two, close fitting, ***food grade*** plastic buckets, fit one with a tap at the bottom and fill it with grapes. Put the second bucket on top and fill it with water. It's not perfect and you won't get as much juice as from a proper press, but it's a cheap and serviceable solution. 3 gallon buckets that are used to hold mayonnaise should be reasonably easy to get from bakers/sandwich shops. Make sure you get plain mayo ones only, flavoured mayos can leave a hard to remove taint.
9,571,638
I have a script already for uploading pictures, but I want the ability to select more pictures at once on upload,by holding down ctrl,I know I can use uploadify but I don't want to start over, mabe you guys know a script or something for jquery, that will work without to remove the current code, or you guys could give me a snippet.
2012/03/05
[ "https://Stackoverflow.com/questions/9571638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58839/" ]
The ability to slect multiple files in entirely the browsers features. Which cannot be changed by using a `Javascript` or `css` or `html`. Using uploadify or similar as you mentioned in your question is the right way to go. You know `uploadify` also uses the `swfobject.js`, to overcome this limitation by using an `actionscript` instead.
You could write your own upload system in javascript with ajax. See <http://www.html5rocks.com/en/tutorials/file/dndfiles/> Basic workflow * get local file contents * push to server via ajax With this you could do a multi-file select and/or drag and drop upload system. Best and maybe only solution if you want to stay in javascript.
118,181
I am confused with the way uniform integrability is defined in the context of random variables. Keeping with the analysis idea, I had expected this definition: If $X$ is a random variable, given $\epsilon \ge 0$ and $A \subseteq \Omega$, there must be a $\delta$ such that $\int\_{A} d\mu \le \delta$ and $\int\_{A} X(\omega) d \omega \le \epsilon$. Instead this is what I find in most places [including Wiki](http://en.wikipedia.org/wiki/Uniform_integrability) (when $K \subset L^1(\mu)$): $$\lim\_{c \to \infty} \sup\_{X \in K} \int\_{|X|\ge c} |X| d \mu = 0$$ What is the reason for this different definition? Why does the bound on the value of $X$ even make an appearance?
2012/03/09
[ "https://math.stackexchange.com/questions/118181", "https://math.stackexchange.com", "https://math.stackexchange.com/users/24451/" ]
Three conditions are involved: > > (C) For every $\varepsilon\gt0$, there exists a finite $c$ such that, for every $X$ in $\mathcal H$, $\mathrm E(|X|:|X|\geqslant c)\leqslant\varepsilon$. > > > (C1) There exists a finite $C$ such that, for every $X$ in $\mathcal H$, $\mathrm E(|X|)\leqslant C$. > > > (C2) For every $\varepsilon\gt0$ there exists $\delta\gt0$ such that, for every measurable $A$ such that $\mathrm P(A)\leqslant\delta$ and every $X$ in $\mathcal H$, $\mathrm E(|X|:A)\leqslant\varepsilon$. > > > Then (C) is equivalent to (C1) and (C2). To wit: * (C) implies (C1) since $\mathrm E(|X|)\leqslant c+\mathrm E(|X|:|X|\geqslant c)$. * (C) implies (C2) since $\mathrm E(|X|:A)\leqslant c\mathrm P(A)+\mathrm E(|X|:|X|\geqslant c)$. * (C1) and (C2) imply (C) since $\mathrm P(|X|\geqslant c)\leqslant\mathrm E(|X|)/c$. The intuition might lie in the decomposition $A=(A\cap[|X|\lt c])\cup(A\cap[|X|\geqslant c])$ used to show that (C) implies (C2): for any given $c$, the expectation of $|X|$ on the first part is controlled uniformly over $X$ by something of the order of $\mathrm P(A)$ and the expectation of $|X|$ on the second part is controlled uniformly over $A$ thanks to condition (C).
There is an equivalent definition of uniform integrability which goes: Let $(\Omega,\mathcal{F},P)$ be a probability space. A set $\mathcal{H}$ of random variables is uniformly integrable if and only if $$ \sup\_{X\in \mathcal{H}}\int\_\Omega |X| dP < \infty $$ and $$ \forall \epsilon >0\, \exists \delta >0\;\forall A\in \mathcal{F}: P(A)\leq \delta \Rightarrow \sup\_{X\in\mathcal{H}} \int\_A |X| dP\leq \epsilon. $$ Maybe this it what you are looking for.
823,706
I'm trying to compile the [SQLite amalgamation](http://www.sqlite.org/amalgamation.html) source into my iPhone app (to give me access to the full-text searching functionality that isn't available in the iPhone-compiled version of the binary. When I add sqlite3.c and sqlite3.h to a normal Carbon C app template, it compiles just fine (with a single warning about an unused variable), but when I try compiling it in my iPhone project I get a number of errors relating to missing function declarations. I'm able to solve these problems by explicitly including ctype.h, but it's a little strange. However, even after it builds it fails on linking with the following error: ``` "_sqlite3_version", referenced from: _sqlite3_version$non_lazy_ptr in sqlite3.0 symbol(s) not found collect2: ld returned 1 exit status ``` I assume that it's something in the iPhone app's build settings, but I can't figure it out. Any ideas?
2009/05/05
[ "https://Stackoverflow.com/questions/823706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337184/" ]
Try it with this steps: 1. xcode menu -> project -> new target -> static library -> target name: SQLite 2. drop SQLite amalgamation source into the project, now you can select the target, choose SQLite 3. xcode menu -> project -> edit active target -> tab General -> Direct Dependencies -> add SQLite 4. tab General -> Linked Libraries -> add your SQLite
That type of error usually means a missing framework. 1. Right- or control-click on your Project's *Frameworks* folder. 2. Select *Add > Existing Framework...* 3. Go to: *Macintosh HD > Developer > Platforms > iPhoneOS.platform > Developer > SDKs > iPhoneOS2.2sdk > usr > lib* and select *libsqlite3.dylib* 4. Rebuild your project That should take care of it, I think. You may need to add a similar library for running on the iPhone Simulator.
823,706
I'm trying to compile the [SQLite amalgamation](http://www.sqlite.org/amalgamation.html) source into my iPhone app (to give me access to the full-text searching functionality that isn't available in the iPhone-compiled version of the binary. When I add sqlite3.c and sqlite3.h to a normal Carbon C app template, it compiles just fine (with a single warning about an unused variable), but when I try compiling it in my iPhone project I get a number of errors relating to missing function declarations. I'm able to solve these problems by explicitly including ctype.h, but it's a little strange. However, even after it builds it fails on linking with the following error: ``` "_sqlite3_version", referenced from: _sqlite3_version$non_lazy_ptr in sqlite3.0 symbol(s) not found collect2: ld returned 1 exit status ``` I assume that it's something in the iPhone app's build settings, but I can't figure it out. Any ideas?
2009/05/05
[ "https://Stackoverflow.com/questions/823706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337184/" ]
I've managed to do this using the amalgamation and dumped it straight into my project without having to do the linking catlan suggested (I'm not saying it's a bad idea, merely it's possible to do in the main project). I didn't need to edit anything (except for adding the necessary FTS define for the text searching) and compiled error free. Check your build settings and ensure '-sqlite3' isn't in your Other Linking Flags.
That type of error usually means a missing framework. 1. Right- or control-click on your Project's *Frameworks* folder. 2. Select *Add > Existing Framework...* 3. Go to: *Macintosh HD > Developer > Platforms > iPhoneOS.platform > Developer > SDKs > iPhoneOS2.2sdk > usr > lib* and select *libsqlite3.dylib* 4. Rebuild your project That should take care of it, I think. You may need to add a similar library for running on the iPhone Simulator.
823,706
I'm trying to compile the [SQLite amalgamation](http://www.sqlite.org/amalgamation.html) source into my iPhone app (to give me access to the full-text searching functionality that isn't available in the iPhone-compiled version of the binary. When I add sqlite3.c and sqlite3.h to a normal Carbon C app template, it compiles just fine (with a single warning about an unused variable), but when I try compiling it in my iPhone project I get a number of errors relating to missing function declarations. I'm able to solve these problems by explicitly including ctype.h, but it's a little strange. However, even after it builds it fails on linking with the following error: ``` "_sqlite3_version", referenced from: _sqlite3_version$non_lazy_ptr in sqlite3.0 symbol(s) not found collect2: ld returned 1 exit status ``` I assume that it's something in the iPhone app's build settings, but I can't figure it out. Any ideas?
2009/05/05
[ "https://Stackoverflow.com/questions/823706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337184/" ]
Try it with this steps: 1. xcode menu -> project -> new target -> static library -> target name: SQLite 2. drop SQLite amalgamation source into the project, now you can select the target, choose SQLite 3. xcode menu -> project -> edit active target -> tab General -> Direct Dependencies -> add SQLite 4. tab General -> Linked Libraries -> add your SQLite
I've managed to do this using the amalgamation and dumped it straight into my project without having to do the linking catlan suggested (I'm not saying it's a bad idea, merely it's possible to do in the main project). I didn't need to edit anything (except for adding the necessary FTS define for the text searching) and compiled error free. Check your build settings and ensure '-sqlite3' isn't in your Other Linking Flags.
8,677,053
I have set up a MySQL database for location tracking on several devices. Currently, I plan to have each device having their own table in which to store their locations at various times. I was thinking that in a device's table, there would be a timestamp table which would hold latitude, longitude, and other identifying information. This is my first time using MySQL, so I'm sure this isn't the best way to do it...but is this possible? If not, what are some other alternatives?
2011/12/30
[ "https://Stackoverflow.com/questions/8677053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122510/" ]
From what I can see, your database schema should look more or less like this: ``` create table devices ( id int not null auto_increment primary key, name ..., ... ) engine=INNODB; create table device_locations ( id int not null auto_increment primary key, device_id not null, lat ..., lng ..., ..., index ix_device_id(device_id), foreign key (device_id) references devices(id) ) engine=INNODB; ``` What you want to do is perfectly suitable for a relational database (such as MySQL, hey it even has [built-in datatypes just for storing GIS data](http://dev.mysql.com/doc/refman/5.6/en/spatial-extensions.html)), however you should probably read up on [normal forms](http://en.wikipedia.org/wiki/Database_normalization#Normal_forms "normal forms") first.
Try NoSQL databases that doesn't restrict schemas. MongoDB comes in mind when you want to structure nested collection.
8,677,053
I have set up a MySQL database for location tracking on several devices. Currently, I plan to have each device having their own table in which to store their locations at various times. I was thinking that in a device's table, there would be a timestamp table which would hold latitude, longitude, and other identifying information. This is my first time using MySQL, so I'm sure this isn't the best way to do it...but is this possible? If not, what are some other alternatives?
2011/12/30
[ "https://Stackoverflow.com/questions/8677053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122510/" ]
From what I can see, your database schema should look more or less like this: ``` create table devices ( id int not null auto_increment primary key, name ..., ... ) engine=INNODB; create table device_locations ( id int not null auto_increment primary key, device_id not null, lat ..., lng ..., ..., index ix_device_id(device_id), foreign key (device_id) references devices(id) ) engine=INNODB; ``` What you want to do is perfectly suitable for a relational database (such as MySQL, hey it even has [built-in datatypes just for storing GIS data](http://dev.mysql.com/doc/refman/5.6/en/spatial-extensions.html)), however you should probably read up on [normal forms](http://en.wikipedia.org/wiki/Database_normalization#Normal_forms "normal forms") first.
With according to Flickr experience with MySQL, it can be used as schema-less as well, just start keep serialized data in a column if you know what you want. MySQL is primarily production-ready solution with ready-to-use tools to backup, recover, replication and sharding tool which is ideal to maintenance. If you don't want to use schema, just don't use it
45,263,811
I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button. Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text. ``` var dots = 0; $(document).ready(function() { $('#payDots').on('click', function() { $(this).attr('disabled', 'disabled'); setInterval(type, 600); }) }); function type() { var dot = '.'; if(dots < 3) { $('#payDots').val('processing' + dot.repeat(dots)); dots++; } else { $('#payDots').val('processing'); dots = 0; } } ``` --- ``` <input id="payDots" type="button" value="Pay" class="button"> ``` --- ``` .button{ text-align: center; width: 300px; font-size: 20px; } ``` <https://jsfiddle.net/v8g4rfsw/1/> (button should be pressed)
2017/07/23
[ "https://Stackoverflow.com/questions/45263811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6467195/" ]
I'm not aware that `zsh` has a built-in function of this sort, but it should be pretty easy to script without resorting to a single subshell or slow pipe: ```bash #!/bin/zsh paths=(${(s:/:)PWD}) cur_path='/' cur_short_path='/' for directory in ${paths[@]} do cur_dir='' for (( i=0; i<${#directory}; i++ )); do cur_dir+="${directory:$i:1}" matching=("$cur_path"/"$cur_dir"*/) if [[ ${#matching[@]} -eq 1 ]]; then break fi done cur_short_path+="$cur_dir/" cur_path+="$directory/" done printf %q "${cur_short_path: : -1}" echo ``` This script will output the shortest path needed for auto-completion to work. You can throw it in your `.zshrc` as a function and then run it from any directory. ```bash function spwd { paths=(${(s:/:)PWD}) cur_path='/' cur_short_path='/' for directory in ${paths[@]} do cur_dir='' for (( i=0; i<${#directory}; i++ )); do cur_dir+="${directory:$i:1}" matching=("$cur_path"/"$cur_dir"*/) if [[ ${#matching[@]} -eq 1 ]]; then break fi done cur_short_path+="$cur_dir/" cur_path+="$directory/" done printf %q "${cur_short_path: : -1}" echo } ``` Here's a video of it in action: <https://asciinema.org/a/0TyL8foqvQ8ec5ZHS3c1mn5LH> Or if you prefer, some sample output: ```none ~/t $ ls adam alice bob getshortcwd.zsh ~/t $ ls adam devl ~/t $ ls alice devl docs ~/t $ spwd /h/v/t ~/t $ cd adam/devl ~/t/adam/devl $ spwd /h/v/t/ad/d ~/t/adam/devl $ cd ../../alice/devl ~/t/alice/devl $ spwd /h/v/t/al/de ~/t/alice/devl $ cd ../docs ~/t/alice/docs $ spwd /h/v/t/al/do ~/t/alice/docs $ `spwd` [TAB] ~/t/alice/docs $ /h/v/t/al/do [TAB] ~/t/alice/docs $ /home/vsimonian/t/alice/docs ```
Yes it is possible to collapse the directories to a first-unique-letter path and have the Z Shell expand that path upon pressing [Tab]. I simply used compinstall (zsh utility script installed with Zsh) to generate the following code. The important part to take note of for expanding path elements is on the **sixth `zstyle` command, near the end**, where the bracket of characters to separate completion points with includes the `/`, which is, of course, the directory separator. With this, the unique paths you suggested will fully fill out with just one [Tab] press as if the `*` were at the end of each path-name unique letters. ``` # The following lines were added by compinstall zstyle ':completion:*' add-space true zstyle ':completion:*' completer _list _expand _complete _ignored _match _correct _approximate _prefix zstyle ':completion:*' completions 1 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*' matcher-list 'm:{[:lower:]}={[:upper:]} r:|[._-]=* r:|=*' 'm:{[:lower:]}={[:upper:]} m:{[:lower:][:upper:]}={[:upper:][:lower:]} r:|[._-]=* r:|=*' 'r:|[._-/]=* r:|=*' 'l:|=* r:|=*' zstyle ':completion:*' match-original both zstyle :compinstall filename '/home/micah/.zsh/.zshrc' autoload -Uz compinit compinit # End of lines added by compinstall ``` As for creating the unique path in the first place and inserting it into the prompt, it is possible with a zsh script or function, and therefore *should* be possible for the completer or line-editor also, but just sticking to the prompt, you would add a function to the `$precmd_functions` array that modifies or adds to the `PS1` variable. This special array is a list of function names that are run right before each prompt. ``` function precmd_unique_pwd { local pwd_string="$(upwd)" PS1="%B%n@%m $pwd_string => %b" } precmd_functions+=( precmd_unique_pwd ) ``` For getting of the current PWD in shortened form, I think this function is clear and easy to follow, though not necessarily optimized for low resource usage. ``` #!/bin/zsh function upwd { emulate -LR zsh -o nullglob local dir Path local -a newpwd tmp stack local -i length=1 Flag=0 newpwd=( ${(s./.)PWD} ) foreach dir ( $newpwd ) (( length=0, Flag=0 )) repeat $#dir do (( length += 1 )) tmp=( ${(j.*/.)~stack}/$dir[1,$length]*(/) ) if (( $#tmp == 1 )) then Path=$Path/$dir[1,$length] stack+=( /$dir ) (( Flag=1 )) break fi done if (( Flag )) then continue else Path=$Path/$dir fi end print -- $Path } upwd ``` Notice that it finds unique paths with directory names because of the Zsh feature `(/)` at the end of the globbing. On the last directory (current) this means you may match something else if there is a file with the same name plus an extension.
203,346
Does the versioning option in SharePoint 2013 only work for Microsoft Word Documents? What about Excel or PowerPoint? Can I do Versioning with Tasks as well? Thanks
2016/12/22
[ "https://sharepoint.stackexchange.com/questions/203346", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/59061/" ]
Both lists and libraries can use Versioning, the file type does not matter in the case of documents. [![enter image description here](https://i.stack.imgur.com/mWPmS.jpg)](https://i.stack.imgur.com/mWPmS.jpg)
Versioning works with all document types and different list options. > > Versioning is available for list items in all default list types—including calendars, issue tracking lists, and custom lists. It is also available for all file types that can be stored in libraries, including Web Part pages. > > > [See Microsoft Article Here](https://support.office.com/en-us/article/How-does-versioning-work-in-a-list-or-library-0f6cd105-974f-44a4-aadb-43ac5bdfd247?ui=en-US&rs=en-US&ad=US)
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
There is no point in sending a manned mission! ---------------------------------------------- As @HDE22686 noted, there *are* many interesting phenomena associated with black holes. Given the opportunity to study one up close, it is likely that missions *will* be sent. However, describing all the cool phenomena associated with black holes only means they will be studied - **not that humans will be there to see them** So why on Earth would you send a human to a black hole? ------------------------------------------------------- * **Human error influences data**: This is a once-in-a species (potentially) chance. There is no point sending humans capable of error on board this probe when a *considerable amount of money* is at stake. * **Black holes are deadly**: Any miscalculation in the trajectory of the probe may risk ending human lives, millions of miles away from home - is that really worth it? Additionally, exotic radiation is associated with black holes. It's safest not to play with that. * **We can send other organisms instead**: If the point is seeing the effects black holes have on living tissue, why not send rats? Or dogs? Or chimpanzees? Or a sample of human flesh kept alive by life support? * **Multiple unmanned probes decrease chances of inaccuracy**: While machines *are* capable of failure - see the [*recently crashed Mars rover which was brought down by a glitch*](http://www.news.com.au/technology/science/space/europes-mars-lander-failure-caused-by-glitch-but-gives-researchers-valuable-lesson/news-story/a2db7c2f2c470ffe31117c6ec24868eb) - many agencies capable of sending probes *will do so*, meaning data collected will generally reflect the truth. Compare this to multiple probes with humans on board. * **Missions are flybys**: When we send spacecraft out of the solar system to observe distant objects, we never intend to get them back - and even if we wanted to, it's extremely expensive! The first few generations of Mars colonists will be stuck on Mars forever because we aren't willing to pay for ships capable of escaping Mars after landing. With that in mind, why would we send people out of the Solar System and then attempt to get them back? * **Machines are competent and won't need to make major decisions**: While humans *can* make on-the-spot decisions, a probe with basic sensors, locomotion, and apparatus is capable of steering itself. No situation will arise where *only* a human could decide what to do. **In conclusion,** we'll be killing people - who could mess up the missions - in strange and potentially cruel ways, millions of miles away from home, with no chance of retrieval - **when machines can do the job even better.** Missions? Yes! People? *No*.
My favorite scifi author Greg Egan wrote a short story about just this. It's available free online if you're curious: [The Planck Dive](http://gregegan.customer.netspace.net.au/PLANCK/Complete/Planck.html). Quick TLDR: It's set in a very farflung transhuman society, and they do it out of pure scientific curiosity by forking their personalities. As others have said, there's not really any reason to send a person in on a one way trip except for the experience of it. As you say, a sort of elegant way for a scientifically minded person to die.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
Send Humans! Why? Because of archaeology... As others have stated, computers can handle the mission, running a bunch of experiments and sending us back the results. Those automated experiments are, by definition, limited to studying the expected characteristics of the black hole. They can test for minute variances in established theories and provide detailed measurements of the black hole's physical characteristics. But automated experiments cannot study the unexpected. That black hole may have a solar system of its own, spinning around it in slowly decreasing orbits. The planets of that solar system will vary in origin, having been stolen from different solar systems which the black hole passed through. Studying those planets and their surrounding dust clouds, is our opportunity to sample matter from farther away than we could ever travel. And some of those adopted worlds may even have once harbored intelligent life.
How to find it? --------------- Black holes are by definition invisible the only way to find one is to look around to see stars being blocked out by them. How to get data? ---------------- To get data from a black hole you would have to study the effects on what it does to the surrounding area and **not** the black hole itself. Sizes of black holes: --------------------- A "small" black hole is an instant death due to spaghettification of the human and the probe. **A supermassive black hole's estimated inside view:** [![A large black hole's estimated view from the inside.](https://i.stack.imgur.com/F2ggu.gif)](https://i.stack.imgur.com/F2ggu.gif) A large black hole is a slow death because the event horizon spans much further out where the gravity is still "survivable". This would probably be the most amazing way to die because you would see the universe slowly fading away. On earth maybe 100+ years might pass because of time dilation while for you only 10 minutes might have passed. Event horizon: -------------- It's very simple: You pass it and there is **no** way to get you or your data out of it. A black hole by is by definition black because it sucks in everything. X-Rays, radio frequency waves, entire stars and also light. This means that once you're in you'll have to play cards with yourself until you and the shuttle disappear from existence. Time dilation: -------------- [![SpaceTime](https://i.stack.imgur.com/BK3cx.jpg)](https://i.stack.imgur.com/BK3cx.jpg) A black hole is so heavy that time itself behaves differently. This is because we dont merely live in space or in time but in spacetime. Spacetime can stretch depending on how "heavy" something is. For example, every 60 years our satellites need to add 1 second to their own clock because on earth time goes a tiny bit slower. This is exactly the same near a black hole as on earth except that it is magnified so much that once you pass the event horizon someone flying outside it would see you falling forever. Spaghettification ----------------- Spaghettification happens when gravity on the close end of an object is higher than the further end. (On earth this would be your feet.) Because a black hole is much more powerful than earth it will stretch you from the closest end to the furthest until you are basically one long string of human. Gravitational Lensing --------------------- [![A black hole's gravitational lens](https://i.stack.imgur.com/Vtp3h.gif)](https://i.stack.imgur.com/Vtp3h.gif) A black hole is so heavy that it will warp the space around it like a magnifying glass. Pro's of a human ---------------- * Amazing view. * Time travel (only future). Cons of a human --------------- * Bodily harm due to gravity, spaghettification etc. * Can accidently mess up the data. Bonus points ------------ * Stand near a supermassive black hole to travel into the future (still outside event horizon but close enough to experience the effects)
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
For science! ============ At present we have two main theories of physics: * General relativity, which is about very heavy things and gravity. * Quantum mechanics, which is about very small things. We have not been able to fit these two together. One of the reasons for this is that we have not been able do experiments that test both at once. Objects that are small enough to have quantum effects are not noticeably affected by gravity. At least not strongly enough that we can distinguish between different theories of gravity. Our other theories (eg. electromagnetism) can be fit with one or the other, but not both at once. Black holes changes things. Here gravity is very strong and even electrons will feel the pull. If we would be able to bring along both a neutrino source and a neutrino detector, we would learn much about these mysterious particles. However, at current or near-future tech levels neutrino detectors are *very* massive and not something you can move off-Earth. Even without that I am sure there are numerous experiments we could do with a humble electron ray that will be very useful. The main experiment I see done is sending a laser or a ray of electrons in very close to the event horizon, and putting a detector where it comes out. Useful results would be angle of deflection and time taken for the journey. Maybe also how spread out the beam has become. If the hole is rotating, sending beams both with and against the rotation will be interesting. Why humans? =========== This is about science, which means we won't know in advance what experiments we want to perform. Results of the one experiment will suggest new physics theories. These will suggest new experiments to perform. A machine cannot do this. (Unless you have powerful AI) If there are no humans on the spot, the results will have to be sent to Earth and new commands sent back. This will take too much time and the black hole will move away before we are done. I suggest a crew consisting of a mixture of astronauts and physicists. Both will need to have a good understanding of the other side, but in the end they are different in their goals. The astronauts will want to keep everybody alive and return home in one piece. The physicists will want to perform more experiments. *More*! **MORE**!! Other answers have suggested sending several unmanned probes instead of a manned one. I suggest a manned ship carrying many unmanned probes. The ship stays prudently far away from the radiation, the probes go closer, not close enough for tidal effects to destroy them, but definitely into hard radiation areas. Parting gift. ============= The time comes when the hole moves away and we have to go home to Earth. Leave something behind for aliens to discover, maybe something like the Pioneer Plaques and Voyager Golden Discs. The hole will be a scientist magnet from every civilization it passes nearby and a good meeting spot. Maybe we will find an alien artifact already there...
As someone with less of a scientific background as many of the contributors on this question, my gut reaction is that part of the case for humans exploring black holes can be made simply by considering human nature and it's role in history. We are, by nature, adventurous creatures who inevitably grow used to our surroundings and seek to expand our horizons. The fact that we are curious, and want to know more about our surroundings (be they terrestrial or extraterrestrial) suggests to me that, while perhaps millions of years down the road, we will inevitably attempt to explore these phenomena ourselves anyway. Some of the most empowering, inspiring and audacious ventures undertaken by mankind have been marked by certain death/injury/loss, even by those embarking upon them. The promise of our species is that, despite these factors we will always want to explore further. If there are individuals willing and wanting to take that kind of leap, why not allow them to do so, even if only to entertain our nature. (Philosophical-ish response conjectured from an assumption of economic, technological and legal viability of the project)
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
There is no point in sending a manned mission! ---------------------------------------------- As @HDE22686 noted, there *are* many interesting phenomena associated with black holes. Given the opportunity to study one up close, it is likely that missions *will* be sent. However, describing all the cool phenomena associated with black holes only means they will be studied - **not that humans will be there to see them** So why on Earth would you send a human to a black hole? ------------------------------------------------------- * **Human error influences data**: This is a once-in-a species (potentially) chance. There is no point sending humans capable of error on board this probe when a *considerable amount of money* is at stake. * **Black holes are deadly**: Any miscalculation in the trajectory of the probe may risk ending human lives, millions of miles away from home - is that really worth it? Additionally, exotic radiation is associated with black holes. It's safest not to play with that. * **We can send other organisms instead**: If the point is seeing the effects black holes have on living tissue, why not send rats? Or dogs? Or chimpanzees? Or a sample of human flesh kept alive by life support? * **Multiple unmanned probes decrease chances of inaccuracy**: While machines *are* capable of failure - see the [*recently crashed Mars rover which was brought down by a glitch*](http://www.news.com.au/technology/science/space/europes-mars-lander-failure-caused-by-glitch-but-gives-researchers-valuable-lesson/news-story/a2db7c2f2c470ffe31117c6ec24868eb) - many agencies capable of sending probes *will do so*, meaning data collected will generally reflect the truth. Compare this to multiple probes with humans on board. * **Missions are flybys**: When we send spacecraft out of the solar system to observe distant objects, we never intend to get them back - and even if we wanted to, it's extremely expensive! The first few generations of Mars colonists will be stuck on Mars forever because we aren't willing to pay for ships capable of escaping Mars after landing. With that in mind, why would we send people out of the Solar System and then attempt to get them back? * **Machines are competent and won't need to make major decisions**: While humans *can* make on-the-spot decisions, a probe with basic sensors, locomotion, and apparatus is capable of steering itself. No situation will arise where *only* a human could decide what to do. **In conclusion,** we'll be killing people - who could mess up the missions - in strange and potentially cruel ways, millions of miles away from home, with no chance of retrieval - **when machines can do the job even better.** Missions? Yes! People? *No*.
Don't send humans! There are two basic reasons to send humans to space: 1) To cope with the unexpected. When your mission goes off the rails it's much more likely to succeed if you have a very flexible system on board: a human. Think of Apollo 11, coming down into the rock garden. The tech of the time would have crashed the rocket, even modern tech would be hard pressed to land it safely. A human pilot was capable of analyzing the problem and dealing with it, thus saving the mission. 2) When there is an analysis problem that can't reasonably be handled by tech. Apollo era tech couldn't do a reasonable job of gathering moon rocks. If we wanted to bring home samples other than whatever happened to be right under the scoop we had to send humans. (And note that the landing problem in #1 is also an example of this.) Now, apply these standards to a black hole mission: 1) The unexpected, sure. It's always useful to send a human. However, that means an awful lot of life support equipment, you can send multiple unmanned missions for the price of one manned one. 2) Jobs that need a human. What jobs? There are no samples to go pick up or the like, it's going to be an extremely lethal environment outside the hull. What can the humans do??? Basically nothing! Also, consider that the most interesting observations will be made as low as possible: 1) Delta-v requirements mean that you can get lower if you can burn all your fuel on going down and not save any for coming home. 2) The deeper you go the more dangerous the environment becomes. If you can get close I would **expect** lost probes as there will be lots of fast-moving debris. Note: If the black hole is far enough out you might send a manned mission as a mothership. A lagtime of minutes or hours could be of considerable value over a lag of months from Earth.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
What could be learned? ====================== There are so many things you could study by looking at a black hole. There are lots of open or partially unsolved problems that surround them: * **Does [Hawking radiation](https://en.wikipedia.org/wiki/Hawking_radiation) exist?** While it has been predicted theoretically, direct evidence is lacking - well, nonexistent. Stellar-mass black holes aren't the best targets - primordial black holes are better - but you never know. Extreme up-close measurements could yield results. * **How do [astrophysical jets](https://en.wikipedia.org/wiki/Astrophysical_jet) form from accretion disks?** Jets are present around many objects, black holes included (if there is an accretion disk present), but the precise mechanism for their formation is unknown. The prevailing hypothesis is the [Blandford–Znajek process](https://en.wikipedia.org/wiki/Blandford%E2%80%93Znajek_process), but this has yet to be confirmed. * **Is general relativity accurate?** All the evidence is in its favor, but more experiments never hurt. Many [tests of general relativity](https://en.wikipedia.org/wiki/Tests_of_general_relativity) could be repeated near the black hole, where relativistic effects are extremely strong. The tests could include + **[Gravitational lensing](https://en.wikipedia.org/wiki/Gravitational_lens)**, the bending of light by a massive object. + **[Gravitational redshift](https://en.wikipedia.org/wiki/Gravitational_redshift)**, the change in wavelength/frequency of light near a massive object. + **[Frame-dragging](https://en.wikipedia.org/wiki/Frame-dragging)**, which is important near rotating massive objects.We could also test [alternative theories of gravity](https://en.wikipedia.org/wiki/Alternatives_to_general_relativity), and maybe rule some of them out. * **Do black holes even exist?** While there is quite a lot of evidence for black holes or black-hole-like objects, alternatives or modifications have been proposed, including + [Eternally collapsing objects](https://en.wikipedia.org/wiki/Eternally_collapsing_object) + [Magnetospheric eternally collapsing objects](https://en.wikipedia.org/wiki/Magnetospheric_eternally_collapsing_object) + [Black stars](https://en.wikipedia.org/wiki/Black_star_(semiclassical_gravity)) + [Fuzzballs](https://en.wikipedia.org/wiki/Fuzzball_(string_theory)) + [Dark energy stars](https://en.wikipedia.org/wiki/Dark-energy_star) + [Gravastars](https://en.wikipedia.org/wiki/Gravastar)Many of these ideas are wild, and some cannot be tested by observations of black holes (or "black-hole-like objects"). * **Is [information lost](https://en.wikipedia.org/wiki/Black_hole_information_paradox) inside black holes?** The black hole information paradox - a notable problem in general relativity, quantum mechanics, and physics in general - asks whether or not "information" about physical states is lost inside a black hole. This has implications regarding [string theory](https://physics.stackexchange.com/a/3177/56299), among other areas. * **Do [naked singularities](https://en.wikipedia.org/wiki/Naked_singularity) exist?** The [cosmic censorship hypothesis](https://en.wikipedia.org/wiki/Cosmic_censorship_hypothesis) states that they don't; observing a rotating ([Kerr](https://en.wikipedia.org/wiki/Kerr_metric)) black hole could give us more information about this. Gravastars also provide a solution to the paradox; if black holes are actually gravastars, then the paradox could be solved. Whether or not [the two are observationally different](https://physics.stackexchange.com/q/87472/56299) is a harder question. Why send humans? ================ Now, all of this could be done by computers, not humans. So why send humans, who need that pesky air, food, water, waste disposal, life support systems, life insurance, etc.? Good question. Here are my answers: * **It's good publicity.** Would you rather be the first nation/company to send a probe to a black hole, or the first nation/company to send brave, daring human explorers out into the great beyond, champions of our species - to boldly go where no man has gone before? Admit it; the second sounds a lot better. Yes, the astronauts will have to deal with a lot of risk. But there are going to be plenty of people willing to do it. * **Communication is hard, and humans can make on-the-spot decisions.** Light travels at a finite speed, and on astronomical scales, this is pesky. It takes 8 minutes for light to travel to Earth from the Sun (one astronomical unit, or AU). The Solar System is a *lot* larger - even Neptune is 30 AU away from the Sun. This black hole is likely farther, especially if it's going to cause no disruption to the system (unlikely, unless it's *really* far away). Therefore, you can either pre-program the itinerary beforehand, or send people who can make on-the-spot decisions. Mission Control isn't going to be there to hand-hold the ship's computers through this thing, and humans do have a certain knack for solving problems when things don't go as planned.
For science! ============ At present we have two main theories of physics: * General relativity, which is about very heavy things and gravity. * Quantum mechanics, which is about very small things. We have not been able to fit these two together. One of the reasons for this is that we have not been able do experiments that test both at once. Objects that are small enough to have quantum effects are not noticeably affected by gravity. At least not strongly enough that we can distinguish between different theories of gravity. Our other theories (eg. electromagnetism) can be fit with one or the other, but not both at once. Black holes changes things. Here gravity is very strong and even electrons will feel the pull. If we would be able to bring along both a neutrino source and a neutrino detector, we would learn much about these mysterious particles. However, at current or near-future tech levels neutrino detectors are *very* massive and not something you can move off-Earth. Even without that I am sure there are numerous experiments we could do with a humble electron ray that will be very useful. The main experiment I see done is sending a laser or a ray of electrons in very close to the event horizon, and putting a detector where it comes out. Useful results would be angle of deflection and time taken for the journey. Maybe also how spread out the beam has become. If the hole is rotating, sending beams both with and against the rotation will be interesting. Why humans? =========== This is about science, which means we won't know in advance what experiments we want to perform. Results of the one experiment will suggest new physics theories. These will suggest new experiments to perform. A machine cannot do this. (Unless you have powerful AI) If there are no humans on the spot, the results will have to be sent to Earth and new commands sent back. This will take too much time and the black hole will move away before we are done. I suggest a crew consisting of a mixture of astronauts and physicists. Both will need to have a good understanding of the other side, but in the end they are different in their goals. The astronauts will want to keep everybody alive and return home in one piece. The physicists will want to perform more experiments. *More*! **MORE**!! Other answers have suggested sending several unmanned probes instead of a manned one. I suggest a manned ship carrying many unmanned probes. The ship stays prudently far away from the radiation, the probes go closer, not close enough for tidal effects to destroy them, but definitely into hard radiation areas. Parting gift. ============= The time comes when the hole moves away and we have to go home to Earth. Leave something behind for aliens to discover, maybe something like the Pioneer Plaques and Voyager Golden Discs. The hole will be a scientist magnet from every civilization it passes nearby and a good meeting spot. Maybe we will find an alien artifact already there...
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
What could be learned? ====================== There are so many things you could study by looking at a black hole. There are lots of open or partially unsolved problems that surround them: * **Does [Hawking radiation](https://en.wikipedia.org/wiki/Hawking_radiation) exist?** While it has been predicted theoretically, direct evidence is lacking - well, nonexistent. Stellar-mass black holes aren't the best targets - primordial black holes are better - but you never know. Extreme up-close measurements could yield results. * **How do [astrophysical jets](https://en.wikipedia.org/wiki/Astrophysical_jet) form from accretion disks?** Jets are present around many objects, black holes included (if there is an accretion disk present), but the precise mechanism for their formation is unknown. The prevailing hypothesis is the [Blandford–Znajek process](https://en.wikipedia.org/wiki/Blandford%E2%80%93Znajek_process), but this has yet to be confirmed. * **Is general relativity accurate?** All the evidence is in its favor, but more experiments never hurt. Many [tests of general relativity](https://en.wikipedia.org/wiki/Tests_of_general_relativity) could be repeated near the black hole, where relativistic effects are extremely strong. The tests could include + **[Gravitational lensing](https://en.wikipedia.org/wiki/Gravitational_lens)**, the bending of light by a massive object. + **[Gravitational redshift](https://en.wikipedia.org/wiki/Gravitational_redshift)**, the change in wavelength/frequency of light near a massive object. + **[Frame-dragging](https://en.wikipedia.org/wiki/Frame-dragging)**, which is important near rotating massive objects.We could also test [alternative theories of gravity](https://en.wikipedia.org/wiki/Alternatives_to_general_relativity), and maybe rule some of them out. * **Do black holes even exist?** While there is quite a lot of evidence for black holes or black-hole-like objects, alternatives or modifications have been proposed, including + [Eternally collapsing objects](https://en.wikipedia.org/wiki/Eternally_collapsing_object) + [Magnetospheric eternally collapsing objects](https://en.wikipedia.org/wiki/Magnetospheric_eternally_collapsing_object) + [Black stars](https://en.wikipedia.org/wiki/Black_star_(semiclassical_gravity)) + [Fuzzballs](https://en.wikipedia.org/wiki/Fuzzball_(string_theory)) + [Dark energy stars](https://en.wikipedia.org/wiki/Dark-energy_star) + [Gravastars](https://en.wikipedia.org/wiki/Gravastar)Many of these ideas are wild, and some cannot be tested by observations of black holes (or "black-hole-like objects"). * **Is [information lost](https://en.wikipedia.org/wiki/Black_hole_information_paradox) inside black holes?** The black hole information paradox - a notable problem in general relativity, quantum mechanics, and physics in general - asks whether or not "information" about physical states is lost inside a black hole. This has implications regarding [string theory](https://physics.stackexchange.com/a/3177/56299), among other areas. * **Do [naked singularities](https://en.wikipedia.org/wiki/Naked_singularity) exist?** The [cosmic censorship hypothesis](https://en.wikipedia.org/wiki/Cosmic_censorship_hypothesis) states that they don't; observing a rotating ([Kerr](https://en.wikipedia.org/wiki/Kerr_metric)) black hole could give us more information about this. Gravastars also provide a solution to the paradox; if black holes are actually gravastars, then the paradox could be solved. Whether or not [the two are observationally different](https://physics.stackexchange.com/q/87472/56299) is a harder question. Why send humans? ================ Now, all of this could be done by computers, not humans. So why send humans, who need that pesky air, food, water, waste disposal, life support systems, life insurance, etc.? Good question. Here are my answers: * **It's good publicity.** Would you rather be the first nation/company to send a probe to a black hole, or the first nation/company to send brave, daring human explorers out into the great beyond, champions of our species - to boldly go where no man has gone before? Admit it; the second sounds a lot better. Yes, the astronauts will have to deal with a lot of risk. But there are going to be plenty of people willing to do it. * **Communication is hard, and humans can make on-the-spot decisions.** Light travels at a finite speed, and on astronomical scales, this is pesky. It takes 8 minutes for light to travel to Earth from the Sun (one astronomical unit, or AU). The Solar System is a *lot* larger - even Neptune is 30 AU away from the Sun. This black hole is likely farther, especially if it's going to cause no disruption to the system (unlikely, unless it's *really* far away). Therefore, you can either pre-program the itinerary beforehand, or send people who can make on-the-spot decisions. Mission Control isn't going to be there to hand-hold the ship's computers through this thing, and humans do have a certain knack for solving problems when things don't go as planned.
The expense of sending a manned mission vs. many unmanned probes is going to make the latter very enticing. Certainly humans can adapt to situations better, but technology has gotten to the point that most of the situations they could adapt to are unlikely enough to occur that you'd make up for those occurrences by the redundancy of the probes. The other argument for sending people may be to explore/check out something so totally unexpected that we'd have no way of accounting for it in the probe's programming. But - and this may just be the cynic in me - I think that's extremely unlikely. In a far enough future that this is feasible at all (though granted, if we were OK with the probe taking 10000 years to make it, and another 3000 to get the data, we could do it with today's technology!) tech is (hopefully) going to be so cheap and small that it'll be easy enough to make the probes just collect all the data they can. We think there *might* be objects orbiting the black hole, right? So a couple dozen of those probes will be set to divert course and orbit those instead, and collect data from them. I'm going to assume that they all have advanced physics processing units and would be able to calculate those orbits on the fly. And still some of them might crash (or just veer off into the void), but again, you can send a dozen probes for the cost of one manned mission. I could potentially see live humans as ambassadors in the event that extraterrestrial intelligence is met, but the cynic in me doubly doubts that we'll ever find extraterrestrial life, let alone intelligent life. (It believes such exists - the universe is too vast not to - but it's also too vast to feasibly encounter any.) The probes collecting all that data, petabytes upon petabytes of it, will see any evidence for life that might be out there. They won't recognize it, of course, but the human scientists on earth 15000 years later (after receiving a mysterious signal from space that they decode to find that they can decode it perfectly to ancient English, and after consulting historians who kept the records of ancient, quaint technology are able to realize that a forgotten civilization of a bygone era sent it) *might* glean some evidence that there could be some kind of potential for the conditions of life on one of those bodies. But anyway, the probes aren't really there for that. They're gathering all the data they can because it was cheap at the time, but mostly they were looking at the black hole. Some of that information could provide insights to the current civilization, if they can translate it from a language that died thousands of years ago. But then again, 15000 years into the future of this already future point they may have built a miniature black hole and replicated most of the experiments anyway. Honestly, with the time lag, I'm not sure I see the use of even sending unmanned missions. If I were to even do that it'd just be a probe that has "Kilroy was here" spray-painted on it, just for giggles. Sending a manned mission that distance - no matter how dangerous a black hole is - is a death sentence. (Even if they could come back, everyone and everything they've ever known will have been dead for ages.) That is not a problem for the hero in your story, though, and is in fact kind of a selling point. I have a simple proposition for why they'd send a manned mission - **he wants to go**. "I am going to die anyway, but I'd be the only human in all of human history to see a black hole up close." Sounds like motivation enough for me. In my view, he's not able to convince any government's space agency to let him do that, but a private aerospace firm finds the earnestness in his mission and undertakes (...pun intended) the project. He isn't actually necessary to gather or interpret the data, but he's able to make sense of it when his craft reports it to him. He gets to make all those conclusions and realize that he's the first person in history to not only see a black hole up close, but also finally understand Hawking radiation/information loss/general relativity. He passes away to a peaceful death, as the camera zooms out revealing the cartoon of the fellow with the big nose peeking over the wall, spray-painted onto his ship.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
There is no point in sending a manned mission! ---------------------------------------------- As @HDE22686 noted, there *are* many interesting phenomena associated with black holes. Given the opportunity to study one up close, it is likely that missions *will* be sent. However, describing all the cool phenomena associated with black holes only means they will be studied - **not that humans will be there to see them** So why on Earth would you send a human to a black hole? ------------------------------------------------------- * **Human error influences data**: This is a once-in-a species (potentially) chance. There is no point sending humans capable of error on board this probe when a *considerable amount of money* is at stake. * **Black holes are deadly**: Any miscalculation in the trajectory of the probe may risk ending human lives, millions of miles away from home - is that really worth it? Additionally, exotic radiation is associated with black holes. It's safest not to play with that. * **We can send other organisms instead**: If the point is seeing the effects black holes have on living tissue, why not send rats? Or dogs? Or chimpanzees? Or a sample of human flesh kept alive by life support? * **Multiple unmanned probes decrease chances of inaccuracy**: While machines *are* capable of failure - see the [*recently crashed Mars rover which was brought down by a glitch*](http://www.news.com.au/technology/science/space/europes-mars-lander-failure-caused-by-glitch-but-gives-researchers-valuable-lesson/news-story/a2db7c2f2c470ffe31117c6ec24868eb) - many agencies capable of sending probes *will do so*, meaning data collected will generally reflect the truth. Compare this to multiple probes with humans on board. * **Missions are flybys**: When we send spacecraft out of the solar system to observe distant objects, we never intend to get them back - and even if we wanted to, it's extremely expensive! The first few generations of Mars colonists will be stuck on Mars forever because we aren't willing to pay for ships capable of escaping Mars after landing. With that in mind, why would we send people out of the Solar System and then attempt to get them back? * **Machines are competent and won't need to make major decisions**: While humans *can* make on-the-spot decisions, a probe with basic sensors, locomotion, and apparatus is capable of steering itself. No situation will arise where *only* a human could decide what to do. **In conclusion,** we'll be killing people - who could mess up the missions - in strange and potentially cruel ways, millions of miles away from home, with no chance of retrieval - **when machines can do the job even better.** Missions? Yes! People? *No*.
There's a few pitfalls to trying to study a black hole up close 1. Not much is coming out to study. Mostly black holes emit x-rays. No matter, no light, no nothing. 2. Once, say, a probe goes in, it's not coming back out. Nor is it likely going to be able to send data back past the event horizon. 3. [Time dilation](https://www.youtube.com/watch?v=orx0H9mBeXk). The closer things get to the black hole, the slower they appear in real time. So let's say you sent a team to the black hole. They would return thousands or millions of years later. So whomever sent them would be long gone by the time they got back.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
The expense of sending a manned mission vs. many unmanned probes is going to make the latter very enticing. Certainly humans can adapt to situations better, but technology has gotten to the point that most of the situations they could adapt to are unlikely enough to occur that you'd make up for those occurrences by the redundancy of the probes. The other argument for sending people may be to explore/check out something so totally unexpected that we'd have no way of accounting for it in the probe's programming. But - and this may just be the cynic in me - I think that's extremely unlikely. In a far enough future that this is feasible at all (though granted, if we were OK with the probe taking 10000 years to make it, and another 3000 to get the data, we could do it with today's technology!) tech is (hopefully) going to be so cheap and small that it'll be easy enough to make the probes just collect all the data they can. We think there *might* be objects orbiting the black hole, right? So a couple dozen of those probes will be set to divert course and orbit those instead, and collect data from them. I'm going to assume that they all have advanced physics processing units and would be able to calculate those orbits on the fly. And still some of them might crash (or just veer off into the void), but again, you can send a dozen probes for the cost of one manned mission. I could potentially see live humans as ambassadors in the event that extraterrestrial intelligence is met, but the cynic in me doubly doubts that we'll ever find extraterrestrial life, let alone intelligent life. (It believes such exists - the universe is too vast not to - but it's also too vast to feasibly encounter any.) The probes collecting all that data, petabytes upon petabytes of it, will see any evidence for life that might be out there. They won't recognize it, of course, but the human scientists on earth 15000 years later (after receiving a mysterious signal from space that they decode to find that they can decode it perfectly to ancient English, and after consulting historians who kept the records of ancient, quaint technology are able to realize that a forgotten civilization of a bygone era sent it) *might* glean some evidence that there could be some kind of potential for the conditions of life on one of those bodies. But anyway, the probes aren't really there for that. They're gathering all the data they can because it was cheap at the time, but mostly they were looking at the black hole. Some of that information could provide insights to the current civilization, if they can translate it from a language that died thousands of years ago. But then again, 15000 years into the future of this already future point they may have built a miniature black hole and replicated most of the experiments anyway. Honestly, with the time lag, I'm not sure I see the use of even sending unmanned missions. If I were to even do that it'd just be a probe that has "Kilroy was here" spray-painted on it, just for giggles. Sending a manned mission that distance - no matter how dangerous a black hole is - is a death sentence. (Even if they could come back, everyone and everything they've ever known will have been dead for ages.) That is not a problem for the hero in your story, though, and is in fact kind of a selling point. I have a simple proposition for why they'd send a manned mission - **he wants to go**. "I am going to die anyway, but I'd be the only human in all of human history to see a black hole up close." Sounds like motivation enough for me. In my view, he's not able to convince any government's space agency to let him do that, but a private aerospace firm finds the earnestness in his mission and undertakes (...pun intended) the project. He isn't actually necessary to gather or interpret the data, but he's able to make sense of it when his craft reports it to him. He gets to make all those conclusions and realize that he's the first person in history to not only see a black hole up close, but also finally understand Hawking radiation/information loss/general relativity. He passes away to a peaceful death, as the camera zooms out revealing the cartoon of the fellow with the big nose peeking over the wall, spray-painted onto his ship.
There's no point sending someone into a black hole in and of itself, because once they're in they have no way of sending any findings back. However, sending someone *near* a black hole could allow them to study the various features mentioned in other answers. For the purposes of your story, the mission could be one that goes near a black hole to study it, but with no way to prevent the eventual crossing of the event horizon. That part wouldn't be the actual intent of the mission, but an unavoidable end to a mission focused on what could be done prior to that.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
For science! ============ At present we have two main theories of physics: * General relativity, which is about very heavy things and gravity. * Quantum mechanics, which is about very small things. We have not been able to fit these two together. One of the reasons for this is that we have not been able do experiments that test both at once. Objects that are small enough to have quantum effects are not noticeably affected by gravity. At least not strongly enough that we can distinguish between different theories of gravity. Our other theories (eg. electromagnetism) can be fit with one or the other, but not both at once. Black holes changes things. Here gravity is very strong and even electrons will feel the pull. If we would be able to bring along both a neutrino source and a neutrino detector, we would learn much about these mysterious particles. However, at current or near-future tech levels neutrino detectors are *very* massive and not something you can move off-Earth. Even without that I am sure there are numerous experiments we could do with a humble electron ray that will be very useful. The main experiment I see done is sending a laser or a ray of electrons in very close to the event horizon, and putting a detector where it comes out. Useful results would be angle of deflection and time taken for the journey. Maybe also how spread out the beam has become. If the hole is rotating, sending beams both with and against the rotation will be interesting. Why humans? =========== This is about science, which means we won't know in advance what experiments we want to perform. Results of the one experiment will suggest new physics theories. These will suggest new experiments to perform. A machine cannot do this. (Unless you have powerful AI) If there are no humans on the spot, the results will have to be sent to Earth and new commands sent back. This will take too much time and the black hole will move away before we are done. I suggest a crew consisting of a mixture of astronauts and physicists. Both will need to have a good understanding of the other side, but in the end they are different in their goals. The astronauts will want to keep everybody alive and return home in one piece. The physicists will want to perform more experiments. *More*! **MORE**!! Other answers have suggested sending several unmanned probes instead of a manned one. I suggest a manned ship carrying many unmanned probes. The ship stays prudently far away from the radiation, the probes go closer, not close enough for tidal effects to destroy them, but definitely into hard radiation areas. Parting gift. ============= The time comes when the hole moves away and we have to go home to Earth. Leave something behind for aliens to discover, maybe something like the Pioneer Plaques and Voyager Golden Discs. The hole will be a scientist magnet from every civilization it passes nearby and a good meeting spot. Maybe we will find an alien artifact already there...
My favorite scifi author Greg Egan wrote a short story about just this. It's available free online if you're curious: [The Planck Dive](http://gregegan.customer.netspace.net.au/PLANCK/Complete/Planck.html). Quick TLDR: It's set in a very farflung transhuman society, and they do it out of pure scientific curiosity by forking their personalities. As others have said, there's not really any reason to send a person in on a one way trip except for the experience of it. As you say, a sort of elegant way for a scientifically minded person to die.
62,672
Suppose we detect a stellar black hole passing near the Solar system, and we have technology and time to send a manned mission to study it. Are there any experiments or observations that would help us learn more, maybe test some of our theories or the whole mission is pointless? I would like to use this as a setting, if it makes any sense. **Envisioned Story** My "hero" is a physicist suffering from some kind of incurable disease, that won't prevent him from doing his mission. He knows it's a one way trip and that's why he volunteered to be send there. My plan was to do some observations, experiments with probes, and finally enter the black hole. I know it's a cliche but it feels cool.
2016/11/29
[ "https://worldbuilding.stackexchange.com/questions/62672", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/29225/" ]
There is no point in sending a manned mission! ---------------------------------------------- As @HDE22686 noted, there *are* many interesting phenomena associated with black holes. Given the opportunity to study one up close, it is likely that missions *will* be sent. However, describing all the cool phenomena associated with black holes only means they will be studied - **not that humans will be there to see them** So why on Earth would you send a human to a black hole? ------------------------------------------------------- * **Human error influences data**: This is a once-in-a species (potentially) chance. There is no point sending humans capable of error on board this probe when a *considerable amount of money* is at stake. * **Black holes are deadly**: Any miscalculation in the trajectory of the probe may risk ending human lives, millions of miles away from home - is that really worth it? Additionally, exotic radiation is associated with black holes. It's safest not to play with that. * **We can send other organisms instead**: If the point is seeing the effects black holes have on living tissue, why not send rats? Or dogs? Or chimpanzees? Or a sample of human flesh kept alive by life support? * **Multiple unmanned probes decrease chances of inaccuracy**: While machines *are* capable of failure - see the [*recently crashed Mars rover which was brought down by a glitch*](http://www.news.com.au/technology/science/space/europes-mars-lander-failure-caused-by-glitch-but-gives-researchers-valuable-lesson/news-story/a2db7c2f2c470ffe31117c6ec24868eb) - many agencies capable of sending probes *will do so*, meaning data collected will generally reflect the truth. Compare this to multiple probes with humans on board. * **Missions are flybys**: When we send spacecraft out of the solar system to observe distant objects, we never intend to get them back - and even if we wanted to, it's extremely expensive! The first few generations of Mars colonists will be stuck on Mars forever because we aren't willing to pay for ships capable of escaping Mars after landing. With that in mind, why would we send people out of the Solar System and then attempt to get them back? * **Machines are competent and won't need to make major decisions**: While humans *can* make on-the-spot decisions, a probe with basic sensors, locomotion, and apparatus is capable of steering itself. No situation will arise where *only* a human could decide what to do. **In conclusion,** we'll be killing people - who could mess up the missions - in strange and potentially cruel ways, millions of miles away from home, with no chance of retrieval - **when machines can do the job even better.** Missions? Yes! People? *No*.
Send Humans! Why? Because of archaeology... As others have stated, computers can handle the mission, running a bunch of experiments and sending us back the results. Those automated experiments are, by definition, limited to studying the expected characteristics of the black hole. They can test for minute variances in established theories and provide detailed measurements of the black hole's physical characteristics. But automated experiments cannot study the unexpected. That black hole may have a solar system of its own, spinning around it in slowly decreasing orbits. The planets of that solar system will vary in origin, having been stolen from different solar systems which the black hole passed through. Studying those planets and their surrounding dust clouds, is our opportunity to sample matter from farther away than we could ever travel. And some of those adopted worlds may even have once harbored intelligent life.
50,730,394
I am running `knife client list` and getting the following error: ``` ERROR: Failed to authenticate to https://chef-server.dev.reach.IE.LOCAL/organizations/accenture as chef-user with key /home/svc.jenkins/helix-chef/iac_chef_standalone_wso2/.chef/chef-user.pem Response: Failed to authenticate as chef-user. Synchronize the clock on your host. ``` The weird thing is that this just worked a second ago with the output message of: ``` $ knife client list accenture-validator ``` I just ran ``knife client list``` again and received the error though (nothing has changed that should have caused this) **Knife.rb:** ``` current_dir = File.dirname(__FILE__) log_level :info log_location STDOUT node_name "chef-user" client_key "#{current_dir}/chef-user.pem" validation_client_name "accenture-validator" validation_key "#{current_dir}/accenture-validator.pem" chef_server_url "https://chef-server.dev.reach.IE.LOCAL/organizations/accenture" cache_type 'BasicFile' cache_options( :path => "#{ENV['HOME']}/.chef/checksums" ) cookbook_path ["#{current_dir}/../cookbooks"] ``` **Knife ssl check:** ``` $ knife ssl check Connecting to host chef-server.dev.reach.IE.LOCAL:443 ``` **Knife version:** ``` $ knife --version Chef: 14.1.12 ``` (running on RedHat 7) Does anyone know why I am getting the error and how I could resolve it? * Thank you in advance!
2018/06/06
[ "https://Stackoverflow.com/questions/50730394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6928292/" ]
As the error says "Synchronize the clock on your host." Either your system clock or the clock on the Chef Server is incorrect (or in the wrong time zone relative to what it is set to). To limit replay attacks, we put a signed timestamp in all requests and it has to be within a fairly narrow window (minutes, but not seconds). That error means the server thinks your timestamp is too far out, so one or both of you is wrong about the current time.
Open terminal 1. Write sudo su (to login as administrator) 2. Use the following command -> date +%T -s "11:14:00" This worked for me
556,380
I am using the command ``` sudo git clone git://git.moodle.org/moodle.git ``` to download moodle. After partial downloading, it just halts without any valid reason. How can I suspend the job at such a stage and resume it later?
2019/12/09
[ "https://unix.stackexchange.com/questions/556380", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/385605/" ]
If your `sed` is able to use the non-standard `-E` option to understand extended regular expressions, you may use ``` sed -E 's/string1|string2|string3/true/g' ``` The alternation with `|` is an extended regular expression feature not supported by basic regular expression of the type that `sed` usually supports. The `sed` command above would replace any of the three given string even if they occurred as substrings of other strings (such as `string1` in `string10`). To prevent that, also match word boundaries on either side: ``` sed -E 's/\<(string1|string2|string3)\>/true/g' ``` On macOS, you may want to use `[[:<:]]` and `[[:>:]]` in place of `\<` and `\>` to specify word boundaries. --- As an aside, your `s/[a|b|m]/x/g` expression (now corrected in the question) would not only replace `a`, `b` and `m` with `x` but would also replace any `|` in the text with `x`. This is the same as `s/[abm|]/x/g` or `y/abm|/xxxx/`, or the `tr` commands `tr 'abm|' 'xxxx'` and `tr 'abm|' '[x*4]'`.
Is this what you are looking for? With GNU `sed`: ``` sed -E 's/(command1|command2|command3)/true/' file ```
556,380
I am using the command ``` sudo git clone git://git.moodle.org/moodle.git ``` to download moodle. After partial downloading, it just halts without any valid reason. How can I suspend the job at such a stage and resume it later?
2019/12/09
[ "https://unix.stackexchange.com/questions/556380", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/385605/" ]
Is this what you are looking for? With GNU `sed`: ``` sed -E 's/(command1|command2|command3)/true/' file ```
POSIXly, you could use `awk`: ``` awk '{gsub(/command1|command2|command3/, "true"); print}' < file ``` ([`sed -E` is likely to be specified in the next major of the POSIX standard](http://austingroupbugs.net/view.php?id=528) though, so it will probably spread to most implementations eventually).
556,380
I am using the command ``` sudo git clone git://git.moodle.org/moodle.git ``` to download moodle. After partial downloading, it just halts without any valid reason. How can I suspend the job at such a stage and resume it later?
2019/12/09
[ "https://unix.stackexchange.com/questions/556380", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/385605/" ]
If your `sed` is able to use the non-standard `-E` option to understand extended regular expressions, you may use ``` sed -E 's/string1|string2|string3/true/g' ``` The alternation with `|` is an extended regular expression feature not supported by basic regular expression of the type that `sed` usually supports. The `sed` command above would replace any of the three given string even if they occurred as substrings of other strings (such as `string1` in `string10`). To prevent that, also match word boundaries on either side: ``` sed -E 's/\<(string1|string2|string3)\>/true/g' ``` On macOS, you may want to use `[[:<:]]` and `[[:>:]]` in place of `\<` and `\>` to specify word boundaries. --- As an aside, your `s/[a|b|m]/x/g` expression (now corrected in the question) would not only replace `a`, `b` and `m` with `x` but would also replace any `|` in the text with `x`. This is the same as `s/[abm|]/x/g` or `y/abm|/xxxx/`, or the `tr` commands `tr 'abm|' 'xxxx'` and `tr 'abm|' '[x*4]'`.
POSIXly, you could use `awk`: ``` awk '{gsub(/command1|command2|command3/, "true"); print}' < file ``` ([`sed -E` is likely to be specified in the next major of the POSIX standard](http://austingroupbugs.net/view.php?id=528) though, so it will probably spread to most implementations eventually).
23,889,614
what i'm trying to do is to save a file in a remote server which is created on openshift (i created an application with php 5.3). this is the code which sends a file: ``` private void postFile(){ try{ String postReceiverUrl = "https://openshift.redhat.com/app/console/application/537e9c0be0b8cd34170000b6-alldata"; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(postReceiverUrl); File file = new File(detail); FileBody fileBody = new FileBody(file); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("file", fileBody); httpPost.setEntity(reqEntity); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); if(resEntity != null){ String responseStr = EntityUtils.toString(resEntity).trim(); Log.v("MyApp", "Response:" + responseStr); } else Log.v("MyApp", "couldn't commnicate with the server"); }catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } ``` It throws an exception when it executes the following line: ``` HttpResponse response = httpClient.execute(httpPost); ``` this is the logcat message: ``` 05-27 15:32:01.557: D/libEGL(18546): loaded /vendor/lib/egl/libEGL_POWERVR_SGX544_115.so 05-27 15:32:01.607: D/libEGL(18546): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX544_115.so 05-27 15:32:01.627: D/libEGL(18546): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX544_115.so 05-27 15:32:01.697: D/OpenGLRenderer(18546): Enabling debug mode 0 05-27 15:32:06.717: I/dalvikvm(18546): Total arena pages for JIT: 11 05-27 15:32:06.717: I/dalvikvm(18546): Total arena pages for JIT: 12 05-27 15:32:06.727: D/dalvikvm(18546): Rejecting registerization due to and-int/lit16 v0, v5, (#128) 05-27 15:32:06.737: D/dalvikvm(18546): Rejecting registerization due to and-int/lit16 v0, v5, (#128) 05-27 15:32:06.817: D/dalvikvm(18546): Rejecting registerization due to move v5, v4, (#0) 05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to move v5, v4, (#0) 05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to mul-int/lit8 v4, v2, (#31) 05-27 15:32:06.827: D/dalvikvm(18546): Rejecting registerization due to mul-int/lit8 v4, v2, (#31) 05-27 15:32:06.827: D/dalvikvm(18546): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE 05-27 15:32:06.837: W/dalvikvm(18546): VFY: unable to resolve static field 3758 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser; 05-27 15:32:06.837: D/dalvikvm(18546): VFY: replacing opcode 0x62 at 0x001b 05-27 15:32:06.837: D/dalvikvm(18546): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE 05-27 15:32:06.837: W/dalvikvm(18546): VFY: unable to resolve static field 3752 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter; 05-27 15:32:06.837: D/dalvikvm(18546): VFY: replacing opcode 0x62 at 0x0015 05-27 15:32:06.857: W/System.err(18546): android.os.NetworkOnMainThreadException 05-27 15:32:06.867: W/System.err(18546): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128) 05-27 15:32:06.877: W/System.err(18546): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 05-27 15:32:06.877: W/System.err(18546): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 05-27 15:32:06.877: W/System.err(18546): at java.net.InetAddress.getAllByName(InetAddress.java:214) 05-27 15:32:06.877: D/dalvikvm(18546): Rejecting registerization due to +iget-quick v3, v5, (#20) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 05-27 15:32:06.877: W/System.err(18546): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 05-27 15:32:06.877: W/System.err(18546): at com.measuredistancewalked.PostData.postFile(PostData.java:108) 05-27 15:32:06.877: W/System.err(18546): at com.measuredistancewalked.PostData.writeFile(PostData.java:82) 05-27 15:32:06.877: W/System.err(18546): at com.measuredistancewalked.PostData.saveAllData(PostData.java:58) 05-27 15:32:06.877: W/System.err(18546): at com.measuredistancewalked.DitanceWalkedActivity$1.onClick(DitanceWalkedActivity.java:74) 05-27 15:32:06.877: W/System.err(18546): at android.view.View.performClick(View.java:4383) 05-27 15:32:06.877: W/System.err(18546): at android.view.View$PerformClick.run(View.java:18097) 05-27 15:32:06.877: W/System.err(18546): at android.os.Handler.handleCallback(Handler.java:725) 05-27 15:32:06.877: W/System.err(18546): at android.os.Handler.dispatchMessage(Handler.java:92) 05-27 15:32:06.877: W/System.err(18546): at android.os.Looper.loop(Looper.java:176) 05-27 15:32:06.877: W/System.err(18546): at android.app.ActivityThread.main(ActivityThread.java:5279) 05-27 15:32:06.877: W/System.err(18546): at java.lang.reflect.Method.invokeNative(Native Method) 05-27 15:32:06.877: W/System.err(18546): at java.lang.reflect.Method.invoke(Method.java:511) 05-27 15:32:06.877: W/System.err(18546): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 05-27 15:32:06.877: W/System.err(18546): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 05-27 15:32:06.877: W/System.err(18546): at dalvik.system.NativeStart.main(Native Method) 05-27 15:32:06.887: D/dalvikvm(18546): Rejecting registerization due to +iget-object-quick v7, v9, (#8) 05-27 15:32:06.907: I/dalvikvm(18546): Total arena pages for JIT: 13 05-27 15:32:06.907: I/dalvikvm(18546): Total arena pages for JIT: 14 ``` and I have the following post\_file.php code : ``` <?php if($_FILES){ $file = $_FILES['file']; $fileContents = file_get_contents($file["all_data_file"]); print_r($fileContents); } ?> ``` my question is : where do i upload my php code? and what else should i do to communicate with the server other than providing my openshift application url in my code? Thank you for your help in advance!
2014/05/27
[ "https://Stackoverflow.com/questions/23889614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3656442/" ]
If your app crashes always take a look at the logcat. In 99% of all cases the error message tells you exactly what's wrong and how you can fix it, just like in your case: ``` 05-27 15:32:06.857: W/System.err(18546): android.os.NetworkOnMainThreadException ``` You cannot perform complex tasks in the UI Thread, doing so would cause your app to freeze and lag. In Android there is an extra safe guard against this when it comes to networking. If you try to perform network operations on the UI thread an Exception is thrown, namely this `NetworkOnMainThreadException`. **Solution:** You have to perform your work in a separate `Thread`. I recommend you use an `AsyncTask` for this. Take a look at this example for an `AsyncTask`, the method `doInBackground()` is executed in a separate `Thread`, you can perform all your work there. After `doInBackground()` has finished the result returned by it will be passed to `onPostExecute()`. `onPostExecute()` will again be executed on the UI Thread, so here you can return results from the `AsyncTask` to the UI. ``` private class ExampleTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { // Do your work here // Return true if successful otherwise false return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(result) { // Work has been completed successfully } else { // Work was not completed successfully } } } ```
You need to move network activity off of the UI thread, it should be handled in an `AsyncTask`. ``` private class upload extends AsyncTask<URL, Integer, Long> { private void doInBackground(URL... urls) { try { String postReceiverUrl = "https://openshift.redhat.com/app/console/application/537e9c0be0b8cd34170000b6-alldata"; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(postReceiverUrl); File file = new File(detail); FileBody fileBody = new FileBody(file); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("file", fileBody); httpPost.setEntity(reqEntity); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); if(resEntity != null) { String responseStr = EntityUtils.toString(resEntity).trim(); Log.v("MyApp", "Response:" + responseStr); } else { Log.v("MyApp", "couldn't commnicate with the server"); } } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } ``` You execute the `AsyncTask` like this: ``` new upload().execute(url); ```
13,558,362
In Xcode 4.5 apple introduced apple new maps. My application heavliy requires map services. And I have noticed in my application it shows the wrong current location until you delete the app and reopen it shows the right current location (Sometimes it doesn't). Just to mention I was connected to 4G when it show the wrong current location. Is there a way to fix this bug because my application heavily needs the right location. Thanks in advance. If you could provide code it would help a lot...**Edit:** Same Issue in Apple Map App **My Code:** ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { { } if (!oldLocation) totalDistance = 0.0; else totalDistance += [newLocation distanceFromLocation:oldLocation]; } ```
2012/11/26
[ "https://Stackoverflow.com/questions/13558362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The old approach from apple docs seems still working in iOS6 (didn't notice this in my active app (it tracks user's route via gps)) ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; if (newLocation.horizontalAccuracy < 0) return; // proceed with coords here } ``` *UPDATE* from the discussion: Calculating total and current distance could be done like this (excluding some minor stuff): ``` // somewhere at the top CLLocation* lastUsedLocation = nil; // last location used in calculation CLLocation* pointA = nil; // start of the track double totalDistance = 0; // total distance of track double currentDistance = 0; // distance between startTrack point and current location ... // when you start updating location: - (void) startTracking { lastUsedLocation = nil; pointA = nil; totalDistance = 0; currentDistance = 0; [locationManager startUpdatingLocation]; } ... // location update callback - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; // filter cached if (newLocation.horizontalAccuracy < 0) return; // filter invalid if(!pointA) pointA = [newLocation retain]; if(lastUsedLocation) { totalDistance += [newLocation distanceFromLocation:lastUsedLocation]; } currentDistance = [pointA distanceFromLocation:newLocation]; [lastUsedLocation release]; lastUsedLocation = [newLocation retain]; } ``` If you need the option to turn off background location on purpose you disable it manually like: ``` - (void)applicationDidEnterBackground:(UIApplication *)application { if(backgroundLocationDisabled) { [locationManager stopUpdatingLocation]; // additional stuff } } ```
you should check the timestamp .. if i understand your app logic correctly, you could do something like - ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSDate* time = newLocation.timestamp; NSTimeInterval timePeriod = [time timeIntervalSinceNow]; if(timePeriod < SOME_MINIMUM_TIME_PERIOD ) { //for eg: timePeriod < 1.0 totalDistance += [newLocation distanceFromLocation:oldLocation]; } else { // skip.. or do what you do on a 'location-not-updated' event } } ```
13,558,362
In Xcode 4.5 apple introduced apple new maps. My application heavliy requires map services. And I have noticed in my application it shows the wrong current location until you delete the app and reopen it shows the right current location (Sometimes it doesn't). Just to mention I was connected to 4G when it show the wrong current location. Is there a way to fix this bug because my application heavily needs the right location. Thanks in advance. If you could provide code it would help a lot...**Edit:** Same Issue in Apple Map App **My Code:** ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { { } if (!oldLocation) totalDistance = 0.0; else totalDistance += [newLocation distanceFromLocation:oldLocation]; } ```
2012/11/26
[ "https://Stackoverflow.com/questions/13558362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you should check the timestamp .. if i understand your app logic correctly, you could do something like - ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSDate* time = newLocation.timestamp; NSTimeInterval timePeriod = [time timeIntervalSinceNow]; if(timePeriod < SOME_MINIMUM_TIME_PERIOD ) { //for eg: timePeriod < 1.0 totalDistance += [newLocation distanceFromLocation:oldLocation]; } else { // skip.. or do what you do on a 'location-not-updated' event } } ```
I have noticed the same problem with Xcode 4.4+. The problem only occurs (randomly, or so it seems) within Xcode: if you upload the app to the App Store, this is not a problem anymore. In the meantime, please file a bug.
13,558,362
In Xcode 4.5 apple introduced apple new maps. My application heavliy requires map services. And I have noticed in my application it shows the wrong current location until you delete the app and reopen it shows the right current location (Sometimes it doesn't). Just to mention I was connected to 4G when it show the wrong current location. Is there a way to fix this bug because my application heavily needs the right location. Thanks in advance. If you could provide code it would help a lot...**Edit:** Same Issue in Apple Map App **My Code:** ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { { } if (!oldLocation) totalDistance = 0.0; else totalDistance += [newLocation distanceFromLocation:oldLocation]; } ```
2012/11/26
[ "https://Stackoverflow.com/questions/13558362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The old approach from apple docs seems still working in iOS6 (didn't notice this in my active app (it tracks user's route via gps)) ``` - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; if (newLocation.horizontalAccuracy < 0) return; // proceed with coords here } ``` *UPDATE* from the discussion: Calculating total and current distance could be done like this (excluding some minor stuff): ``` // somewhere at the top CLLocation* lastUsedLocation = nil; // last location used in calculation CLLocation* pointA = nil; // start of the track double totalDistance = 0; // total distance of track double currentDistance = 0; // distance between startTrack point and current location ... // when you start updating location: - (void) startTracking { lastUsedLocation = nil; pointA = nil; totalDistance = 0; currentDistance = 0; [locationManager startUpdatingLocation]; } ... // location update callback - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; // filter cached if (newLocation.horizontalAccuracy < 0) return; // filter invalid if(!pointA) pointA = [newLocation retain]; if(lastUsedLocation) { totalDistance += [newLocation distanceFromLocation:lastUsedLocation]; } currentDistance = [pointA distanceFromLocation:newLocation]; [lastUsedLocation release]; lastUsedLocation = [newLocation retain]; } ``` If you need the option to turn off background location on purpose you disable it manually like: ``` - (void)applicationDidEnterBackground:(UIApplication *)application { if(backgroundLocationDisabled) { [locationManager stopUpdatingLocation]; // additional stuff } } ```
I have noticed the same problem with Xcode 4.4+. The problem only occurs (randomly, or so it seems) within Xcode: if you upload the app to the App Store, this is not a problem anymore. In the meantime, please file a bug.
8,963,724
I am trying to get Junit work with Ant. I have come across questions on the topic. I guess there is some small error somewhere but I can't figure it out. Here is my Build file: ``` <?xml version="1.0" encoding="UTF-8"?> <project name="IvleFileSync" default="dist" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src"/> <property name="build" location="build"/> <property name="dist" location="dist"/> <!-- Variables used for JUnit testing --> <property name="test.dir" location="test" /> <property name="test.report.dir" location="test-reports" /> <path id="junit-classpath"> <fileset dir="${test.dir}"> <include name = "*" /> </fileset> </path> <path id="files-classpath"> <fileset dir="/usr/lib" > <include name="*.jar"/> </fileset> </path> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> <mkdir dir="${test.report.dir}" /> </target> <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"> <classpath> <path refid="files-classpath" /> </classpath> </javac> </target> <target name="dist" depends="compile" description="generate the distribution" > <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/IvleFileSync-${DSTAMP}.jar" basedir="${build}"/> </target> <target name="compile-test" depends="compile" description="compile the tests " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${test.dir}" destdir="${build}"> <classpath> <path refid="files-classpath" /> </classpath> </javac> </target> <target name="test" depends="compile-test" description="Execute Unit Tests" > <junit printsummary="yes" fork="yes" haltonfailure="yes" showoutput="false"> <classpath > <path refid="files-classpath" /> <path refid= "junit-classpath" /> </classpath> <batchtest fork="yes" todir="${test.report.dir}/"> <formatter type="xml"/> <fileset dir="${test.dir}"> <include name="*Test*.java"/> </fileset> </batchtest> </junit> </target> <target name="clean" description="clean up" > <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${test.report.dir}" /> <delete dir="${dist}"/> </target> </project> ``` And I have test files in /test directory as well as i have put the jars in ANT\_HOME/lib That does not work and I get this error when I dig up the test-results/....xml ``` <error message="NewEmptyJUnitTest" type="java.lang.ClassNotFoundException">java.lang.ClassNotFoundException: NewEmptyJUnitTest at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) ``` Thanks for helping me out...
2012/01/22
[ "https://Stackoverflow.com/questions/8963724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611229/" ]
The classpath for the junit task does not include the output of the compile-test target. Use something like the following for the JUnit classpath: ``` <classpath> <pathelement path="${build}"/> <path refid="files-classpath" /> <path refid="junit-classpath" /> </classpath> ```
You forgot to add your own classes ("build") to the "test" target.
39,078,835
I have irregularly spaced time-series data. I have total energy usage and the duration over which the energy was used. ``` Start Date Start Time Duration (Hours) Usage(kWh) 1/3/2016 12:28:00 PM 2.233333333 6.23 1/3/2016 4:55:00 PM 1.9 11.45 1/4/2016 6:47:00 PM 7.216666667 11.93 1/4/2016 7:00:00 AM 3.45 9.45 1/4/2016 7:26:00 AM 1.6 7.33 1/4/2016 7:32:00 AM 1.6 4.54 ``` I want to calculate the sum of all the load curves over a 15 minute window. I can round when necessary (e.g., closest 1 minute). I can't use resample immediately because it would average the usage into the next time stamp, which n the case of the first entry 1/3 12:28 PM, would take 6.23 kWH and spread it evenly until 4:55 PM, which is inaccurate. 6.23 kWh should be spread until 12:28 PM + 2.23 hrs ~= 2:42 PM.
2016/08/22
[ "https://Stackoverflow.com/questions/39078835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5948903/" ]
Here is a straight-forward implementation which simply sets up a Series, `result`, whose index has minute-frequency, and then loops through the rows of `df` (using `df.itertuples`) and adds the appropriate amount of power to each row in the associated interval: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'Duration (Hours)': [2.233333333, 1.8999999999999999, 7.2166666670000001, 3.4500000000000002, 1.6000000000000001, 1.6000000000000001], 'Start Date': ['1/3/2016', '1/3/2016', '1/4/2016', '1/4/2016', '1/4/2016', '1/4/2016'], 'Start Time': ['12:28:00 PM', '4:55:00 PM', '6:47:00 PM', '7:00:00 AM', '7:26:00 AM', '7:32:00 AM'], 'Usage(kWh)': [6.2300000000000004, 11.449999999999999, 11.93, 9.4499999999999993, 7.3300000000000001, 4.54]} ) df['duration'] = pd.to_timedelta(df['Duration (Hours)'], unit='H') df['start_date'] = pd.to_datetime(df['Start Date'] + ' ' + df['Start Time']) df['end_date'] = df['start_date'] + df['duration'] df['power (kW/min)'] = df['Usage(kWh)']/(df['Duration (Hours)']*60) df = df.drop(['Start Date', 'Start Time', 'Duration (Hours)'], axis=1) result = pd.Series(0, index=pd.date_range(df['start_date'].min(), df['end_date'].max(), freq='T')) power_idx = df.columns.get_loc('power (kW/min)')+1 for row in df.itertuples(): result.loc[row.start_date:row.end_date] += row[power_idx] # The sum of the usage over 15 minute windows is computed using the `resample/sum` method: usage = result.resample('15T').sum() usage.plot(kind='line', label='usage') plt.legend(loc='best') plt.show() ``` [enter image description here](https://i.stack.imgur.com/2lvUa.png) ------------------------------------------------------------------- **A note regarding performance**: Looping through the rows of `df` is not very fast especially if `len(df)` is big. For better performance, you may need a [more clever method](https://stackoverflow.com/a/31773404/190597), which handles all the rows "at once" in a vectorized manner: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt # Here is an example using a larger DataFrame N = 10**3 dates = pd.date_range('2016-1-1', periods=N*10, freq='H') df = pd.DataFrame({'Duration (Hours)': np.random.uniform(1, 10, size=N), 'start_date': np.random.choice(dates, replace=False, size=N), 'Usage(kWh)': np.random.uniform(1,20, size=N)}) df['duration'] = pd.to_timedelta(df['Duration (Hours)'], unit='H') df['end_date'] = df['start_date'] + df['duration'] df['power (kW/min)'] = df['Usage(kWh)']/(df['Duration (Hours)']*60) def using_loop(df): result = pd.Series(0, index=pd.date_range(df['start_date'].min(), df['end_date'].max(), freq='T')) power_idx = df.columns.get_loc('power (kW/min)')+1 for row in df.itertuples(): result.loc[row.start_date:row.end_date] += row[power_idx] usage = result.resample('15T').sum() return usage def using_cumsum(df): result = pd.melt(df[['power (kW/min)','start_date','end_date']], id_vars=['power (kW/min)'], var_name='usage', value_name='date') result['usage'] = result['usage'].map({'start_date':1, 'end_date':-1}) result['usage'] *= result['power (kW/min)'] result = result.set_index('date') result = result[['usage']].resample('T').sum().fillna(0).cumsum() usage = result.resample('15T').sum() return usage usage = using_cumsum(df) usage.plot(kind='line', label='usage') plt.legend(loc='best') plt.show() ``` --- With `len(df)` equal to 1000, `using_cumsum` is over 10x faster than `using_loop`: ``` In [117]: %timeit using_loop(df) 1 loop, best of 3: 545 ms per loop In [118]: %timeit using_cumsum(df) 10 loops, best of 3: 52.7 ms per loop ```
The solution I used below is the itertuples method. Please note using numpy's .sum function did not work for me. I instead used the pandas resample keyword, "how" and set it equal to sum. I also renamed the columns in my files to make the import easier. I was not time/resource constrained so I went with the itertuples method because it was easy for me to implement. **Itertuples Code** ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #load data df = pd.read_excel(r'C:\input_file.xlsx', sheetname='sheet1') #convert columns df['duration'] = pd.to_timedelta(df['Duration (Hours)'], unit='H') df['end_date'] = df['start_date'] + df['duration'] df['power (kW/min)'] = df['Usage(kWh)']/(df['Duration (Hours)']*60) df = df.drop(['Duration (Hours)'], axis=1) #create result df with timestamps result = pd.Series(0, index=pd.date_range(df['start_date'].min(), df['end_date'].max(), freq='T')) #iterate through to calculate total energy at each minute power_idx = df.columns.get_loc('power (kW/min)')+1 for row in df.itertuples(): result.loc[row.start_date:row.end_date] += row[power_idx] # The sum of the usage over 15 minute windows is computed using the `resample/sum` method usage = result.resample('15T', how='sum') #plot plt.plot(usage) plt.show() #write to file usage.to_csv(r'C:\output_folder\output_file.csv') ``` [![Solution using itertuples method](https://i.stack.imgur.com/PXXaL.png)](https://i.stack.imgur.com/PXXaL.png)
62,821,375
I want to check bydefault one radiobutton from three option in nopcommerce 4.3 Here is my code, ``` <div class="col-md-6"> <div class="raw"> <div class="col-md-2"> <div class="radio"> <label> @Html.RadioButton("LabourChargeUnit", "false", (Model.LabourChargeUnit == "PCS"), new { id = "LabourChargeUnit_PCS"}) @T("Admin.Catalog.Product.Fields.LabourChargeUnit.PCS") </label> </div> </div> <div class="col-md-2"> <div class="radio"> <label> @Html.RadioButton("LabourChargeUnit", "false", (Model.LabourChargeUnit == "PER"), new { id = "LabourChargeUnit_PER" }) @T("Admin.Catalog.Product.Fields.LabourChargeUnit.PER") </label> </div> </div> <div class="col-md-2"> <div class="radio"> <label> @Html.RadioButton("LabourChargeUnit", "true", (Model.LabourChargeUnit == "GM"), new { id = "LabourChargeUnit_GM" }) @T("Admin.Catalog.Product.Fields.LabourChargeUnit.GM") </label> </div> </div> </div> </div> ``` Now, I have tried many things like **new{@checked = "checked"}, true/false, 0/1** but didnt work.
2020/07/09
[ "https://Stackoverflow.com/questions/62821375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7449534/" ]
Here is your widget ``` Center( child: Container( width: 200, height: 100, decoration: BoxDecoration( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20.0)), gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Color(0xFF9B6EEF), Color(0xFF715ED7)]), ), child: ClipRect(child: CustomPaint(painter: CirclePainter())), ), ), ``` **CustomPainter** class for rings inside ``` class CirclePainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { var paint = Paint() ..color = Colors.white10 ..style = PaintingStyle.stroke ..strokeWidth = 25; canvas.drawCircle(Offset.zero, 60, paint); canvas.drawCircle(Offset(size.width, size.height), 60, paint); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } } ``` **Result** [![enter image description here](https://i.stack.imgur.com/K5OKh.png)](https://i.stack.imgur.com/K5OKh.png)
[![sample](https://i.stack.imgur.com/4MxEE.png)](https://i.stack.imgur.com/4MxEE.png) --- ``` main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: SO(), debugShowCheckedModeBanner: false, ); } } class SO extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ClipRRect( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(24)), child: CustomPaint( size: Size(250, 200), painter: SOP( fillColor: Colors.indigo, spreadColor: Colors.indigoAccent, spread: 25, radius: 100, ), ), ), ), ); } } class SOP extends CustomPainter { final double spread; //the thickness of inner circles final Color spreadColor; //the color of inner circles final Color fillColor; //the background color final double radius; //the radius of inner circles final Paint p; SOP({ @required this.spread, @required this.spreadColor, @required this.fillColor, @required this.radius, }) : p = Paint() ..strokeWidth = spread ..style = PaintingStyle.stroke ..color = spreadColor; @override void paint(Canvas canvas, Size size) { canvas.drawColor(fillColor, BlendMode.src); canvas.drawCircle(Offset(0, 0), radius, p); canvas.drawCircle(Offset(size.width, size.height), radius, p); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; } ```
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
While searching this very question I discovered this example in the [documentation](https://doc.qt.io/qt-5/qcoreapplication.html#quit). ``` QPushButton *quitButton = new QPushButton("Quit"); connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection); ``` Mutatis mutandis for your particular action of course. Along with this note. > > It's good practice to always connect signals to this slot using a > QueuedConnection. If a signal connected (non-queued) to this slot is > emitted before control enters the main event loop (such as before "int > main" calls exec()), the slot has no effect and the application never > exits. Using a queued connection ensures that the slot will not be > invoked until after control enters the main event loop. > > > It's common to connect the QGuiApplication::lastWindowClosed() signal > to quit() > > >
if you need to close your application from main() you can use this code ``` int main(int argc, char *argv[]){ QApplication app(argc, argv); ... if(!QSslSocket::supportsSsl()) return app.exit(0); ... return app.exec(); } ``` The program will terminated if OpenSSL is not installed
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
You can call `qApp->exit();`. I always use that and never had a problem with it. If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
While searching this very question I discovered this example in the [documentation](https://doc.qt.io/qt-5/qcoreapplication.html#quit). ``` QPushButton *quitButton = new QPushButton("Quit"); connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection); ``` Mutatis mutandis for your particular action of course. Along with this note. > > It's good practice to always connect signals to this slot using a > QueuedConnection. If a signal connected (non-queued) to this slot is > emitted before control enters the main event loop (such as before "int > main" calls exec()), the slot has no effect and the application never > exits. Using a queued connection ensures that the slot will not be > invoked until after control enters the main event loop. > > > It's common to connect the QGuiApplication::lastWindowClosed() signal > to quit() > > >
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
If you're using Qt Jambi, this should work: ``` QApplication.closeAllWindows(); ```
if you need to close your application from main() you can use this code ``` int main(int argc, char *argv[]){ QApplication app(argc, argv); ... if(!QSslSocket::supportsSsl()) return app.exit(0); ... return app.exec(); } ``` The program will terminated if OpenSSL is not installed
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
If you're using Qt Jambi, this should work: ``` QApplication.closeAllWindows(); ```
``` //How to Run App bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe"); qDebug() << "Run = " << ok; //How to Kill App system("taskkill /im CozxyLogger.exe /f"); qDebug() << "Close"; ``` [example](https://i.stack.imgur.com/A5Tfx.png)
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
You can call `qApp->exit();`. I always use that and never had a problem with it. If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
if you need to close your application from main() you can use this code ``` int main(int argc, char *argv[]){ QApplication app(argc, argv); ... if(!QSslSocket::supportsSsl()) return app.exit(0); ... return app.exec(); } ``` The program will terminated if OpenSSL is not installed
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
QApplication is derived from QCoreApplication and thereby inherits `quit()` which is a public slot of `QCoreApplication`, so there is no difference between `QApplication::quit()` and `QCoreApplication::quit()`. As we can read in the documentation of [`QCoreApplication::quit()`](http://doc.qt.io/qt-5/qcoreapplication.html#quit) it *"tells the application to exit with return code 0 (success)."*. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call [`QCoreApplication::exit()`](http://doc.qt.io/qt-5/qcoreapplication.html#exit) because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that *"if the event loop is not running, this function (QCoreApplication::exit()) does nothing"*, so in that case you should call `exit(EXIT_FAILURE)`.
While searching this very question I discovered this example in the [documentation](https://doc.qt.io/qt-5/qcoreapplication.html#quit). ``` QPushButton *quitButton = new QPushButton("Quit"); connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection); ``` Mutatis mutandis for your particular action of course. Along with this note. > > It's good practice to always connect signals to this slot using a > QueuedConnection. If a signal connected (non-queued) to this slot is > emitted before control enters the main event loop (such as before "int > main" calls exec()), the slot has no effect and the application never > exits. Using a queued connection ensures that the slot will not be > invoked until after control enters the main event loop. > > > It's common to connect the QGuiApplication::lastWindowClosed() signal > to quit() > > >
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
QApplication is derived from QCoreApplication and thereby inherits `quit()` which is a public slot of `QCoreApplication`, so there is no difference between `QApplication::quit()` and `QCoreApplication::quit()`. As we can read in the documentation of [`QCoreApplication::quit()`](http://doc.qt.io/qt-5/qcoreapplication.html#quit) it *"tells the application to exit with return code 0 (success)."*. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call [`QCoreApplication::exit()`](http://doc.qt.io/qt-5/qcoreapplication.html#exit) because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that *"if the event loop is not running, this function (QCoreApplication::exit()) does nothing"*, so in that case you should call `exit(EXIT_FAILURE)`.
``` //How to Run App bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe"); qDebug() << "Run = " << ok; //How to Kill App system("taskkill /im CozxyLogger.exe /f"); qDebug() << "Close"; ``` [example](https://i.stack.imgur.com/A5Tfx.png)
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
QApplication is derived from QCoreApplication and thereby inherits `quit()` which is a public slot of `QCoreApplication`, so there is no difference between `QApplication::quit()` and `QCoreApplication::quit()`. As we can read in the documentation of [`QCoreApplication::quit()`](http://doc.qt.io/qt-5/qcoreapplication.html#quit) it *"tells the application to exit with return code 0 (success)."*. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call [`QCoreApplication::exit()`](http://doc.qt.io/qt-5/qcoreapplication.html#exit) because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that *"if the event loop is not running, this function (QCoreApplication::exit()) does nothing"*, so in that case you should call `exit(EXIT_FAILURE)`.
If you're using Qt Jambi, this should work: ``` QApplication.closeAllWindows(); ```
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
QApplication is derived from QCoreApplication and thereby inherits `quit()` which is a public slot of `QCoreApplication`, so there is no difference between `QApplication::quit()` and `QCoreApplication::quit()`. As we can read in the documentation of [`QCoreApplication::quit()`](http://doc.qt.io/qt-5/qcoreapplication.html#quit) it *"tells the application to exit with return code 0 (success)."*. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call [`QCoreApplication::exit()`](http://doc.qt.io/qt-5/qcoreapplication.html#exit) because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that *"if the event loop is not running, this function (QCoreApplication::exit()) does nothing"*, so in that case you should call `exit(EXIT_FAILURE)`.
if you need to close your application from main() you can use this code ``` int main(int argc, char *argv[]){ QApplication app(argc, argv); ... if(!QSslSocket::supportsSsl()) return app.exit(0); ... return app.exec(); } ``` The program will terminated if OpenSSL is not installed
8,026,101
How should I quit a Qt Program, e.g when loading a data file, and discovered file corruption, and user need to quit this app or re-initiate data file? Should I: 1. call `exit(EXIT_FAILURE)` 2. call `QApplication::quit()` 3. call `QCoreApplication::quit()` And difference between (2) and (3)?
2011/11/06
[ "https://Stackoverflow.com/questions/8026101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614944/" ]
QApplication is derived from QCoreApplication and thereby inherits `quit()` which is a public slot of `QCoreApplication`, so there is no difference between `QApplication::quit()` and `QCoreApplication::quit()`. As we can read in the documentation of [`QCoreApplication::quit()`](http://doc.qt.io/qt-5/qcoreapplication.html#quit) it *"tells the application to exit with return code 0 (success)."*. If you want to exit because you discovered file corruption then you may not want to exit with return code zero which means success, so you should call [`QCoreApplication::exit()`](http://doc.qt.io/qt-5/qcoreapplication.html#exit) because you can provide a non-zero returnCode which, by convention, indicates an error. It is important to note that *"if the event loop is not running, this function (QCoreApplication::exit()) does nothing"*, so in that case you should call `exit(EXIT_FAILURE)`.
You can call `qApp->exit();`. I always use that and never had a problem with it. If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.
28,686,367
Here's what i don't understand as you can see my outer loop should only print 5 rows but when i add my inner loop it print 6 rows one blank and 5 0123 what happened here? why did my outer loop print 6 rows? ``` public static void main (String[] args) { int x; int y; for(x=1; x<=5; x++){ System.out.println(); for (y=0; y<4; y++){ System.out.print(y); } } } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28686367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4290376/" ]
``` public static void main (String[] args) { //dont need to declare variables here. they can be declared in loop like below for(int x=0; x<5; x++){ System.out.println(); //this is called before inner loop, printing a blank line for (int y=0; y<4; y++){ System.out.print(y); //print 0-3 } } } ``` If you want to print a blank line after the inner loop place the `System.out.println()` after the inner loop. Stepping through the code with a debugger should have been your first troubleshooting step here. You should also standardise your loop variable checks like I have done above.
The first thing the loop does is output a newline. Any characters printed in the `y` for loop after it appear on the next line. So, this prints 5 newlines, each followed by the `y` characters on the next line. The last iteration prints its characters on the 6th line, which follows the 5th newline character printed. Move `System.out.println()` after the `y` `for` loop so it ends the line properly, after writing the characters.
28,686,367
Here's what i don't understand as you can see my outer loop should only print 5 rows but when i add my inner loop it print 6 rows one blank and 5 0123 what happened here? why did my outer loop print 6 rows? ``` public static void main (String[] args) { int x; int y; for(x=1; x<=5; x++){ System.out.println(); for (y=0; y<4; y++){ System.out.print(y); } } } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28686367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4290376/" ]
``` public static void main (String[] args) { //dont need to declare variables here. they can be declared in loop like below for(int x=0; x<5; x++){ System.out.println(); //this is called before inner loop, printing a blank line for (int y=0; y<4; y++){ System.out.print(y); //print 0-3 } } } ``` If you want to print a blank line after the inner loop place the `System.out.println()` after the inner loop. Stepping through the code with a debugger should have been your first troubleshooting step here. You should also standardise your loop variable checks like I have done above.
You are printing the new line before the actual output. Move `System.out.println();` after the inner for loop: ``` public static void main (String[] args) { int x; int y; for(x=1; x<=5; x++){ for (y=0; y<4; y++){ System.out.print(y); } System.out.println(); } } ``` **Output**: ``` 0123 0123 0123 0123 0123 ```
28,686,367
Here's what i don't understand as you can see my outer loop should only print 5 rows but when i add my inner loop it print 6 rows one blank and 5 0123 what happened here? why did my outer loop print 6 rows? ``` public static void main (String[] args) { int x; int y; for(x=1; x<=5; x++){ System.out.println(); for (y=0; y<4; y++){ System.out.print(y); } } } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28686367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4290376/" ]
``` public static void main (String[] args) { //dont need to declare variables here. they can be declared in loop like below for(int x=0; x<5; x++){ System.out.println(); //this is called before inner loop, printing a blank line for (int y=0; y<4; y++){ System.out.print(y); //print 0-3 } } } ``` If you want to print a blank line after the inner loop place the `System.out.println()` after the inner loop. Stepping through the code with a debugger should have been your first troubleshooting step here. You should also standardise your loop variable checks like I have done above.
Your first instruction in your outer loop is ``` System.out.println(); ``` which means you are moving cursor to next line (leaving first line empty). Then ``` for (y=0; y<4; y++){ System.out.print(y); ``` happens which is responsible for printing `0123` in that line. Then again in next iteration of outer loop cursor is moved to next line and 0123 is printed. Consider moving `System.our.println()` at the end of your outer loop. This way you will let inner loop print `0123` first, before moving cursor to next line.
28,686,367
Here's what i don't understand as you can see my outer loop should only print 5 rows but when i add my inner loop it print 6 rows one blank and 5 0123 what happened here? why did my outer loop print 6 rows? ``` public static void main (String[] args) { int x; int y; for(x=1; x<=5; x++){ System.out.println(); for (y=0; y<4; y++){ System.out.print(y); } } } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28686367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4290376/" ]
``` public static void main (String[] args) { //dont need to declare variables here. they can be declared in loop like below for(int x=0; x<5; x++){ System.out.println(); //this is called before inner loop, printing a blank line for (int y=0; y<4; y++){ System.out.print(y); //print 0-3 } } } ``` If you want to print a blank line after the inner loop place the `System.out.println()` after the inner loop. Stepping through the code with a debugger should have been your first troubleshooting step here. You should also standardise your loop variable checks like I have done above.
your outer loop first prints a blank line, then 0123 on the next try ``` int x; int y; for(x=1; x<=5; x++){ for (y=0; y<4; y++){ System.out.print(y); } System.out.println(); } ```