id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23537100
|
abstract class AnimalProcessor {
public abstract IList<Animal> ProcessResults();
}
Then the concrete examples
class GiraffeProcessor : AnimalProcessor {
public override IList<Animal> ProcessResults() {
return new List<Giraffe>();
}
}
class LionProcessor : AnimalProcessor {
public override IList<Animal> ProcessResults() {
return new List<Lion>();
}
}
The problem is that the concrete classes need to have the same signature to override the ProcessResults() method so they need to return an IList<Animal>, however the ACTUAL data I want to return is an IList<Lion>, IList<Giraffe> etc, but then the calling code has to do
GiraffeProcessor processor = new GiraffeProcessor();
IList<Animal> results = processor.GetResults();
Which does not give me an Ilist which is what I want.
Problems
1) Above code does not compile. The giraffeProcessor has to return a concrete List<Animal>, you can populate it with Giraffe objects but the object type you construct to return has to be List<Animal>. Not ideal.
2) When you return the results, you can only get an IList<Animal>, not IList<Giraffe>. I have tried casting explicitly to IList<Giraffe> with
IList<Giraffe> results = (IList<Giraffe>) processor.GetResults();
which gives a runtime error, presumably because the object returned is NOT an IList<Giraffe>, it is an IList<Animal> which CONTAINS Giraffe objects.
Can anyone suggest what I am doing wrong here with my design as Im a bit stumped as to the best way to accomplish this.
A: How about:
abstract class AnimalProcessor<T> where T : Animal {
public abstract IList<T> ProcessResults();
}
class GiraffeProcessor : AnimalProcessor<Giraffe> {
public override IList<Giraffe> ProcessResults() {
return new List<Giraffe>();
}
}
class LionProcessor : AnimalProcessor<Lion> {
public override IList<Lion> ProcessResults() {
return new List<Lion>();
}
}
A: You could resolve this by declaring AnimalProcessor with a generic type constraint, e.g.
public abstract class AnimalProcessor<T> where T : Animal
{
public abstract IList<T> ProcessResults();
}
If that doesnt work, you could use the LINQ Cast operator, for example:
public class GiraffeProcessor : AnimalProcessor
{
public override IList<Animal> ProcessResults()
{
return new List<Giraffe>().Cast<Animal>();
}
}
Or, store the list internally as Animal but add Giraffe's to it, e.g.
public class GiraffeProcessor : AnimalProcessor
{
private List<Giraffe> _innerList = new List<Giraffe>();
public override IList<Animal> ProcessResults()
{
return new List<Animal>(innerList ); }
}
Best regards,
A: If you are using C# 4.0, you can ask yourself whether the processor should return IEnumerable<T> rather than IList<T>. If the answer is "yes", then you can profit from covariance:
abstract class AnimalProcessor {
public abstract IEnumerable<Animal> ProcessResults();
}
class GiraffeProcessor : AnimalProcessor {
public override IEnumerable<Animal> ProcessResults() {
return new List<Giraffe>();
}
}
class LionProcessor : AnimalProcessor {
public override IEnumerable<Animal> ProcessResults() {
return new List<Lion>();
}
}
You have a couple of advantages here. First, you could implement these as iterator blocks:
class GiraffeProcessor : AnimalProcessor {
public override IEnumerable<Animal> ProcessResults() {
yield break;
}
}
Second, and less trivially, you allow the client code to decide what kind of collection to dump the animals into -- if any. For example, consider that the consumer might want a LinkedList<Animal>:
var animals = new LinkedList<Animal>(animalProcessor.ProcessResults());
Or consider that the client might need only to iterate the sequence:
foreach (var animal in animalProcessor.ProcessResults())
{ /*... do something ...*/ }
In either case, if you were using a ToList() call in ProcessResults, you'd be creating a list for nothing. If the consumer really wants a List<Animal>, that can be accomplished very easily:
var animals = new List<Animal>(animalProcessor.ProcessResults());
Finally, you can also benefit from the generic approach, even if you change the interface type of the method's return value:
abstract class AnimalProcessor<T> where T : Animal {
public abstract IEnumerable<T> ProcessResults();
}
class GiraffeProcessor : AnimalProcessor<Giraffe> {
public override IEnumerable<Giraffe> ProcessResults() {
yield break;
}
}
class LionProcessor : AnimalProcessor<Lion> {
public override IEnumerable<Lion> ProcessResults() {
return Enumerable.Empty<Lion>();
}
}
| |
doc_23537101
|
<object data="games/shadez2" muted="true"></object>
id like to know in html or jquery please so that i can do a click function to mute it.
$(window).click(function(){
if ( event.target.tagName !== "object" ) {
// mute
} else {
// unmute
}
});
A: Did you try muted as a property?
<object data="games/shadez3" muted></object>
or check this post, maybe can help you
Toggling the 'muted' attribute of HTML5 audio
A: Try a boolean to toggle.
var bool = $(target).prop("muted");
| |
doc_23537102
|
I have set the port to 80, server.port=0080
but I am getting errors when init the app.
2019-03-31 12:52 [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol.log(173) - Starting ProtocolHandler ["http-nio-80"]
2019-03-31 12:52 [restartedMain] ERROR o.a.catalina.util.LifecycleBase.log(175) - Failed to start component [Connector[HTTP/1.1-80]]
org.apache.catalina.LifecycleException: Protocol handler start failed
at org.apache.catalina.connector.Connector.startInternal(Connector.java:1008)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.addConnector(StandardService.java:226)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.addPreviouslyRemovedConnectors(TomcatWebServer.java:259)
at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.start(TomcatWebServer.java:197)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.startWebServer(ServletWebServerApplicationContext.java:311)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:164)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at io.icrypts.ICryptsApplication.main(ICryptsApplication.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.net.BindException: Address already in use
A: Ports with numbers 0–1023 are called system or well-known ports.
These are reserved ports and you should not run your applications in that port range.
In your exception you can read:
Caused by: java.net.BindException: Address already in use
It means there's a service already using port 80. You can't bind your application on that port unless you find which service is already bound and kill it.
Again, it's discouraged to use ports 0–1023 for custom apps.
As already suggested, it's better to have an apache or nginx setup on port 80 that forwards the requests to your app (which should run on ports in the range 1024–49151). Example of how to setup reverse-proxy that forwards 80 to 8080 can be found here.
| |
doc_23537103
|
I'm trying to install my web application using a Yocto-Project recipe file.
PR = "r0"
PV = "1.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=d41d8cd98f00b204e9800998ecf8427e"
SRC_URI = "\
file://sources \
file://COPYING \
"
S = "${WORKDIR}"
do_install() {
install -d ${D}${localstatedir}/www
cp -r ${S}/sources/* ${D}${localstatedir}/www/
chown -R www-data:www-data ${D}${localstatedir}/www/
chmod -R 775 ${D}${localstatedir}/www/cgi-bin
}
But /var/www is still owned by root:root and not www-data:www-data like desired.
Question
So how do I chown the /var/www directory recusively to www-data:www-data?
EDIT
I have seen page 9 of the following presentation: https://wiki.yoctoproject.org/wiki/images/e/e6/Custom_Users_Groups_in_Yocto1.1.pdf .
I created this recipe file to mimic this page.
A: First, chown and chmod should work in YP/OE recipes the way you use them.
The problem may be that you've missed a / in your path arguments for the commands. According to the documentation [1] ${D} has no trailing /.
Therefore the following should work:
do_install() {
install -d ${D}/${localstatedir}/www
cp -r ${S}/sources/* ${D}/${localstatedir}/www/
chown -R www-data:www-data ${D}/${localstatedir}/www/
chmod -R 775 ${D}/${localstatedir}/www/cgi-bin
}
(If not please post your bitbake logs)
[1] https://www.yoctoproject.org/docs/latest/mega-manual/mega-manual.html#var-D
A: sudo chown -R wwwdata:wwwdata /var/www/ to make the ownership of the desired folder and its inner folders or files recursively
| |
doc_23537104
|
Concatenate parts of two or more webm video blobs
And tried the sample code here - https://developer.mozilla.org/en-US/docs/Web/API/MediaSource -- (without modifications) in hopes of transforming the blobs into arraybuffers and appending those to a sourcebuffer for the MediaSource WebAPI, but even the sample code wasn't working on my chrome browser for which it is said to be compatible.
The crux of my problem is that I can't combine multiple blob webm clips into one without incorrect playback after the first time it plays. To go straight to the problem please scroll to the line after the first two chunks of code, for background continue reading.
I am designing a web application that allows a presenter to record scenes of him/herself explaining charts and videos.
I am using the MediaRecorder WebAPI to record video on chrome/firefox. (Side question - is there any other way (besides flash) that I can record video/audio via webcam & mic? Because MediaRecorder is not supported on not Chrome/Firefox user agents).
navigator.mediaDevices.getUserMedia(constraints)
.then(gotMedia)
.catch(e => { console.error('getUserMedia() failed: ' + e); });
function gotMedia(stream) {
recording = true;
theStream = stream;
vid.src = URL.createObjectURL(theStream);
try {
recorder = new MediaRecorder(stream);
} catch (e) {
console.error('Exception while creating MediaRecorder: ' + e);
return;
}
theRecorder = recorder;
recorder.ondataavailable =
(event) => {
tempScene.push(event.data);
};
theRecorder.start(100);
}
function finishRecording() {
recording = false;
theRecorder.stop();
theStream.getTracks().forEach(track => { track.stop(); });
while(tempScene[0].size != 1) {
tempScene.splice(0,1);
}
console.log(tempScene);
scenes.push(tempScene);
tempScene = [];
}
The function finishRecording gets called and a scene (an array of blobs of mimetype 'video/webm') gets saved to the scenes array. After it gets saved. The user can then record and save more scenes via this process. He can then view a certain scene using this following chunk of code.
function showScene(sceneNum) {
var sceneBlob = new Blob(scenes[sceneNum], {type: 'video/webm; codecs=vorbis,vp8'});
vid.src = URL.createObjectURL(sceneBlob);
vid.play();
}
In the above code what happens is the blob array for the scene gets turning into one big blob for which a url is created and pointed to by the video's src attribute, so -
[blob, blob, blob] => sceneBlob (an object, not array)
Up until this point everything works fine and dandy. Here is where the issue starts
I try to merge all the scenes into one by combining the blob arrays for each scene into one long blob array. The point of this functionality is so that the user can order the scenes however he/she deems fit and so he can choose not to include a scene. So they aren't necessarily in the same order as they were recorded in, so -
scene 1: [blob-1, blob-1] scene 2: [blob-2, blob-2]
final: [blob-2, blob-2, blob-1, blob-1]
and then I make a blob of the final blob array, so -
final: [blob, blob, blob, blob] => finalBlob
The code is below for merging the scene blob arrays
function mergeScenes() {
scenes[scenes.length] = [];
for(var i = 0; i < scenes.length - 1; i++) {
scenes[scenes.length - 1] = scenes[scenes.length - 1].concat(scenes[i]);
}
mergedScenes = scenes[scenes.length - 1];
console.log(scenes[scenes.length - 1]);
}
This final scene can be viewed by using the showScene function in the second small chunk of code because it is appended as the last scene in the scenes array. When the video is played with the showScene function it plays all the scenes all the way through. However, if I press play on the video after it plays through the first time, it only plays the last scene.
Also, if I download and play the video through my browser, the first time around it plays correctly - the subsequent times, I see the same error.
What am I doing wrong? How can I merge the files into one video containing all the scenes? Thank you very much for your time in reading this and helping me, and please let me know if I need to clarify anything.
I am using a element to display the scenes
A: The file's headers (metadata) should only be appended to the first chunk of data you've got.
You can't make an new video file by just pasting one after the other, they've got a structure.
So how to workaround this ?
If I understood correctly your problem, what you need is to be able to merge all the recorded videos, just like if it were only paused.
Well this can be achieved, thanks to the MediaRecorder.pause() method.
You can keep the stream open, and simply pause the MediaRecorder. At each pause event, you'll be able to generate a new video containing all the frames from the beginning of the recording, until this event.
Here is an external demo because stacksnippets don't works well with gUM...
And if ever you needed to also have shorter videos from between each resume and pause events, you could simply create new MediaRecorders for these smaller parts, while keeping the big one running.
| |
doc_23537105
|
g = require 'gulp'
$ = require('gulp-load-plugins')()
g.task 'vendor:styles', ->
sass_filter = $.filter('*.scss')
less_filter = $.filter('*.less')
g.src(['vendor/font-awesome-4.2.0/scss/font-awesome.scss', 'vendor/bootstrap-3.2.0/less/bootstrap.less'])
.pipe $.sourcemaps.init()
.pipe(sass_filter).pipe($.sass()).pipe(sass_filter.restore())
.pipe(less_filter).pipe($.less(strictMath: true)).pipe(less_filter.restore())
.pipe $.concat('vendor.css')
.pipe $.sourcemaps.write('./maps')
.pipe g.dest('.tmp/styles/vendor')
(This is Coffeescript, but the Javascript is almost identical. I can provide the JS if the above is difficult to parse.)
When running the above, gulp-sourcemaps throws:
gulp-sourcemap-write: source file not found:/Users/pikeas/Documents/code/pypjs/crypto/front/merged/vendor/font-awesome-4.2.0/scss/normalize.less
...(repeated x20, for print.less, carousel.less, etc)
In other words, it's looking for Bootstrap's files in the Font Awesome directory. I've tried using gulp-if instead of gulp-filter, but that also fails with the same error.
What's the right way to write this task?
A: I managed to write a gulpfile.js that takes care of whatever styles my project contains (.scss, .less, .css). All neccessary files are compiled into css, then all is automatically prefixed, minimalized and concated into 1 file. All with their sourcemaps.
const sass = require('gulp-sass');
const less = require('gulp-less');
const gulpIf = require('gulp-if');
const browserSync = require('browser-sync').create();
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const autoprefixer = require('autoprefixer');
const concat = require('gulp-concat');
gulp.task('styles', function() {
return gulp.src(['assets/libs/**/*.less', 'assets/libs/**/*.scss', 'assets/libs/**/*.css', '!assets/libs/all.css'])
.pipe(sourcemaps.init())
.pipe(gulpIf('**/*.less', less().on('error', onErrorLogContinue), gulpIf('**/*.scss', sass().on('error', onErrorLogContinue))))
.pipe(postcss([
autoprefixer({browsers: ['last 2 versions']}),
cssnano(),
]))
.pipe(concat('all.css',{newLine: ''}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('assets/libs'))
.pipe(browserSync.reload({
stream: true
}));
});
| |
doc_23537106
|
lib.langnav >
lib.langnav = HMENU
lib.langnav {
wrap = <ul>|ul
special = language
special.value = 0,1,3
special.normalWhenNoLanguage = 0
1 = TMENU
1 {
noBlur = 1
NO = 1
NO {
additionalParams.cObject = COA
additionalParams.cObject {
5 = TEXT
5.wrap = &L=1
Then I add tx_news controller and action to get translation url for news item on detail page:
10 = TEXT
10.data = GP:tx_news_pi1|news
10.wrap = &tx_news_pi1[news]=|
10.required = 1
20 = TEXT
20.data = GP:tx_news_pi1|controller
20.wrap = &tx_news_pi1[controller]=|
20.required = 1
30 = TEXT
30.data = GP:tx_news_pi1|action
30.wrap = &tx_news_pi1[action]=|
30.required = 1
... and other standard things.
Now when I work with FLUID, I have:
<v:page.languageMenu class="language-menu"
defaultIsoFlag="{settings.config.defaultIsoFlag}"
defaultLanguageLabel="{settings.config.defaultLanguageLabel}"
tagName="ul"
tagNameChildren="li"
linkCurrent="0"
as="languageMenu"
hideNotTranslated="1"
classCurrent="'current'"> ... </v:page.languageMenu>
How can I add the tx_news controller and action (make translation url for news detail pages) in fluid lang.menu?
A: I find just one solution - overwrite default View Helper for added QueryString in url. In my extension (Fluid Theme) typo3conf/ext/huskytheme/Classes/ViewHelpers/Page/LanguageMenuViewHelper.php
<?php
namespace HIT\Huskytheme\ViewHelpers\Page;
class LanguageMenuViewHelper extends \FluidTYPO3\Vhs\ViewHelpers\Page\LanguageMenuViewHelper {
protected function getLanguageUrl($uid) {
$excludedVars = trim((string) $this->arguments['excludeQueryVars']);
$config = array(
'parameter' => $this->getPageUid(),
'returnLast' => 'url',
'additionalParams' => '&L=' . $uid,
'useCacheHash' => $this->arguments['useCHash'],
'addQueryString' => true,
'addQueryString.' => array(
'method' => 'GET',
'exclude' => 'id,L,cHash' . ($excludedVars ? ',' . $excludedVars : '')
)
);
if (TRUE === is_array($this->arguments['configuration'])) {
$config = $this->mergeArrays($config, $this->arguments['configuration']);
}
return $this->cObj->typoLink('', $config);
}
}
and in template
{namespace hit=HIT\Huskytheme\ViewHelpers}
...
<f:section name="LanguageMenu">
{v:variable.typoscript(path: 'plugin.tx_huskytheme.settings') -> v:variable.set(name: 'settings' )}
<v:variable.set name="currentlang" value="{v:page.language(normalWhenNoLanguage: 0)}" />
<div class="lang pull-right">
<hit:page.languageMenu
defaultLanguageLabel="{settings.config.defaultLanguageLabel}"
linkCurrent="0"
as="languageMenu"
hideNotTranslated="1"
classCurrent="'current'"
>
<v:variable.set name="langcount" value="{languageMenu -> f:count()}" />
<f:if condition="{langcount > 1}">
<f:then>
<ul class="navlang">
<f:for each="{languageMenu}" as="item" iteration="iteration">
<f:if condition="{item.current}">
<f:then>
<li class="active">
<span>{item.label}</span>
</li>
</f:then>
<f:else>
<li class="{f:if(condition: iteration.isLast, then: 'last')}">
<a href="{item.url}">{item.label}</a>
</li>
</f:else>
</f:if>
</f:for>
</ul>
</f:then>
</f:if>
</hit:page.languageMenu>
</div>
</f:section>
| |
doc_23537107
|
and on my iphone the line numbers are, for whatever reason, in a smaller font size:
I haven't done anything to edit any sort of font sizes anywhere on my website. It's all default sizes. If I manually set the font size, say to 12px, it is still lined up on my desktop browser, and still smaller on my mobile browser.
The code block is laid out as a table with two cells. The left cell contains a 1 column table, each row contains a number. The right cell contains a 1 column table, each row contains a line of code.
Any idea why the font is shrunk on the mobile browser?
EDIT: LINK: http://grantslatton.com/posts/blog/2013-08-16/sudoku_solver/
EDIT2: It renders correctly on windows phones and android phones.
SOLUTION: Turns out mobile Safari decides to change text size for you! I saw a solution on this page that worked :Fix font size issue on Mobile Safari (iPhone) where text is rendered inconsistently and some fonts are larger than others?
I put -webkit-text-size-adjust: 100% in the body { } section of my CSS to prevent mobile safari from messing with my text size.
A: Turns out mobile Safari decides to change text size for you! I saw a solution on this page that worked:
*
*Fix font size issue on Mobile Safari (iPhone) where text is rendered inconsistently and some fonts are larger than others?
I put the following in my CSS to prevent mobile safari from messing with my text size.
body {
-webkit-text-size-adjust: 100%;
}
| |
doc_23537108
|
I'm working on a code, which does fetch categories together with other elements from a database (php & mysql).
These elements/nodes are all in a "<label> ... </label>" for a radio button.
If a user clicks on one of these labels for a radio button, the category name and an img, which are also in the label, should how up ALSO in a other "<div id="selection"> ... </div>".
What does work:
By clicking on a radiobutton/label, I already can fetch the radioButton value (in my case the value must be the the category id).
What doesn't work:
I cant fetch the other elements in this label and display it ALSO in a other span
VERY IMPORTANT!: The content in the labels getting fetched from a database, so it is dynamically!
Here is a simple version of my code without php elements, but the output should be kinda the same.
function check() {
var radioBttn = document.querySelectorAll("input[name = 'pet']");
var countRadioBttn = radioBttn.length;
for (i = 0; i < countRadioBttn; i++) {
if (radioBttn[i].checked) {
selection.innerHTML = "You selected a/n " + radioBttn[i].value + ",<br>good choice!";
}
}
}
*{margin: 0; padding: 0;font-family: arial; font-family: ubuntu; -webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none; user-select: none;}
b{color: dodgerBlue;}
body{background-color: rgba(50,50,50);}
#option{width: 250px; height: 100px; background-color: rgba(255,255,255,.3); margin: 10px; padding: 10px; color: rgba(255,255,255,.9);}
#selection{width: 250px; height: 55px; background-color: rgba(100,100,100,.3); margin: 10px; padding: 10px; color: lightgreen;}
<div id="option">
<b>Option Box</b>
<br>
<label>
<input onclick="check()" type="radio" name="pet" class="rb_category" value="id:1">
<span>Cat</span>
<img src=""></img>
</label>
<br>
<label>
<input onclick="check()" type="radio" name="pet" class="rb_category" value="id:2">
<span>Dog</span>
<img src=""></img>
</label>
<br>
<label>
<input onclick="check()" type="radio" name="pet" class="rb_category" value="id:3">
<span>Hamster</span>
<img src=""></img>
</label>
<br>
<label>
<input onclick="check()" type="radio" name="pet" class="rb_category" value="id:4">
<span>Mammoth</span>
<img src=""></img>
</label>
</div>
<div id="selection">
No selection yet
</div>
A: Do you mean this?
var rads = document.querySelectorAll("input[name=pet]");
for (var i = 0; i < rads.length; i++) {
rads[i].addEventListener("click", function() {
var parentLabel = this.closest("label");
document.getElementById("selection").innerHTML =
"You selected a/n " + this.value + ",<br>good choice!" +
"<span>" + parentLabel.querySelector("span").innerHTML + "</span>" +
"<img src='" + parentLabel.querySelector("img").src + "'/>";
});
};
*{margin: 0; padding: 0;font-family: arial; font-family: ubuntu; -webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none; user-select: none;}
b{color: dodgerBlue;}
body{background-color: rgba(50,50,50);}
#option{width: 250px; height: 100px; background-color: rgba(255,255,255,.3); margin: 10px; padding: 10px; color: rgba(255,255,255,.9);}
#selection{ width: 250px; height: 55px; background-color: rgba(100,100,100,.3); margin: 10px; padding: 10px; color: lightgreen;}
label>img { height:25% }
<div id="option">
<b>Option Box</b>
<br>
<label>
<input type="radio" name="pet" class="rb_category" value="id:1">
<span>Cat</span>
<img src="https://lorempixel.com/output/cats-q-c-200-200-5.jpg" />
</label>
<br>
<label>
<input type="radio" name="pet" class="rb_category" value="id:2">
<span>Dog</span>
<img src="https://lorempixel.com/output/animals-q-c-200-200-8.jpg" />
</label>
<br>
<label>
<input type="radio" name="pet" class="rb_category" value="id:3">
<span>Rhino</span>
<img src="https://lorempixel.com/output/animals-q-c-200-200-1.jpg" />
</label>
<br>
<label>
<input type="radio" name="pet" class="rb_category" value="id:4">
<span>Tiger</span>
<img src="https://lorempixel.com/output/animals-q-c-200-200-3.jpg" />
</label>
</div>
<br style="clear:both" />
<div id="selection">
No selection yet
</div>
| |
doc_23537109
|
The thing is, yaourt is unable to find a valid mirror to download from
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from ftp.swin.edu.au : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from ftp.acc.umu.se : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirror.neuf.no : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirrors.ustc.edu.cn : The requested URL returned error: 404
error: failed retrieving file 'yaml-cpp-0.6.1-3-x86_64.pkg.tar.xz' from mirror.23media.de : The requested URL returned error: 404
(4/4) checking keys in keyring [##############################] 100%
(4/4) checking package integrity [##############################] 100%
error: yaml-cpp: signature from "Levente Polyak (anthraxx) <levente@leventepolyak.net>" is invalid
I tried building the lib manually from source and putting it in /usr/lib but it doesn't work either.
What can I do here ?
Thanks
A: You must update your Arch Linux before installing any new package.
The following command are fine:
*
*pacman -Syu followed by pacman -S yaml-cpp
*pacman -Syu yaml-cpp
You must not do this (it may break your system):
*
*pacman -Sy followed by pacman -S yaml-cpp
*pacman -Sy yaml-cpp
| |
doc_23537110
|
Sheet1 got updated each 5 minutes, if there is any possibility to update Sheet2 each 5 minute that will be really great.
Example:
Sheet1
Sheet1
Sheet2Sheet2
NB: My VBA or Macro knowledge is very basic. If I’m not asking too much, explanation to apply the solutions will be great.
Using office 365 latest version
A: If you are having a hard time finding a place to start, you could try this Worksheet_Change event macro for Sheet1.
Option Explicit
Private dALL As Double
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Sum(Target.Parent.UsedRange.Cells) <> dALL Then
dALL = Application.Sum(Target.Parent.UsedRange.Cells)
On Error GoTo bm_Safe_Exit
'suspend events so nothing on Sheet2 gets triggered
Application.EnableEvents = False
Dim a As Long, i As Long, j As Long, aVALs As Variant
aVALs = Target.Parent.UsedRange.Cells.Value2
For i = LBound(aVALs, 1) To UBound(aVALs, 1)
For j = LBound(aVALs, 2) To UBound(aVALs, 2) - 1
If Not CBool(Len(aVALs(i, j))) Then
For a = j + 1 To UBound(aVALs, 2)
If CBool(Len(aVALs(i, a))) Then
aVALs(i, j) = aVALs(i, a)
aVALs(i, a) = vbNullString
Exit For
End If
Next a
End If
Next j
Next i
With ThisWorkbook.Worksheets("Sheet2")
.UsedRange.Clear
.Cells(1, 1).Resize(UBound(aVALs, 1), UBound(aVALs, 2)) = aVALs
End With
End If
bm_Safe_Exit:
Application.EnableEvents = True
End Sub
| |
doc_23537111
|
Hi all, can we implement strategy in cluster like openlayer 2? I don't find any example to cluster with strategy in openlayer3. I want to cluster only a feature which have the same class like openlayer 2 do in example : http://dev.openlayers.org/examples/strategy-cluster-extended.html .. How to code it in openlayer 3? thx
| |
doc_23537112
|
I was trying following code but the listener doesn't seem to trigger, although the OP value actually changed:
val appOpsManager: AppOpsManager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
appOpsManager.startWatchingMode("android:post_notification", context.packageName) { op, _ ->
Log.d("foo", "$op value changed")
}
| |
doc_23537113
|
For brevity I'm only posting the relevant code here.
world.rb
class World < ApplicationRecord
belongs_to :user
has_many :states
end
state.rb
class State < ApplicationRecord
belongs_to :world
belongs_to :user
end
states_controller.rb
class StatesController < ApplicationController
before_action :set_state, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@states = State.all
end
def new
@world = World.find(params[:id])
@state = @world.states.build
end
def create
@world = World.find(params[:id])
@state = @world.states.build(state_params)
@state.user = current_user
respond_to do |format|
if @state.save
format.html { redirect_to @state, notice: 'State was successfully created.' }
else
format.html { render :new }
end
end
end
private
def set_state
@state = State.find(params[:id])
end
def state_params
params.require(:state).permit(:name, :summary, :history, :population, :inception, :life_expectancy, :land_mass,
:climate, :industry, :education, :mythology, :law, :culture, :world_id, :user_id)
end
end
The link to the new state form in worlds/show.html.erb:
<%= link_to 'New State', new_world_state_path(@world) %>
routes.rb
Rails.application.routes.draw do
resources :states
resources :worlds
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
root to: "home#index"
resources :users
resources :worlds do
resources :states
end
end
states/_form.html.erb
<div class="form">
<%= form_for(state) do |f| %>
<% if state.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(world.errors.count, "error") %> prohibited this state from being saved:</h2>
<ul>
<% state.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :name, placeholder: 'Name' %><br />
<fieldset>
<legend>Basic Info</legend>
<%= f.text_area :summary, placeholder: 'Summary About', rows: 6 %><br />
<%= f.text_area :history, placeholder: 'History', rows: 6 %><br />
<%= f.text_area :climate, placeholder: 'Climate', rows: 3 %><br />
<%= f.text_area :industry, placeholder: 'Industry', rows: 3 %><br />
<%= f.text_area :education, placeholder: 'Education', rows: 3 %><br />
<%= f.text_area :culture, placeholder: 'Culture', rows: 3 %><br />
<%= f.text_area :law, placeholder: 'Legal System, Crime & Punishment', rows: 3 %><br />
<%= f.text_area :mythology, placeholder: 'Mythology', rows: 3 %><br />
</fieldset>
<fieldset>
<legend>Quick Stats</legend>
<%= f.text_field :inception, placeholder: 'Inception' %><br />
<%= f.text_field :population, placeholder: 'Population' %><br />
<%= f.text_field :life_expectancy, placeholder: 'Ave. Life Expectance' %><br />
<%= f.text_field :land_mass, placeholder: 'Land Mass' %><br />
</fieldset>
<p><%= f.submit %></p>
<% end %>
</div>
rails console results when clicking 'New State' link
Started GET "/worlds/1/states/new" for 70.196.17.76 at 2017-05-22 13:43:47 +0000
Cannot render console from 70.196.17.76! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StatesController#new as HTML
Parameters: {"world_id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
World Load (0.1ms) SELECT "worlds".* FROM "worlds" WHERE "worlds"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.4ms)
ActiveRecord::RecordNotFound (Couldn't find World with 'id'=):
app/controllers/states_controller.rb:13:in `new'
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (4.7ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.6ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms)
A: Modify your link_to helper to specify and tell to Rails what's the parameter you're sending through it:
From:
<%= link_to 'New State', new_world_state_path(@world) %>
To:
<%= link_to 'New State', new_world_state_path(id: @world) %>
id because you're trying to find the World through :id as param.
Try also changing the param that's being received within the controller where you're setting the @world variable:
def new
@world = World.find(params[:world_id])
...
end
In the show.html.erb:
<%= link_to 'New World', new_world_state_path(world_id: @world) %>
Update: What we made:
In the app/views/worlds/show.html.erb to change the way the param was being setted:
From:
<%= link_to 'New Nation', new_world_state_path(world_id: @world_id) %> # @world_id wasn't defined
To:
<%= link_to 'New Nation', new_world_state_path(world_id: @world.id) %>
In the /app/views/states/_form.html.erb to add the world_id as a hidden_field:
<%= f.hidden_field :world_id, value: @world.id %>
And then in app/controllers/states_controller.rb to change the way the params were being received:
def new
@world = World.find(params[:world_id])
@state = @world.states.build
end
def create
@world = World.find(params[:state][:world_id])
...
A: The world_id while it is passed to the :new action, it may not be passed back on the form to the create action.
Your state_params are expecting a :world_id to be sent back so add a hidden field to send it back on the form.
new.html.erb
<%= f.hidden_field :world_id, :value => @world.id %>
and update the create action to
@world = World.find(params[:world_id])
| |
doc_23537114
|
I am trying to merge multiple excel files into single one using below code.
But it is giving me error like below (no additional info in innerexception) at sheet.Copy command.
Unable to get the Copy property of the Worksheet class
Code...
private void MergeXlsxFiles(string destXlsxFileName, params string[] sourceXlsxFileNames)
{
Application excelApp = null;
Workbook destWorkBook = null;
var temppathForTarget = Path.Combine(Directory.GetCurrentDirectory() , Guid.NewGuid() + ".xls");
if (File.Exists(temppathForTarget))
File.Delete(temppathForTarget);
try
{
excelApp = new Application
{
DisplayAlerts = false,
SheetsInNewWorkbook = 3
};
destWorkBook = excelApp.Workbooks.Add();
destWorkBook.SaveAs(temppathForTarget);
foreach (var sourceXlsxFile in sourceXlsxFileNames)
{
var file = Path.Combine(Directory.GetCurrentDirectory(), sourceXlsxFile);
var sourceWorkBook = excelApp.Workbooks.Open(file);
foreach (Worksheet ws in sourceWorkBook.Worksheets)
{
var wSheet = destWorkBook.Worksheets[destWorkBook.Worksheets.Count];
ws.Copy(wSheet);
destWorkBook.Worksheets[destWorkBook.Worksheets.Count].Name =
ws.Name;
}
sourceWorkBook.Close(XlSaveAction.xlDoNotSaveChanges);
}
destWorkBook.Sheets[1].Delete();
destWorkBook.SaveAs(destXlsxFileName);
}
catch (Exception ex)
{
}
finally
{
if (destWorkBook != null)
destWorkBook.Close(XlSaveAction.xlSaveChanges);
if (excelApp != null)
excelApp.Quit();
}
}
Does anyone knows what is wrong with this code.
I am referring Microsoft.Office.Interop.Excel dll from GAC with version 15.0.0.0 and I have MSOffice 2013 installed on my machine.
A: In general, when I test the code in the question, it runs into problems with data typing. Excel is "picky" about data typing - it's often necessary to explicitly cast a type. The following foreach works for me: Notice the (Excel.Worksheet) casts. With those I ran into no problems with the Copy (or the Name) method (property).
I also ran into "oddities" assigning sheet names. The logic used in the code in the question is not clear, so on the assumption the new sheets should be added after the default three empty sheets, I altered ws.Copy to put them at the end.
foreach (Excel.Worksheet ws in sourceWorkBook.Worksheets)
{
var wSheet = (Excel.Worksheet) destWorkBook.Worksheets[destWorkBook.Worksheets.Count];
ws.Copy(missing, wSheet);
Excel.Worksheet wNewSheet = (Excel.Worksheet)destWorkBook.Worksheets[destWorkBook.Worksheets.Count];
wNewSheet.Name = "New" + ws.Name;
}
| |
doc_23537115
|
But i have 2 queries :
1.How can i check that which one is used 'ng-view' ($routeProvider) or 'ui-view' ($stateProvider) by user in his/her application ??
2.I want to get module name which he/she has defined in main app.js so by using that default(already defined) module name i can apply my custom angular functionality on that module.
Thanks
| |
doc_23537116
|
I realized that just this morning, they had added contentEditable=false properties to each of their <div> and parts of my existing code was no longer working. Now my first reaction was just "ok, there must be a way using javascript to overwrite this attribute to make it 'true' and then I can re-execute my manipulations." But then before I started digging into the fix, I started wondering about the broader question here - should I be doing that for this site?
Understand the way I phrased that is very ambiguous and at this point it's more just a personally moral? gray area? question, but does anyone with more experience have any opinions as to whether I should start using different URLs for something like this?
| |
doc_23537117
|
*
*phone: Windows, url: app://url1
*phone: iPhone, url: app://url2, redirectURL: https://itunes.apple.com/app/123456
*phone: Android, url: app://url3, redirectURL: https://www.google.com
I've attached my code below. It works as expected for the Windows phone. However for the iPhone, if the app isn't installed, a message pops up "Safari can not open the page." before being redirected to the redirectURL. Is there any way to avoid this or a better method to implement this?
My code so far:
<head>
<script type="text/javascript">
function myHref() {
if (navigator.userAgent.match(/Windows Phone [1-8]/i)) {
location.href = 'app://url1';
}
if (navigator.userAgent.match(/iPad/i) || (navigator.userAgent.match(/iPhone/i))) {
document.location = 'app://url2';
setTimeout(function () {
if (confirm('You do not seem to have the app installed. Do you want to go download it now?')) {
location.href = 'https://itunes.apple.com/app/123456';
}
}, 300);
}
if (navigator.userAgent.match(/Android/i)) {
location.href = "app://url3"
}
if (navigator.userAgent.match(/BlackBerry/i)) {
//code for blackberry here
}
if (navigator.userAgent.match(/webOS/i)) {
//code for webOS here
}
}
</script>
</head>
<body>
<p>
<a href="#" onclick="myHref()" style="font-size:20px;">link</a>
</p>
</body>
| |
doc_23537118
|
I'm building an API Rest in Symfony 2.7 with JMSSerializerBundle.
I got a Customer model with address properties separated: (line1, line2, city, postal_code, state, country_code), when i'm sending the response, i'm doing this:
{
"company_name": "Foograde",
"first_name": "Federico",
"last_name": "Balderas Mata",
"email": "federico.balderas@foograde.com.mx",
"address": {
"line1": "Gral. Ortega #223D",
"city": "Celaya",
"state": "Guanajuato",
"postal_code": "38010",
"country_code": "MX"
}}
Like you see, i'm sending parameter on an address object:
/**
* Get address
* @VirtualProperty
* @return array
* @SerializedName("address")
*/
public function getAddress()
{
return array(
'line1' => $this->line1,
'line2' => $this->line2,
'line2' => $this->line3,
'city' => $this->city,
'state' => $this->state,
'postal_code' => $this->postal_code,
'country_code' => $this->country_code
);
}
But now what i'm trying to do is get the request in the same form, with an address object and separate the properties to insert them in the database.
Any idea?
A: I think you should move address from Customer to its own entity, So, there would be Address entity and Customer entity with unidirectional manyToMany address field. By this way you can create a form for address, embed it to customer form, and you can also get validation ready for you..
A: as the docs from JMSSerializer state:
@VirtualProperty
This annotation can be defined on a method to indicate that the data returned by the method should appear like a property of the object.
Note: This only works for serialization and is completely ignored during deserialization.
As thexurshid29 states, it is best to move the "Address" to a seperate entity, you can have the json output remain exactly the same as before, by using serializationgroups (to include/eclude the fields you want)
This way, you can also deserialize this exact same data, back into its appropriate entities, by simply using the JMSSerializer, to deserialize the json data.
| |
doc_23537119
|
when i build in FROM php:7.3-fpm-alpine it work but i want to use php 8 it not work this error i got
ERROR [ 4/10] RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
executor failed running [/bin/sh -c docker-php-ext-install pdo_mysql mbstring zip exif pcntl]: exit code: 1
this my dockerfile
FROM php:8.0.7-fpm-alpine3.13 AS php
# FROM php:8.0.7-fpm-alpine not work
# FROM php:8.0.7-fpm-alpine3.13 not work
# FROM php:7.4-fpm not work
# FROM php:7.3-fpm work
WORKDIR /var/www
RUN apk update && apk add \
build-base \
freetype-dev \
libjpeg-turbo-dev \
libpng-dev \
libzip-dev \
zip \
jpegoptim optipng pngquant gifsicle \
vim \
unzip \
git \
curl
RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
RUN docker-php-ext-configure gd --with-gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-png-dir=/usr/include/
RUN docker-php-ext-install gd
# Install Extension
RUN apk add autoconf && pecl install -o -f redis \
&& rm -rf /tmp/pear \
&& docker-php-ext-enable redis && apk del autoconf
COPY ./config/php/local.ini /usr/local/etc/php/conf.d/local.ini
RUN addgroup -g 1000 -S www && \
adduser -u 1000 -S www -G www
USER www
COPY --chown=www:www . /var/www
EXPOSE 9000
any one please advise me
| |
doc_23537120
|
I have tried this code with no success:
data_file = pd.read_excel('C:..scrapingData.xlsx', sheet_name="Articles Scraping")
data_file_2 = data_file[data_file["Link"].str.contains("radiondekeluka")]
My new dataframe doesn't contain any observation. What am I missing? Thanks!
enter image description here
| |
doc_23537121
|
I have a string like $string = "this is my string";
The output should be "thisismystring"
How can I do that?
A: If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).
A: If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
A: str_replace will do the trick thusly
$new_str = str_replace(' ', '', $old_str);
A: Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
| |
doc_23537122
|
<?php
try
{
$stmt = $conn->prepare("SELECT * FROM registration");
$stmt->errorInfo();
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Autoid'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
if($_SESSION['sesuname'])
{
echo "<td>Its You ". $_SESSION['sesuname'] ."</td>";
}
else if(!$_SESSION['sesuname'])
{
echo '<td>Follow</td>';
}
echo "</tr>";
}
} catch (PDOException $e) {
'Database Error : ' .$e->getMessage();
}
?>
I'm trying to show the Follow option and loggedin username in final td. But, this coding always shows the loggedin username in all rows. I don't know where i made mistake?
A: I guess your condition should be,
if($_SESSION['sesuname'] == $row['Name'])
{
echo "<td>Its You ". $_SESSION['sesuname'] ."</td>";
}
else
{
echo '<td>Follow</td>';
}
A: I think you want to check each row to see if the name matches the name stored in the session?
So you want if($_SESSION['sesuname'] == $row['Name'])? And any condition on the else clause is spurious.
A: For every row you are only testing your session variable; and then printing it.
A: check with isset()
if(isset($_SESSION['sesuname'])&&$_SESSION['sesuname']==$row['Name'])
| |
doc_23537123
|
$action=$_REQUEST['action'];
if($action=='addSellRent'){
if(array_key_exists('file1',$_FILES)){
$result[]=uploadSellImage($_FILES);
}
}
function uploadSellImage($_FILES){
print_r($_FILES);exit;
}
Here inside trying to print the file but its showing blank. Here I need to pass the file data to the uploadSellImage function and try to doing some operation there. Please help me.
A: try this
function uploadSellImage($upload){
echo "<pre>"; print_r($upload);die;
}
| |
doc_23537124
|
package com.jama.lyricist.ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
public class AdvancedTabbedPaneUI extends BasicTabbedPaneUI{
@Override
protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) {
Color savedColor = g.getColor();
g.setColor(new Color(238,238,238));
g.fillRect(rects[tabIndex].x, rects[tabIndex].y,
rects[tabIndex].width, rects[tabIndex].height);
g.setColor(new Color(153, 153, 153));
g.drawRect(rects[tabIndex].x, rects[tabIndex].y,
rects[tabIndex].width, rects[tabIndex].height);
g.setColor(new Color(102,102,102));
g.setColor(savedColor);
}
private final Insets borderInsets = new Insets(0, 0, 0, 0);
@Override
protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
}
@Override
protected Insets getContentBorderInsets(int tabPlacement) {
return borderInsets;
}
@Override
protected void paintContentBorderTopEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
super.paintContentBorderTopEdge(g, tabPlacement, -1, x, y, w, h);
}
}
It outputs this: Output
A: By overriding the paintTab() method, you're preventing the title from being painted by the base class.
You have one of two options:
*
*Override paintTabBackground() and paintTabBorder() instead of overriding the paintTab() method, letting the base class paint the title
*Paint the title yourself in your paintTab() method
| |
doc_23537125
|
trait Set[A <: Ordered[A]] {
def incl(x: A): Set[A]
def contains(x: A): Boolean
}
and
trait Set[A <% Ordered[A]] ...
further on page 55. He also says that the <:/<% is the only change required for trait Set in order to demonstrate the type bounding possibilities.
However, when I repeat the example with my own code, the IDE complains that traits may NOT have view bounds, only type bounds. Changing the trait keyword to abstract class or changing the view bound to type bound helps. Is this a mistake in the book?
A: Let's use our powerful tool called the REPL to understand what is going on:
scala> trait Example[A<:Ordered[A]] { def contains(x:A):Boolean }
defined trait Example
scala> class Example2[A<%Ordered[A]]( val a:A) { def isLower(otherA:A):Boolean = a< otherA }
defined class Example2
scala> :javap Example
Compiled from "<console>"
public interface Example{
public abstract boolean contains(scala.math.Ordered);
}
scala> :javap Example2
Compiled from "<console>"
public class Example2 extends java.lang.Object implements scala.ScalaObject{
public java.lang.Object a();
public boolean isLower(java.lang.Object);
public Example2(java.lang.Object, scala.Function1);
}
As you can see , the view bound becomes the second argument of the Example2 constructor. Since a trait does not have a constructor, clearly it is not possible to provide a view bound.
Why this has been possible in previous releases is to me a mistery (maybe an additional Function1 val was created inside the trait and filled by the compiler?)
Concerning your question about Scala evolution, it is mature and powerful. You can expect changes between major releases (2.8, 2.9, 2.10) but I would not consider scala not mature enough for this. There is, however, always space for improvement
| |
doc_23537126
|
The problem is that on startup I get a ClassNotFoundException for my session manager.
I have tried adding my jar to the lib folder and modifying the config.ini to make my jar load up on startup but that did not help
In this scenario what should I do to ensure that my class is found on startup.
A: You can use the Virgo Shell Commands as described in this blog to analyze class loading issues. You can lists all bundles that can load a class for example. Have a look at the Virgo FAQ How to add imports to 3rd party bundles if need be.
A: Enabling class loader debugging helped,
In configuration/config.ini add the following property
osgi.debug=configuration/equinox-debug.properties
In configuration/equinox-debug.properties add the following properties,
org.eclipse.osgi/debug=true
org.eclipse.osgi/debug/loader=true
Now when you restart the container it prints out the BundleClassLoader which is attempting to load your class. I wanted my bundle to a be added as a fragment to the bundle which was loading this class, so once I figured out which bundle was loading the class I simply used that as the fragment host.
| |
doc_23537127
|
using System.Windows.Forms;
What I most need from the Windows.Forms namespace is a WebBrowser control. Any ideas on how to get this working? Thank you.
A: Add a reference to System.Windows.Forms in the project.
Here is how you do it: (copied from the user below - thankyou!):
you need to add reference to it's assembly
right click your project node in solutions explorer and
choose AddReference --> .Net -->System.Windows.Forms
Just make sure that you don't call MessageBox from your service. It is not a smart thing to do. (Yes, I have blocked services that way)
A: you need to add reference to it's assembly
right click your project node in solutions explorer and
choose AddReference --> .Net -->System.Windows.Forms
A: I'm not sure how you expect to use a WebBrowser control in a Windows service, a type of application that inherently does not have a user interface. What you probably need is a reference to the System.Windows.Forms library. If you right click on your project and go to Add Reference..., there will be a whole list of reference. Scroll down and select System.Windows.Forms and clikc OK and you should be good to go.
| |
doc_23537128
|
Compiler Error Message: CS7036: There is no argument given that corresponds to the required formal parameter 'myService' of 'MyUserControl.MyUserControl(IMyService)'
Source Error:
Line 165:
Line 166: [System.Diagnostics.DebuggerNonUserCodeAttribute()]
Line 167: public calls_new_mycontrol_ascx() {
Line 168: ((global::MyCompany.Web.MyUserControl)(this)).AppRelativeVirtualPath = "~/MyUserControl.ascx";
Line 169: if ((global::ASP.calls_new_mycontrol_ascx.@__initialized == false)) {
I've forked the sample and it works with a user control. I can't seem to figure out what is different between the two projects.
*
*I've upgraded my project to 4.8 Framework
*I've added a nuget reference to Microsoft.CodeDom.Providers.DotNetCompilerPlatform 2.0.1
A: I met the same problem and my solution was to add a default constructor in my class
In your case
public MyUserControl(){}
would solve the problem.
A: In web.config add <httpRuntime targetFramework="4.7.2"/>.
<configuration>
<system.web>
<!--Use Dependency Injection In WebForms Application-->
<httpRuntime targetFramework="4.7.2"/>
</system.web>
</configuration>
Source: ASP.NET Blog Post on DI in Webforms
| |
doc_23537129
|
this is my datagrid
'use strict';
var React = require('react')
var DataGrid = require('react-datagrid')
var columns = [
{ name: 'id', title: '#', width: 50 },
{ name: 'business_id', flex: 1 },
{ name: 'lastName' },
{ name: 'city', flex: 1 },
{ name: 'country', flex: 1 },
{ name: 'email', width: 200 }
]
var App = React.createClass({
initData: function(documents){
if(documents){
return documents;
} else {
console.log('documents: '+ this.props.documents);
return this.props.documents;
}
},
getInitialState: function(){
return {
dataSource: [],
}
},
componentDidMount() {
this.setState({
dataSource: this.initData()
})
},
render: function(){
console.log('this.props.documents: '+ this.props.documents)
return <DataGrid
idProperty='id'
dataSource={this.initData()}
columns={columns}
style={{height: 400}}
onFilter={this.handleFilter}
liveFilter={true} //to apply the filter while typing
/>
},
handleFilter: function(column, value, allFilterValues){
//reset data to original data-array
var data = this.initData()
//go over all filters and apply them
Object.keys(allFilterValues).forEach(function(name){
var columnFilter = (allFilterValues[name] + '').toUpperCase()
if (columnFilter == ''){
return
}
data = data.filter(function(item){
if ((item[name] + '').toUpperCase().indexOf(columnFilter) === 0){
return true
}
})
})
this.initData(data)
this.setState({})
}
})
the first console log returns nothind
documents:
the console log in the render() returns data
this.props.documents:[object Object],[object Object],[object Object],[object Object],[object Object]
and this how I call my datagrid component from my home component
<DocumentReactNewGrid documents={this.state.documents}/>
A: Make the dataSource as a state. On filter, set the new data to the state. This will re-render the component with the new data.
'use strict';
var React = require('react')
var DataGrid = require('react-datagrid')
var columns = [
{ name: 'id', title: '#', width: 50 },
{ name: 'business_id', flex: 1 },
{ name: 'lastName' },
{ name: 'city', flex: 1 },
{ name: 'country', flex: 1 },
{ name: 'email', width: 200 }
]
var App = React.createClass({
initData: function(documents){
if(documents){
return documents;
} else {
return this.props.documents;
}
},
getInitialState: function(){
return {
dataSource: this.initData(),
}
},
componentWillReceiveProps(nextProps) {
this.setState({
dataSource: nextProps.documents,
})
},
render: function(){
return <DataGrid
idProperty='id'
dataSource={this.state.dataSource}
columns={columns}
style={{height: 400}}
onFilter={this.handleFilter}
liveFilter={true} //to apply the filter while typing
/>
},
handleFilter: function(column, value, allFilterValues){
//reset data to original data-array
var data = this.initData()
//go over all filters and apply them
Object.keys(allFilterValues).forEach(function(name){
var columnFilter = (allFilterValues[name] + '').toUpperCase()
if (columnFilter == ''){
return
}
data = data.filter(function(item){
if ((item[name] + '').toUpperCase().indexOf(columnFilter) === 0){
return true
}
})
})
this.setState({
dataSource: data
})
}
})
Hope this helps!
| |
doc_23537130
|
{
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self;
[mailCont setSubject:@"yo!"];
[mailCont setToRecipients:@[@"address@example.com"]];
[mailCont setMessageBody:@"Don't ever want to give you up" isHTML:YES];
[self presentViewController:mailCont animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
//handle any error
[controller dismissViewControllerAnimated:YES completion:nil];
}
I have a code like this which work. But I do not want to open MFMailComposer. I just want to send mail directly on the click of button.This code open MFMailComposer.I don't want to open it.Please Help.
A: Check link below :--
SKPSMTPMessage
This one is for sending mails in background with out any user interaction...
Use Code Below to use this library...
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc]init];
emailMessage.fromEmail = @"SENDER MAIL ID";
emailMessage.toEmail = @"RECEIPENT MAIL ID";
emailMessage.relayHost = @"smtp.gmail.com";
emailMessage.requiresAuth = YES;
YOUR LOGIN CREDENTIALS OF YOUR EMAIL TO SEND EMAIL
emailMessage.login = @"YOUR EMAIL ID";
emailMessage.pass = @"PASSWORD OF YOUR MAIL ACCOUNT";
emailMessage.subject = @"YOUR SUBJECT TO SEND MAIL";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self;
NSString *password = @"PASSWORD";
NSString *message = [NSString stringWithFormat:@"Your password is : %@", password];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, @"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[emailMessage setParts:[NSArray arrayWithObjects:plainPart, nil]];
[emailMessage send];
Hope this help you...
you have to give login email and password of your/company email from which you want to send mail ...
emailMessage.login = @"YOUR EMAIL ID";
emailMessage.pass = @"PASSWORD OF YOUR MAIL ACCOUNT";
| |
doc_23537131
|
public class MyDto implements Serializable {
private UUID uuid;
private Long sequential;
// Constructor taking properties as parameters
// Geters and setters
}
And my code works great when I try to construct in CriteriaBuilder like this:
// Assuming my constructor in MyDto take only UUID parameter
query.select(builder.construct(MyDto.class,
root.get(MyDto_.uuid)));
But when I try to add the 'sequential' parameter in the constructor of my Dto, and change my select to retrieve the value from a db function as bellow:
// Assuming my constructor in MyDto take both UUID and Long parameters
query.select(builder.construct(MyDto.class,
builder.function("nextval", Long.class, builder.literal("my_seq")),
root.get(MyDto_.uuid)));
hibernate throw a exception:
java.lang.NullPointerException
at org.hibernate.hql.internal.NameGenerator.generateColumnNames(NameGenerator.java:27)
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.generateColumnNames(SessionFactoryHelper.java:418)
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeColumnNames(SelectClause.java:269)
at org.hibernate.hql.internal.ast.tree.SelectClause.finishInitialization(SelectClause.java:259)
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:254)
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:545)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:654)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3282)
at org.hibernate.query.criteria.internal.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:318)
at org.hibernate.query.criteria.internal.compile.CriteriaCompiler.compile(CriteriaCompiler.java:127)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:3575)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:204)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
at org.jboss.weld.proxies.AutoCloseable$EntityManager$HibernateEntityManager$QueryProducer$Serializable$Session$SharedSessionContract$1645305853$Proxy$_$$_WeldClientProxy.createQuery(Unknown Source)
This is an example of what I'm trying to do, and here I see the function being used in a where, but my need is to use in the constructor of CriteriaBuilder.
I have this working in the old way SELECT NEW MyDto(...) but Im strugling with CriteriaBuilder.
A: For everyone facing the same problem, the answer is: register your function.
As mentioned in this article,
When executing an entity query (e.g. JPQL, HQL or Criteria API), you can use any SQL function without having to register it as long as the function is passed directly to the WHERE clause of the underlying SQL statement. However, if the SQL function is used in the SELECT clause, and Hibernate has not registered the SQL function (be it a database-specific or user-defined function), you will have to register the function prior to using it in an entity query.
So what I needed to do was first create a class extending my dialect, and registering my functions inside the constructor
public class MyCustomPostgreSQLDialect extends org.hibernate.dialect.PostgreSQLDialect {
public MyCustomPostgreSQLDialect() {
super();
registerFunction("name_of_function",
new StandardSQLFunction("name_of_function",
StandardBasicTypes.BIG_DECIMAL // Or the appropriated result of the function
)
);
}
}
And after that, change my Dialect in the persistence.xml to my new custom dialect with registrated functions
<property name="hibernate.dialect" value="my.package.MyCustomPostgreSQLDialect"/>
| |
doc_23537132
|
Let's say I have a set of buildings and in each building there are tenants. So I was going to set this up as a hierarchy in the Term Store:
TermGroup: Real Estate
TermSet: Buildings
Real Estate
Buildings
123 Main Street
345 West Avenue
567 North Blvd
This works great, I can create a field in my document library called "Building" as a Managed Metadata field and point it at "Buildings" and it will let me set it to one of the Buildings above.
Now I want to add the tenants to the Buildings because I want the metadata on a file to include both the building that it relates to and the tenant it relates to. Because some files relate only to the entire building, while some relate to a specific tenant. And I want to be able to look at the document in the document library and see the tenant it relates to (not Building\Tenant - that's too long).
So now it looks like this:
Real Estate
Buildings
123 Main Street
John Smith
Mary Jones
345 West Avenue
Bill Johnson
XYZ Company
Sue Stein
567 North Blvd
Fred Fulton
Mary Jones
Andy Dufrane
So now I add a Tenant field as a Managed Metadata field on the library - but I have to point it to the Buildings TermSet because that's how it finds the tenants when I enter a value in the field. But there's nothing to stop the end user from picking a Building instead of a Tenant in the Tenant field, right?
I could create a second TermSet that has all the Tenants in it at the first level - but as you can see above, there is a Mary Jones (two different people) in two different Buildings.
So I suppose my question is - is there a way to have a hierarchy like this in the Term Store, but require that a field use the second level values only?
Or another way to structure this so I do keep the relation of Building:Tenant but make sure that only Buildings go in the Building field and only Tenants go in the Tenant field?
| |
doc_23537133
|
# sample_config.py
import numpy as np
import datetime
params1 = {key1: {key2: val1,
key3: val2}}
params2 = {key4: datetime(2018, 3, 14)}
params3 = {key5: np.linspace(0, 1, 21)}
I have a main python file that calls the sample_config.py, uses the params dictionaries and update the params dictionaries.
# main.py
config = __import__('sample_config')
params1 = config.params1
params2 = config.params2
params3 = config.params3
test_out = test_function(input1, input2, params1)
params1['key1'] = updated_value
etc etc
What I'd like to do is to update the sample_config.py (or create a new config .py file) with the updated params dictionaries in main.py.
In my searches past couple of hours, many people recommend using json file, but since config file uses python modules, I'd like to keep it in the same .py format if possible..
Any help will be really appreciated. Thank you in advance.
A: You could cast the whole dictionary as a string and then write it to a .py file. Here's an example of what I mean:
updated_params_1 = {'a':1, 'b':2, 'c':3}
updated_params_2 = {'d':4, 'e':5, 'f':6}
new_python_file_contents = ('''
new_params_1 = {0}
new_params_2 = {1}
'''.format(updated_params_1, updated_params_2))
with open('updated_params.py', 'w') as f:
f.write(new_python_file_contents)
| |
doc_23537134
|
I would like to perform the following calculation with jquery when the tickbox is active and when the drop down is selected. And to recalculate if any of the other inputs change:
(#songLength slider value) x (#tracks select value) x (#basicRate value)
and to display the result in the output field.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Song Length</h1>
<div class="slidecontainer">
<input type="range" min="1" max="5" value="3" step="0.5" class="slider" id="songRange">
<p>Song Length: <span id="songLength"></span></p>
</div>
<div>
<label for="tracks">How many tracks?</label>
<select id="tracks">
<option selected value="0">How Many Tracks?</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<div>
<input type="checkbox" id="basicDisplay" name="tuning" value="10">
<label for="tuning">Vocal Tuning</label>
</div>
Tuning cost: <output name = "tuningCost"></output>
<script>
//slider
var slider = document.getElementById("songRange");
var output = document.getElementById("songLength");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
</script>
</body>
</html>
A: This might be a starting point:
(function($) {
var slider = $('#songRange'),
tracks = $('#tracks'),
checkb = $('input[type="checkbox"]'),
output = $('output');
var onChange = function() {
if (!checkb.is(':checked')) {
output.text('')
} else {
var sliderVal = slider.val(),
tracksVal = tracks.val(),
checkbVal = checkb.val()
output.text(sliderVal * tracksVal * checkbVal)
}
}
$(document).on('input change', '#songRange', onChange);
$(document).on('change', '#tracks', onChange);
$(document).on('change', 'input[type="checkbox"]', onChange);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Song Length</h1>
<div class="slidecontainer">
<input type="range" min="1" max="5" value="3" step="0.5" class="slider" id="songRange">
<p>Song Length: <span id="songLength"></span></p>
</div>
<div>
<label for="tracks">How many tracks?</label>
<select id="tracks">
<option selected value="0">How Many Tracks?</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
</select>
<div>
<input type="checkbox" id="basicRdisplay the result i ate" name="tuning" value="10">
<label for="tuning">Vocal Tuning</label>
</div>
Tuning cost: <output name="tuningCost"></output>
</body>
</html>
| |
doc_23537135
|
persist() is well defined. It makes a transient instance persistent.
However, it doesn't guarantee that the identifier value will be
assigned to the persistent instance immediately, the assignment might
happen at flush time. The spec doesn't say that, which is the problem
I have with persist().
persist() also guarantees that it will not execute an INSERT statement
if it is called outside of transaction boundaries. This is useful in
long-running conversations with an extended Session/persistence
context.
A method like persist() is required.
save() does not guarantee the same, it returns an identifier, and if
an INSERT has to be executed to get the identifier (e.g. "identity"
generator, not "sequence"), this INSERT happens immediately, no matter
if you are inside or outside of a transaction. This is not good in a
long-running conversation with an extended Session/persistence
context.
Can you please help me in understanding the lines for persist that says:
persist() also guarantees that it will not execute an INSERT statement
if it is called outside of transaction boundaries. This is useful in
long-running conversations with an extended Session/persistence
context.
What are the transaction boundaries here? and what are the long-running conversations? what is extended Session/persistence context means?
Also for save method:
this INSERT happens immediately, no matter if you are inside or
outside of a transaction. This is not good in a long-running
conversation with an extended Session/persistence context.
I understand that we need not have statements like session.beginTransaction() and session.getTransaction().commt() if we are using save method in my program for saving an object. Please let me know if the statement says the same thing here. So how is this useful in long running conversations?
I am new to hibernate and finding it difficulty to understand the differences, can you please help me in understanding the differences.
A: Your question relates to the Open Session in View pattern Hibernate implements.
The idea is that you might have an atomic unit of work in a web application that needs to run throughout a particular process. Imagine ordering food online. You sign in on one page, choose pizza and toppings on the next page, add dessert on the next page, add drinks on the next page, and pay on the last page. You want that whole process to be a single unit of work.
So the Hibernate Session needs to be opened at the beginning of that unit of work and closed at the end--either manually or through some kind of container management.
Calling persist during that conversation will not result in any inserts of data, but it will make a detached entity persistent. Hibernate will "keep a record" of all inserts to be made and then flush them at the end of the conversation.
Meanwhile save does the insert immediately and gives your entity an id from the database. This isn't good during a long-running conversation because you want your database operations to be atomic--all or nothing. Weird things like multiple inserts of the same data could occur.
Hope that helps.
A: The save() method can return that primary key id value which is generated by hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, hope you are clear.
So persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries since there is no need to get id after persisting an object.
Whereas the save() method does not guarantee the same, since it need to returns an identifier (probably primary key id).
An INSERT has to be executed to get the identifier (e.g. "identity" generator), So, this INSERT happens immediately with save(), no matter if you are inside or outside of a transaction.
A: One of the key difference between save and persist methods are depends on ID generation strategies. Basically save() method will return the value(id) back to the client and persist() method will not..
1) In a case where you let your ORM engine generates ID for you and in those cases you can use save().Reason is simple "Hibernate giving you the opportunity to get to know what ID it has generated/used to persist your object "
2) In a case where your have generated your id by yourself (assigned ID generation strategy) and passing it to ORM engine to use the same to persist your object.In such cases persist() will be appropriate .
click here
As I said
"It depends on ID generation strategies"
Cheers!
A: As the method name suggests, hibernate save() can be used to save entity to database. We can invoke this method outside a transaction. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session
Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database.
Also, we can use persist() method only within the boundary of a transaction, so it’s safe and takes care of any cascaded objects.
Finally, persist doesn’t return anything so we need to use the persisted object to get the generated identifier value.
| |
doc_23537136
|
This is my code. Please check it.
<?php echo $waktune; ?> // You can change it into seconds
var detik = <?php echo $waktune; ?>;
if (document.images) {
parselimit = detik
}
function begintimer() {
if (!document.images)
return
if (parselimit < 12) {
document.getElementById("servertime").style.color = "Green";
}
if (parselimit == 1) {
document.getElementById("hasil").submit();
} else {
parselimit -= 1 curmin = Math.floor(parselimit / 60)
cursec = parselimit % 60
if (curmin != 0)
curtime = curmin + ":" + cursec + ""else
curtime = cursec + " detik"document.getElementById("servertime").innerHTML = curtime setTimeout("begintimer()", 1000)
}
}
A: Try to use session storage :
// Store
sessionStorage.setItem("key", "value");
// Retrieve
document.getElementById("result").innerHTML=sessionStorage.getItem("key");
Update
Example :
<head>
</head>
<body>
<div id="divCounter"></div>
<script type="text/javascript">
if (sessionStorage.getItem("counter")) {
if (sessionStorage.getItem("counter") >= 10) {
var value = 0;
} else {
var value = sessionStorage.getItem("counter");
}
} else {
var value = 0;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value >= 10) {
sessionStorage.setItem("counter", 0);
value = 0;
} else {
value = parseInt(value) + 1;
sessionStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(counter, 1000);
</script>
</body>
A: Store the server time in a cookie (see setcookie) and load that. You'll want to think about how long you want this cookie to last though.
A: I think you have to save some value in the cookie and reset timer only if timer > x && cookie is already been setted.
Set cookie on init:
setcookie("reloaded","true");
Set cookie on reaload:
setcookie("reloaded","false");
Check:
if($_COOKIE["reloaded"] == false && timer > $time) {
/* reset timer */
}
A: You can use local storage, such as :
localStorage.setItem('countDownValue', curtime); // To set the value
...
curtime = localStorage.getItem('countDownValue'); // To get the value
A: <form name="counter">
<input type="text" size="8" name="chandresh" id="counter">
</form>
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var cnt = 60;
function counter(){
if(getCookie("cnt") > 0){
cnt = getCookie("cnt");
}
cnt -= 1;
document.cookie = "cnt="+ cnt;
jQuery("#counter").val(getCookie("cnt"));
if(cnt>0){
setTimeout(counter,1000);
}
}
counter();
</script>
Source: http://chandreshrana.blogspot.in/2017/01/how-to-make-counter-not-reset-on-page.html
A: How to create a countdown timer with JavaScript.
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
Try it yourself
Hope for help.
| |
doc_23537137
|
PS. I really know nothing about programming so "for dummies" answers only, please. Thx
A: If you check the source code on Github
https://github.com/cnr-isti-vclab/meshlab/blob/f3568e75c9aed6da8bb105a1c8ac7ebbe00e4536/src/common/GLLogStream.h
Meshlab does not use Log4J, looks like they created their on logger.
| |
doc_23537138
|
I know how to do this in Android Studio.
autoSizeMinTextSize=14sp
autoSizeMaxTestSize=20sp
But when I tried to use suggestions like a large font size with minimumScaleFactor, it doesn't work. It just makes the text incredibly small.
Here is my button style.
struct SoundButton: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(Color.black)
.multilineTextAlignment(.center)
.font(.custom("arial", size: 20))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(configuration.isPressed ? LinearGradient(gradient: Gradient(colors: [Color("DarkestGreen"), Color("LightGreen")]), startPoint: .top, endPoint: .bottom):LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .top, endPoint: .bottom))
.cornerRadius(10)
.shadow(radius: 3.0)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.white, lineWidth:2))
.padding(2)
.scaleEffect(configuration.isPressed ? 0.975 : 1.0)
}
}
And here is the button code.
Button(action: {
playSound(sound: "\(self.category)_audio1", type: "mp3")
self.translation = self.btns[1][1]
}) {
if(gotValues==true) {
Text("\(self.btns[1][0])")
} else {
Text("\(self.btn1)")
}
}
Here is what my screen looks like in the app.
What can I add to this to achieve the desired effect? Thank you.
Also, here is the working android version.
A: As far as I understood your goal the following should give you required effect (or sort of)...
Tested with Xcode 11.4 / iOS 13.4
configuration.label
.padding(.horizontal, 8).lineLimit(1).minimumScaleFactor(0.4) // << this place !
.foregroundColor(Color.white)
| |
doc_23537139
|
Thanx.
A: No rewrite needed:
Alias /eventi /dogadjanja
should do the trick.
Alternatively, try
RewriteRule ^/eventi/(.*)$ /dogadjanja/$1 [QSA]
A: Try this rule:
RewriteRule ^eventi(/.*)?$ dogadjanja$1
| |
doc_23537140
|
I use php7.0 and phpmyadmin on vmware ubuntu server 16.04.6
I tried to fix it myself but I'm not really good at those kind of things if you need any more code tell me.
any help if welcome
the site wont let me post the full code here is the full code
This is the AuthController code
<?php namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use Illuminate\Support\Facades\DB;
use App\User;
use Auth;
use Carbon\Carbon;
class AuthController extends Controller
{
/**
* The SteamAuth instance.
*
* @var SteamAuth
*/
protected $steam;
/**
* The redirect URL.
*
* @var string
*/
protected $redirectURL = '192.168.1.12';
/**
* AuthController constructor.
*
* @param SteamAuth $steam
*/
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
/**
* Redirect the user to the authentication page
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function redirectToSteam()
{
return $this->steam->redirect();
}
/**
* Get user info and log in
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function handle()
{
if($this->steam->validate())
{
$info = $this->steam->getUserInfo();
$findUser = DB::table('users')->where('steamid', $info->steamID64)->first();
if(is_null($findUser))
{
$hasThisIp = DB::table('users')->where('ip', $this->getIp())->count();
if(!is_null($hasThisIp)) {
$connections = json_decode(json_encode($hasThisIp), true);
if($connections > 3) return view('connections');
else {
$array = array('<','>');
$numele = $info->personaname;
$name = str_replace($array, '*', $numele);
DB::table('users')->insert(
[
'name' => $name,
'steamid' => $info->steamID64,
'avatar' => $info->avatarfull,
'token' => csrf_token(),
'ip' => $this->getIp()
]
);
| |
doc_23537141
|
+---A---+---B---+
| x | 0 |
| x | 0 |
| ... | ... |
-----------------
Column B is important. If there is no row > 0 then I wouldn't have run another code and could simply echo a text. If there is one row with B>0 then I need to know that.
I tried this so far, which gives me the result shown in the picture. And I checked the table, it's right.
"SELECT COUNT(*) FROM table
WHERE B>0";
I tried to examine the 0 with the code below but I gives me 1 as result. Probably because it counts the row above in the picture.
$statement_count = $pdo->prepare($check);
$statement_count->execute();
$count = $statement_count->rowCount();
echo $count;
So, what can I do instead?
A: You don't need to get the row count, you need to get the result of the query and parse it, then read the value for "count(*)"
A: If you do:
$check = "SELECT B FROM table WHERE B>0"
$statement_count = $pdo->prepare($check);
$statement_count->execute();
$count = $statement_count->rowCount();
echo $count;
It will echo the number of rows that match your criteria.
if you apply rowCount on a query that do SELECT COUNT it will by definition return 1 because the query will always return one row
The other option is to run the count query you have
$check = "SELECT COUNT(*) FROM table WHERE B>0";
$statement_count = $pdo->prepare($check);
$statement_count->execute();
$count = $statement_count->fetchColumn();
echo $count;
A: Your query always returns exactly 1 row. You need to read the value in that row. To read only one column from one row you can use PDOStatement::fetchColumn:
$count = $statement_count->fetchColumn();
| |
doc_23537142
|
Here's an image of the scenario I'm trying to explain:
A: Includes happen on the server when the script is executed, there are no http requests involved in that process. These are two totally separate and different things.
Optimize the number of http (ajax) requests and do not worry about includes in that context. I'm not even sure how you could substitute one for another. Includes are basically a way to structure your program into logical chunks to enable better maintainability and reusability. Http requests are the method used to communicate between the client (browser) and your program (server).
A: Short answer is NO PHP includes are not HTTP requests and are being processed by PHP interpreter during script execution.
However there is something called include through HTTP, which is specific scenario where you include file using HTTP protocol.
You can read this link from PHP manual for more information: http://php.net/manual/en/function.include.php
| |
doc_23537143
|
{(4x^2-20x+1/4 y^2+8=0
1/2 xy^2+2x-5y+8=0)
I have already run the code,but I'm confused if there should be 1 answer or 2 because function will only return the results for the last line
Should I do like this
> myfunc=function(x){
+ 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+ }
> optim(c(0,0),myfunc,method="BFGS")
and
> myfunc=function(x){
+ (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+ }
> optim(c(0,0),myfunc,method="BFGS")
or should I do like this
> myfunc=function(x){
+ 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+ (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+ }
> optim(c(0,0),myfunc,method="BFGS")
For the second one it still give me only the answer for the second function so which method is correct.
A: Minimize the sum of the squares of the two expressions that should equal zero and ensure that the value at the optimum equals 0 (up to floating point approximation).
myfunc <- function(z) {
x <- z[1]
y <- z[2]
(4*x^2-20* x + 1/4*y^2 + 8)^2 + (1/2 * x*y^2 + 2*x- 5*y + 8)^2
}
optim(c(0, 0), myfunc)
giving:
$par
[1] 0.5000553 2.0002986
$value
[1] 1.291233e-06
$counts
function gradient
67 NA
$convergence
[1] 0
$message
NULL
A: You can also use a package for solving systems of non linear equations such as nleqslv.
Slightly redefine your function by making it return a vector containing the result for each equation
myfunc <- function(x){
y <- numeric(length(x))
y[1] <- 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
y[2] <- (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
y
}
Define a starting value for the solver
xstart <- c(0,0)
Then do this
library(nleqslv)
nleqslv(xstart,myfunc)
giving
$x
[1] 0.5 2.0
$fvec
[1] -1.472252e-09 -7.081979e-10
$termcd
[1] 1
$message
[1] "Function criterion near zero"
$scalex
[1] 1 1
$nfcnt
[1] 7
$njcnt
[1] 1
$iter
[1] 7
There are more packages that can solve equation systems such as BB and pracma.
| |
doc_23537144
|
if let urlContent = data {
do {
let jsonResult = try
JSONSerialization.jsonObject(with:urlContent, options:
JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(jsonResult)
if let items = jsonResult["items"] as? NSArray {
for item in items {
print(item["published"])
print(item["title"])
print(item["content"])
A: You need it as an array of dictionaries it seems.
if let items = jsonResult["items"] as? [[String: Any]] {
for item in items {
print(item["published"])
print(item["title"])
print(item["content"])
}
}
Depending on what content you have in the dictionary you can replace Any in [String: Any] with that type. In this case it seems to be String.
| |
doc_23537145
|
I have the following code :
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
if unsafepointer != nil {
sText=String.fromCString(unsafepointer)! // <<<<<< ERROR
} else {
sText="unsafe text pointer is nil !";
}
I get an error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
at line marked with <<<<<< ERROR.
The unsafe pointer's value is not nil:
pointerValue : 2068355072
How can I handle this error, so my app is not crashing ?
A: Another possible solution is this:
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
var sText = "unsafe text pointer is nil !";
if unsafepointer != nil{
if let text = String.fromCString(unsafepointer) as String?{
sText = text;
}
}
A: let statementValue = sqlite3_column_text(statement, 2)
var sText = withUnsafeMutablePointer(&statementValue) {UnsafeMutablePointer<Void>($0)}
A: if sqlite3_column_text(statement, 2) != nil {
print("do something")
} else {
YourString = ""
}
| |
doc_23537146
|
Gives an error message
fatal: bad boolean config value 'of' for 'core.quotepath'
What should I do to avoid this error message?
A: Since Git 2.39, I mentioned all boolean values are now explicitly described are true or false.
In your case, considering core.quotepath is by default true:
git config --global core.quotepath false
Or, to restore its default value:
git config --global --unset core.quotepath
| |
doc_23537147
|
Consider a df with two columns, one with a year, and the other with a binary variable indicating some event.
df <- data.frame(year = c(2000,2001,2002,2003,2004, 2005,2006,2007,2008,2010),
flag = c(0,0,0,1,0,0,0,1,0,0))
I want to create a third column that simply counts the years since the last flag and that resets when a new flag appears, like so:
I thought this code would do the job:
First, add a 0 as "year_since" for every year with a flag, then, if there was a flag in the previous year, add 1 to the value of the previous "year_since".
df <- df %>% mutate(year_since = ifelse(flag == 1, 0, NA)) %>%
mutate(year_since = ifelse(dplyr::lag(flag, n=1, order_by = "year") == 1 & is.na(year_since),
dplyr::lag(year_since, n=1, order_by = "year")+1, year_since))
However, this returns NA for every row that should be 1,2,3, and so on.
A: You could do
df %>%
group_by(group = cumsum(flag)) %>%
mutate(year_since = ifelse(group == 0, NA, seq(n()) - 1)) %>%
ungroup() %>%
select(-group)
#> # A tibble: 10 x 3
#> year flag year_since
#> <dbl> <dbl> <dbl>
#> 1 2000 0 NA
#> 2 2001 0 NA
#> 3 2002 0 NA
#> 4 2003 1 0
#> 5 2004 0 1
#> 6 2005 0 2
#> 7 2006 0 3
#> 8 2007 1 0
#> 9 2008 0 1
#> 10 2010 0 2
Created on 2022-09-16 with reprex v2.0.2
A: Using data.table
library(data.table)
setDT(df)[, year_since := (NA^!cummax(flag)) * rowid(cumsum(flag))-1]
-output
> df
year flag year_since
<num> <num> <num>
1: 2000 0 NA
2: 2001 0 NA
3: 2002 0 NA
4: 2003 1 0
5: 2004 0 1
6: 2005 0 2
7: 2006 0 3
8: 2007 1 0
9: 2008 0 1
10: 2010 0 2
| |
doc_23537148
|
In the Kessel-Gustufson algorithm, we choose the mahalanobis norm in case we want to take a better shape for the cluster?
fuzzy question :In the clustering mean-c algorithm, we choose the parameter m as close to one in case we want partitioning hard?
In the Kessel-Gustufson algorithm, we choose the mahalanobis norm in case we want to take a better shape for the cluster?
| |
doc_23537149
|
Mi nuxt.config.js file:
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
ssr: true,
// Global page headers: https://go.nuxtjs.dev/config-head,
modules: [
'@nuxtjs/axios',
'@nuxtjs/auth-next',
// '~/modules/api/index.js'
],
serverMiddleware:[
{ path: '/api', handler: '~/api/index.js'},
],
axios: {
baseURL: 'http://localhost:3000/',
},
head: {
title: 'Encontrar Hogar',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Encontra tu nuevo hogar en chacabuco. Todas las propiedades e inmuebles de Chacabuco en un mismo lugar' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: '/normalize.css' },
{ rel: 'stylesheet', href: "https://unpkg.com/swiper/swiper-bundle.min.css" }
],
script: [
{ src: "https://kit.fontawesome.com/57d52ad1ee.js", crossorigin: "anonymous" },
]
},
loading: {
color: 'black',
height: '8px',
continuous: true
},
css: [
'@/assets/css/index.css'
],
auth: {
cookie:{
options:{
secure: true
}
},
strategies: {
local: {
token: {
property: 'token'
},
user: {
property: 'user'
},
endpoints: {
login: { url: '/api/usuarios/login', method: 'post', propertyName: 'data' },
user: { url: '/api/usuarios/mi-perfil', method: 'get', propertyName: 'data' },
logout: false
}
}
}
},
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/swiper.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true
}
/api/index.js file:
const bodyParser = require('body-parser')
const app = require('express')()
app.get('/api/:id?', (req, res) => res.send('hello'))
module.exports = app
If I try to create endpoints like the one that I will leave below, the only thing I get when making the get requests through the browser or postman is a 404 not found response, I do not understand what I am configuring wrong.
app.get('/api/products', (req, res) => res.send('products'))
A: Did you call http://localhost:3000/api/youridhere ?
According to your configuration and serveMiddleware, your link should be http://localhost:3000/api/api/youridhere
A: You have static target, change to "server" if you want serverMiddleware to work
| |
doc_23537150
|
$ ls .git/refs/tags
v0.0.1 v0.0.2 v0.0.3 v0.0.4
Now, if I go to machineB and do a clone of the repo [that is on the server or hosting provider, not the repo on machineA]. None of the tags are available [on machineB]. I tried git fetch --all --tags. I also tried git tag -l. The .git/refs/tags is empty also. What am I doing wrong? These tags were inserted by the python-semantic-release module.
A: As in the comments and my update of your question with corrected facts, the problem is that you've never sent the tags from machineA to the server-or-hosted repository. You need to use git push --tags, or an explicit git push of each tag, from machineA to the server, so that the server will have the tags, before machineB can get those tags from the server.
(Cloning on machineB directly from machineA would also work.)
| |
doc_23537151
|
url="http://192.168.1.254/xslt?PAGE=C_2_1"
From inspection, I believe this is the form I'm trying fill. The key value is ADM_PASSWORD.
<h2>Login</h2>
<p>Device access code required. Please enter the device access code, then click Submit.</p>
<form name="pagepost" method="post" action="xslt?PAGE=login_post" id="pagepost">
<input type="hidden" name="NONCE" value="0abc59f54121398" />
<input type="hidden" name="THISPAGE" value="" />
<input type="hidden" name="NEXTPAGE" value="C_2_1" />
<input type="hidden" name="CMSKICK" value="" />
<div>
<div class="form-group">
<label for="ADM_PASSWORD">Access code</label>
<span>
<input type="password" id="ADM_PASSWORD" name="ADM_PASSWORD" size="16" maxlength="16" autofocus="autofocus" required="required" autocomplete="off" />
</span>
</div>
</div>
<p align="right">
<input type="submit" class="button" value="Submit" />
I tried this but got 500 status error.
payload = { 'ADM_PASSWORD':'*access code*' }
response = requests.post(url, headers=headers, data=payload)
Is there a way to be able to collect information via requests instead of using GUI?
A: First in Chrome/Firefox you can use DevTools (tab: Network) to see what browser sends when you login.
Form has action="xslt?PAGE=login_post" so you should send to
url = "http://192.168.1.254/xslt?PAGE=login_post"
It is relative path - so if you would open page ie. http://http://192.168.1.254/login/ then it would need
url = "http://192.168.1.254/login/xslt?PAGE=login_post"
You have to send all input which you see in form - especially hidden.
Sometimes it may need even submit.
And you should use name= as key, not id=
payload = {
'NONCE': '0abc59f54121398',
'THISPAGE': '',
'NEXTPAGE': 'C_2_1',
'CMSKICK': '',
'ADM_PASSWORD': '*access code*'
}
If you use post() with data= or json= then it should automatically set correct value in Content-Type and Content-Length and you don't have to set it in headers.
You may also first run get() to page with form because it may set cookies which server/device may also check.
Problem can be only if page uses JavaScript to generate some extra data in form and it would need to use Selenium - but it would need to write all with Selenium
Sometimes I send request to https://httpbin.org/post and it sends me back all headers, cookies, post data which it get from me and I can compare it with data which I see in DevTools.
Evetually I use local proxy server Charles and use it in browser and in Python to see if code sends the same data as browser.
| |
doc_23537152
|
...other stuff...
<div style="width: 30px; margin-left: 500px; bottom: 0px;">
<img src="picture.png">
</div>
</body>
margin-left is working. Cannot figure out why the picture won't stick to the bottom..
A: For bottom to be effective, you will have to also use position set to relative or absolute:
<div style="position:absolute; width: 30px; margin-left: 500px; bottom: 0">
<img src="picture.png">
</div>
Use absolute or relative position depending on your layout requirements.
Note: With position set, you can also use left, right and top.
A: You have to explicitly position the element to be able to use the bottom property:
For absolutely positioned boxes, this property specifies how far the bottom margin edge of the box is offset above the bottom padding edge of its containing block.
For relatively positioned boxes, this property specifies how far the bottom edge of the box is offset above the position it would have had in the normal flow.
DEMO - source
A: The element is missing a position rule for the bottom to take effect. quirksmode has a good article on CSS positioning.
A: I think You are looking for something like this.
<div style="width: 30px; margin-left: 500px;">
<img src="picture.png" style='display: block;'>
</div>
The img by default has some space below, is above text baseline. It isn't margin or padding. The most common way to change this is to set display of image to block.
| |
doc_23537153
|
DS1 has week #( 1 to 49) , corresponding sales , ID
DS 2 has week #(50 to 52) , corresponding sales , ID
I did a data blending using ID as the relationship.
Question :
*
*How do I draw a graph between week # and sales for the complete data (week 1 till week 52)
*Does calculated field provide functions to get this done ?
Thanks in advance !
A: I'm going to enter this as a proposed solution rather than a comment. A union in the tableau data source screen is 100% the best way to go. If the 2 datasources have the same columns, you shouldn't need to re-pull the data. All of the work is done in Tableau.
Drag the "new union" pill into your data source pane and select the tables that you want to bring together, in this case DS 1 and DS 2.
The one caveat is that you have to be in v9.3+ like @AlexBlakemore said.
| |
doc_23537154
|
Is it possible to get the duration of the encoding process before we start encoding?
The aim of this is to get the total duration and display a progress bar (PHP).
Thanks
A: You will need to calculate the duration of the file in its current form using ffprobe to then be able to determine what the final file size will be before you start.
Duration: if it is audio and video not yet muxed, you can use ffprobe on the audio file if the video file Duration says "N/A".
File size: you control the size of the output file using the avconv options such as video bit rate, audio bit rate, along with the length/duration of the video to encode as detected by ffprobe.
Here is an example for calculating file size for a 30 minute video using typical avconv option settings:
http://ffmpeg.org/pipermail/ffmpeg-user/2012-February/005194.html
Use PHP (or better, an ajax call to a PHP back-end and animate using javascript or jquery) to update a progress bar as the size of the file output grows towards its final size.
| |
doc_23537155
|
My PWA installs service worker and manifest.json file. If I open it on chrome on mobile phone and put my phone on flight mode, then refreshing the url still gives shows me my application. Its expected as my service worker is doing offline caching.
But when I add my PWA to home screen, and try to open it on flight mode then it doesn't work. This is probably my first PWA, so please help me. I am generating my service worker file from 'sw-precache-webpack-plugin'.
My manifest.json file is:
{
"name": "VanillaJS-webpack App",
"short_name": "VanillaJS-webpack App",
"description": null,
"dir": "auto",
"lang": "en-US",
"display": "standalone",
"orientation": "any",
"start_url": "/?homescreen=1",
"background_color": "#ee6e73",
"icons": [
{
"src": "android-chrome-36x36.png",
"sizes": "36x36",
"type": "image/png"
},
{
"src": "android-chrome-48x48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "android-chrome-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "android-chrome-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "android-chrome-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "/android-chrome-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
A: When loading from home screen it should work in the same way as when loaded from the browser.
In your example, a quick debugging seems to indicate that the problem is related to the query string: https://plain-js-pwa.herokuapp.com/?homescreen=1
It does not work offline when the query string is added (irrelevant if loaded from home screen or otherwise). Without looking at your service worker configuration, most likely you need to instruct your service worker to ignore query string params using ignoreSearch (https://developer.mozilla.org/en-US/docs/Web/API/Cache/match) or ignoreUrlParametersMatching if using sw-precache.
| |
doc_23537156
|
Usually I would use this function accompanied by the code you get from the google consent page:
oauth2Client.getToken(code).
So I would expect something like this:
oauth2Client.getTokenWithRefreshToken(refresh_token).
But no.
Am I just misunderstanding the concept of refresh tokens?
A: If you have already had your refresh token and you want to use Google APIs using the access token retrieved from the refresh token using googleapis for Node.js, how about the following sample script?
Sample script:
const { google } = require("googleapis");
const oauth2Client = new google.auth.OAuth2(
"###", // Please set your client ID.
"###", // Please set your client secret.
"###", // Please set your redirect uri.
);
oauth2Client.setCredentials({
refresh_token: "###" // Please set your refresh token.
});
// If you want to retrieve the access token from the refresh token, you can use the following sample script.
oauth2Client.getAccessToken((err, token) => {
if (err) {
console.log(err);
return;
}
console.log(token);
});
// The following script is a sample script for using Drive API.
// In this case, it is required to include the scope for using Drive API. Please be careful this.
// const drive = google.drive({ version: "v3", auth: oauth2Client });
// drive.files.list({ pageSize: 10, fields: "files(name)" }, (err, res) => {
// if (err) {
// console.log(err);
// return;
// }
// console.log(res.data);
// });
Reference:
*
*Google APIs Node.js Client
| |
doc_23537157
|
When i use the JBossWS console to see the registered service endpoints, all my webservices follow the same URL pattern:
http://my_machine:8080/some_default_name/webservice_name?wsdl
The problem is that i need to change the some_default_name part of the URL.
Any suggestions? :)
A: I think what you call some_default_name is the of your web-app context. The simple way to change it is to rename your war (should be /server//deploy/some_default_name.war).
Jboss uses Tomcat as web container. You can configure path on Context element to change your context name as well.
| |
doc_23537158
|
<form action="/blogs/add" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST">
</div>
<!-- omitted: form inputs -->
</form>
Why is that div with the display:none; style there? How do I make it not show up?
UPDATE: Just to be clear, I'm wondering why both the div AND the hidden input inside the div show up. They don't seem to be necessary, and therefore I don't want them to be there.
A: For anyone coming to this recently, there is a simple solution to this now that doesn't involve a custom helper. Using the FormHelper templates, the block of code in question is generated by the 'hiddenBlock' template. (See the full list of default templates here: https://api.cakephp.org/3.2/class-Cake.View.Helper.FormHelper.html#%24_defaultConfig).
So, to amend the example given in CakePHP's documentation to match this case and remove the wrapping <div> around the hidden <input> for _method (assuming HTML5):
// In your View class
$this->loadHelper( 'Form' , [ 'templates' => 'app_form' ] );
// in config/app_form.php
return [
'hiddenBlock' => '{{ content }}'
];
I was confronted with this problem because I recently implemented a Content Security Policy that doesn't allow inline styling, and I thought I should share my working solution.
A: The div is there to be valid HTML.
Non-block-level elements (such as <input>) are not valid directly inside <form> tags until HTML5. Source
Edit: To answer your question, you can't easily get rid of it. It's hard-coded into FormHelper::create(), you'd have to override that method in a custom helper. Why is it bothering you anyways?
A: This link might help you.
Whenever you use FormHelper->create() method ,A hidden input field is generated to override the default HTTP method. You can also change it by passing type option. Kindly ask if it not worked for you.
A: Try:
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => false
)
));
The divs won't be created on any input of the form.
A: use hiddenField => false property
| |
doc_23537159
|
Does this addin is specific to Outlook 365 accounts or it should be working with regular Outlook.com? My addin is not working with outlook.com; I just want to make sure before declaring it to the users that it works only with Outlook 365 accounts.
Please suggest!
| |
doc_23537160
|
tables are:
SQL> select *
2 from paydata1;
IDNO NAME J SALARY PAYHR
---- ------------------------- - ---------- ----------
1111 Ann French S 75000 0
2222 Robert Costa H 0 45
3333 Linda Ames H 0 50
4444 Scott Brooks S 78000 0
5555 Susan Ash S 57000 0
6666 James Smith S 55000 0
7777 Mary Jones H 0 36
8888 John Morse H 0 39
AND
SQL> select *
2 from paytran1;
IDNO PRO HOURSWK
---- --- ----------
1111 123 20
1111 456 10
1111 789 15
2222 123 17
2222 456 24
2222 789 20
3333 123 20
3333 789 20
4444 123 10
4444 456 28
4444 789 5
5555 456 40
6666 456 44
7777 456 30
7777 789 15
8888 123 10
8888 456 25
8888 789 5
The question is: write the PL/SQL program to read the files using cursors and write out the total hours worked by each employee.
My pl/sql code is:
SET SERVEROUTPUT ON
DECLARE
v_idno paydata1.idno%TYPE;
v_name paydata1.name%TYPE;
v_idno1 paytran1.idno%TYPE;
v_hourswk paytran1.hourswk%TYPE;
CURSOR paydata1_cursor IS
SELECT idno, name FROM paydata1
ORDER BY idno;
CURSOR paytran1_cursor IS
SELECT idno, hourswk FROM paytran1
WHERE v_idno1 = idno
order BY idno;
BEGIN
OPEN paydata1_cursor;
LOOP
FETCH paydata1_cursor INTO v_idno, v_name;
EXIT WHEN paydata1_cursor%NOTFOUND;
IF paytran1_cursor%ISOPEN THEN
CLOSE paytran1_cursor;
END IF;
OPEN paytran1_cursor;
LOOP
FETCH paytran1_cursor INTO v_idno1, v_hourswk;
EXIT WHEN paytran1_cursor%NOTFOUND;
END LOOP;
INSERT into allinfo
VALUES(v_idno, v_name, v_hourswk);
CLOSE paytran1_cursor;
END LOOP;
CLOSE paydata1_cursor;
END;
/
SET SERVEROUTPUT OFF
My allinfo table results are:
SQL> select *
2 from allinfo;
IDNO EMPLOYEE HOURS
---- --------------- ----------
1111 Ann French
2222 Robert Costa
3333 Linda Ames
4444 Scott Brooks
5555 Susan Ash
6666 James Smith
7777 Mary Jones
8888 John Morse
Why isnt the hourswk being combined and displayed on the allinfo table with the idno and name?
A: Try making paytran1_cursor a parameterized cursor:
CURSOR paytran1_cursor (p_idno1 paydata1.idno%TYPE) IS
SELECT SUM(hourswk) FROM paytran1 -- already have idno; just sum hours
WHERE p_idno1 = idno -- don't need to order by one value
[...]
-- sum() will return one row, so no need to loop
OPEN paytran1_cursor (v_idno1);
FETCH paytran1_cursor INTO v_hourswk;
(I think that's the Oracle syntax.)
There are several problems here. The main one is that your cursor query is run as written when the cursor is opened. That means that when you opened paytran1_cursor, you were querying with the then-current value of v_idno1, which was NULL. Using a parameterized cursor here will
*
*ensure that the value you pass into your WHERE clause is in scope,
and
*make it clear to the reader that you are conditioning the cursor
query on data coming from outside the cursor.
Hope that helps.
A: By looking into the code. I think the better way is to make the approach purely sql rather then using PLSQL approach. I have replicated the scenario in such a way that you can implement it. Mey be this will help you out.
INSERT INTO <TABLE>
SELECT A.IDNO,
SUM(A.PSUM+B.HSWR)
FROM
(SELECT PAYHR.IDNO,
SUM(PAYHR.PAYHR) PSUM
FROM
(SELECT 111 AS IDNO,23 AS PAYHR FROM DUAL
UNION ALL
SELECT 111 AS IDNO,30 AS PAYHR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,10 AS PAYHR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,8 AS PAYHR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,15 AS PAYHR FROM DUAL
UNION ALL
SELECT 113 AS IDNO,25 AS PAYHR FROM DUAL
)PAYHR
GROUP BY PAYHR.IDNO
)A,
(SELECT HSWRK.IDNO,
SUM(HSWRK.HSWR) HSWR
FROM
( SELECT 111 AS IDNO,10 HSWR FROM DUAL
UNION ALL
SELECT 111 AS IDNO,30 HSWR FROM DUAL
UNION ALL
SELECT 111 AS IDNO,15 HSWR FROM DUAL
UNION ALL
SELECT 111 AS IDNO,25 HSWR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,10 HSWR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,17 HSWR FROM DUAL
UNION ALL
SELECT 112 AS IDNO,40 HSWR FROM DUAL
UNION ALL
SELECT 113 AS IDNO,16 HSWR FROM DUAL
)HSWRK
GROUP BY HSWRK.IDNO
)B
WHERE A.IDNO = B.IDNO
GROUP BY A.IDNO;
| |
doc_23537161
|
int foo(int a, int b, int d, int x){
if (c) {a = 1; b = 1; d = a;}
else {a = 2; b = 2; d = 1;}
if (a == b) {x = d;} else {x = 0;}
return x;
}
This trivial function returns always 1. Compiling with clang with -O2 option and looking at the disassembled code LLVM correctly compiles this function as return 1;.
My question is: How does llvm do static value analysys? weakest precondition techiniques? value propagation? Hoare's techniques?
A: LLVM does all sorts of things: see here.
You can get a dump of the intermediate representation after each optimisation pass like this:
clang -c -mllvm -print-after-all -O2 foo.c
to identify which stage is doing what.
In fact, this particular example is not really very magical!
If you convert it to SSA form, it looks something like this:
// block 1
if (c == 0) goto L1;
// block 2
a_0 = 1;
b_0 = 1;
d_0 = a_0;
goto L2;
L1:
// block 3
a_1 = 2;
b_1 = 2;
d_1 = 1;
goto L2;
L2:
// block 4 (has two possible predecessors: block 2 or block 3)
a_2 = PHI(a_0, a_1); // i.e. a_0 if we came from block 2, a_1 if we came from block 3
b_2 = PHI(b_0, b_1); // i.e. b_0 if we came from block 2, b_1 if we came from block 3
d_2 = PHI(d_0, d_1); // i.e. d_0 if we came from block 2, d_1 if we came from block 3
if (a_2 != b_2) goto L3;
// block 5
x_0 = d_2;
goto L4:
L3:
// block 6
x_1 = 0;
goto L4;
L4:
// block 7 (has two possible predecessors: block 5 or block 6)
return PHI(x_0, x_1); // i.e. x_0 if we came from block 5, x_1 if we came from block 6
Simply propagation of constant values results in this:
// block 1
if (c == 0) goto L1;
// block 2
a_0 = 1;
b_0 = 1;
d_0 = 1;
goto L2;
L1:
// block 3
a_1 = 2;
b_1 = 2;
d_1 = 1;
goto L2;
L2:
// block 4
a_2 = PHI(1, 2); // i.e. 1 if we came from block 2, 2 if we came from block 3
b_2 = PHI(1, 2); // i.e. 1 if we came from block 2, 2 if we came from block 3
d_2 = 1; // PHI(d_0, d_1) == PHI(1, 1) i.e. 1 regardless of where we came from
if (a_2 != b_2) goto L3;
// block 5
x_0 = 1; // (we've deduced that d_2 == 1 regardless of control flow)
goto L4:
L3:
// block 6
x_1 = 0;
goto L4;
L4:
// block 7
return PHI(1, 0); // i.e. 1 if we came from block 5, 0 if we came from block 6
Simplifying to remove the assignments which are no longer used for anything else gives this:
// block 1
if (c == 0) goto L1;
// block 2
goto L2;
L1:
// block 3
goto L2;
L2:
// block 4
a_2 = PHI(1, 2); // i.e. 1 if we came from block 2, 2 if we came from block 3
b_2 = PHI(1, 2); // i.e. 1 if we came from block 2, 2 if we came from block 3
if (a_2 != b_2) goto L3;
// block 5
goto L4:
L3:
// block 6
goto L4;
L4:
// block 7
return PHI(1, 0); // i.e. 1 if we came from block 5, 0 if we came from block 6
...and now the first conditional is clearly a no-op; and the second must always be true (the block 5 path) because a_2 and b_2 are the same expression. So the result is
return 1;
| |
doc_23537162
|
So in android, how to prevent multiple process writing to the same file?
A: In android,you can use FileLock to lock a file to prevent another process from writing to that file.
A file lock can be :
Exclusive or
shared
Shared : Multiple processes can hold shared locks on the same region of a single file.
Exclusive : Only a single process can hold an exclusive lock. No other process can simultaneously hold a shared lock overlapping the exclusive.
final boolean isShared() : check wheather the file lock is shared or exclusive.
final long position() : lock's starting position in the file is returned.
abstract void release() : releases the lock on the file.
final long size() : returns length of the file that is locked.
Following example will clear your doubt how to lock a file and release it after performing operations on it.
public void testMethod() throws IOException,NullPointerException{
String fileName="textFile.txt";
String fileBody="write this string to the file";
File root;
File textFile=null;
//create one file inside /sdcard/directoryName/
try
{
root = new File(Environment.getExternalStorageDirectory(),"directoryName");
if (!root.exists()) {
root.mkdirs();
}
textFile = new File(root, fileName);
FileWriter writer = new FileWriter(textFile);
writer.append(fileBody);
writer.flush();
writer.close();
System.out.println("file is created and saved");
}
catch(IOException e)
{
e.printStackTrace();
}
//file created. Now take lock on the file
RandomAccessFile rFile=new RandomAccessFile(textFile,"rw");
FileChannel fc = rFile.getChannel();
FileLock lock = fc.lock(10,20, false);
System.out.println("got the lock");
//wait for some time and release the lock
try { Thread.sleep(4000); } catch (InterruptedException e) {}
lock.release();
System.out.println("released ");
rFile.close();
}
| |
doc_23537163
|
-------------------------------------
| Id | startdate | enddate |rate|
-------------------------------------
| 1 | 1/1/2015 | 2/1/2015 | 10 |
| 1 | 2/1/2015 | 3/1/2015 | 15 |
| 1 | 3/1/2015 | 4/1/2015 | 5 |
| 1 | 4/1/2015 | 5/1/2015 | 10 |
| 1 | 5/1/2015 | 6/1/2015 | 20 |
| 1 | 6/1/2015 | 7/1/2015 | 30 |
| 1 | 7/1/2015 | 8/1/2015 | 10 |
| 1 | 8/1/2015 | 9/1/2015 | 30 |
| 1 | 9/1/2015 | 12/31/2015 | 20 |
------------------------------------
I need to populate cumulative max values for each id (Id=1 for this example) including the first record, like below (SQL server 2008):
----------------------------------
| Id | startdate | enddate |rate |
----------------------------------
| 1 | 1/1/2015 | 2/1/2015 | 10 |
| 1 | 2/1/2015 | 3/1/2015 | 15 |
| 1 | 5/1/2015 | 6/1/2015 | 20 |
| 1 | 6/1/2015 | 7/1/2015 | 30 |
| 1 | 8/1/2015 | 9/1/2015 | 30 |
-----------------------------------
Can any one help me on this?
A: You can calculate the cumulative max in SQL Server 2008 using outer apply:
select t.*, t2.maxrate
from t outer apply
(select max(t2.rate) as maxrate
from t t2
where t2.startdate <= t.startdate
) t2;
Your question appears to be about filtering, not just calculating the cumulative maximum value. You can select the rows with the max rate using a subquery:
select t.*
from (select t.*, t2.maxrate
from t outer apply
(select max(t2.rate) as maxrate
from t t2
where t2.startdate <= t.startdate
) t2
) t
where t.rate = t.maxrate;
This will return duplicates in a row. A better way is to use exists:
select t.*
from t
where not exists (select 1
from t t2
where t2.rate > t.rate and t2.startdate < t.startdate
);
| |
doc_23537164
|
Table 1 contains orders and customer codes.
Table 2 contains orders with issue codes.
I need to be able to return distinct order count by customer from table 1 along with a distinct count by customer of orders with issuecode of 'F' from table 2. Then the final field will be a ratio of the two. Issue count / Order count. I'm using AS400/DB2 SQL. Any help would be greatly appreciated.
Customer ORcnt IScnt IssueRatio
cust1 450 37 0.082
cust2 255 12 0.047
cust3 1024 236 0.230
cust4 450 37 0.082
A: You can use an outer join to your issues table and count with distinct. Something like this depending on your table definitions:
select o.customercode,
count(distinct o.orderid),
count(distinct i.orderid),
count(distinct i.orderid)/count(distinct o.orderid) ratio
from table1 o
left join table2 i on o.orderid = i.orderid and i.issuecode = 'F'
group by o.customercode
Some databases would need to convert the ratio to a decimal -- I'm not sure about db2. If needed, one way is to multiply the result by 1.0:
1.0*count(distinct i.orderid)/count(distinct o.orderid)
Also, you may not need the distinct with the count -- depends on your data...
A: If I understand correctly, this is a join query along with conditional aggregation:
select t1.customer, count(*) as ordercnt,
sum(case when issuecode = 'F' then 1 else 0 end) as issuecnt,
avg(case when issuecode = 'F' then 1.0 else 0 end) as issuep
from table1 t1 join
table2 t2
on t1.orderid = t2.orderid
group by t1.customer;
A: I'm doing this w/ a few subqueries to make it more readable in terms of the description of the problem you presented. sgeddes' solution probably also works (and might perform better) depending on the precise structure of your data.
SELECT t.customer,
count(t.orderID_All),
count(t.orderID_F),
count(t.orderID_F)/count(t.orderID_All)
FROM
(SELECT orders.customer,
orders.orderID AS orderID_All,
issues.orderID AS orderID_F /*assuming primary/unique key is customer-orderID*/
FROM table1 orders
LEFT OUTER JOIN /*you want *all* orders on the left and just orders w/ 'F' on the right*/
(SELECT DISTINCT orderID
FROM table2
WHERE issuecode = 'F') issues ON orders.orderID = issues.orderID) t
GROUP BY t.customer;
| |
doc_23537165
|
tmp0 = np.array([[a,b],[c,d],[e,f],...,[...]])
I want to take out a value, say [a,b] and compare it to [c,d] to make stuff simple, than add those two to the end of a new array as a 3D list
tmp1 = np.array([[[...],[...]],[[a,b],[c,d]]])
This have been proven to be a real horror show... How do I achieve this..? In just a regular array it would be append, but not in numpy for some odd reason
| |
doc_23537166
|
2010/10/04 12:05:27 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:27 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:28 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:28 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:28 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:28 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:28 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:29 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:29 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:29 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:29 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:30 PM: Refreshing [/MyProject-ear/pom.xml]
2010/10/04 12:05:30 PM: Maven Builder: AUTO_BUILD
2010/10/04 12:05:30 PM: Maven Builder: AUTO_BUILD
I'm using M2Eclipse
A: I had the same problem until I unchecked "skip maven compiler plugin when processing resources" in Project properties/Maven/Lifecycle mapping.
A: Not sure if this will work for you, but check the Builders list in the Project properties (Project->Properties->Builders), the Maven Project Builder is listed there, maybe if you disable this builder (I haven't tried) you could get rid of that problem.
Best regards.
A: reinstalled m2e WITHOUT the m2e extras
| |
doc_23537167
|
Following are the
*
*Host the SSH Server on VM Role in Cloud, In this case, will the other Web/Worker roles on the same cloud be ale to access the local storage of the VM role?
*Is it possible to host a SSH FTP server using .NET components (Payed/Open Source) in a Worker role in Azure? If yes, please provide information regarding the .NET components available in Market.
*If there is no support for SSH in Windows Azure, please let me know other alternatives for Secure File Transfer in Cloud.
My client used to run their business Unix machines in Closed network from which they performed the file transfer through SFTP to SSH FTP servers of their suppliers.
We are building some applications on Cloud for them which require them to transfer data in the form of files as input to this cloud (web role) application.
To transfer files from their Closed network and to make them available on Cloud storage, they insist that they want to still perform this using SSH FTP or using SSH Protocol.
We have struck the wall with this requirement, and following is the solutions that we have proposed to them.
Please review and provide your comments/suggestions/inputs regarding the best method to perform SSH FTP of files to Cloud Storage.
*
*Host SSH Server on VM Role in Cloud, and deploy a Service in their network to transfer files from their network to the cloud. In this case, the files might be saved to the file system in the VM Role, how will we extract the file from the VM role and save it to the shared cloud storage so that other web roles running on cloud can access these files for getting input?
*Is it possible to host a SSH FTP server using .NET components (Payed/Open Source) in a Worker role in Azure?
*If there is no support for SSH in Windows Azure, please let me know other alternatives for Secure File Transfer using SSH to transfer files from on-premise to cloud storage.
A: Answers on 2 out of 3:
Host the SSH Server on VM Role in Cloud, In this case, will the other Web/Worker roles on the same cloud be ale to access the local storage of the VM role?
Not the local storage, but you could let them access a shared Cloud Drive - http://blog.maartenballiauw.be/post/2010/02/02/Using-Windows-Azure-Drive-(aka-X-Drive).aspx - note that only one instance can have write access to this drive, but plenty can have read.
If there is no support for SSH in Windows Azure, please let me know other alternatives for Secure File Transfer in Cloud.
The actual upload/download of blobs can be secured with SSL, and access to your stored hosting is via your keys.
To be honest, I'd recommend looking at using blob storage for this requirement. It depends on how many files/blobs you are looking to store and how often you want to change them, but overall blob storage is pretty useful and usable.
For an intro to blobs see http://blogs.msdn.com/b/jnak/archive/2010/01/11/walkthrough-windows-azure-blob-storage-nov-2009-and-later.aspx
Is it possible to host a SSH FTP server using .NET components (Payed/Open Source) in a Worker role in Azure? If yes, please provide information regarding the .NET components available in Market.
Possibly - but I've no idea on this - there's lots of hits from http://www.bing.com/search?setmkt=en-GB&q=ssh+ftp+server+c%23
Edit - also check out this thread - http://forums.iis.net/t/1147827.aspx - you could deploy WinSSHD to a role?
A: Anything is possible of course, but you have some fundamental issues to overcome to have a seamless SSH experience. The biggest issue is not installing SSH - that is cake. The issue you have to face is how to use it across instances when you have a load balancer in front. For a single instance, you should have no issues running an SSH server. All clients will connect easily. Once you have multiple servers running SSH, you get into an issue if the connection to an instance is severed and you reconnect to a different instance. It is nice to run multiple instances for SLA reasons, so this is a common issue.
Now, RDP (which is a stateful connection) works in Windows Azure because of a socket-based router that forwards traffic to the single instance you wish to communicate with. You might be able to do something similar for SSH.
Beyond the communication issue (assuming you work out SSH with load-balancing), you need to think about persistence. When you FTP something into Windows Azure, unless you are using a drive (XDrive), it is persisted only locally. You would need to think about moving those files off the VM and into permanent storage like blob storage.
So, long story short. Yes, you can do it, but it will be some work to do right.
A: We just posted a how-to SSH on Azure using OpenSSH @
http://blogs.msdn.com/b/mariok/archive/2011/08/09/command-line-access-to-azure-vms-ssh.aspx
The posting includes a sample package. It will run on any role type (Web/Worker/VM) and can be combined with other packages/apps.
A: if he's is not sure using the commandline on the instance he could consider installing webmin it's a great application running from your browser it lets you have control in a windows way on your virtual instance of linux I supposed.
| |
doc_23537168
|
ideally i would like to use simpleXML - but i believe it doesn't support namespaces?
failing that maybe simpleDOM? id rather not use DOM since it tends to confuse me a lot!
perhaps there is some other way?
thanks for your help!
:)
nb: i tried to post an example but couldn't get it to format properly (no line breaks with backticks, only one line at a time usng the GUI) so any help with that would be good to!
A: I think all answers above are outdated. Meanwhile EasyRdf seems to be the hippest child in town. It has properties which fully match the zeitgeist such as:
*
*Intuitive interface
*Hosted on Github, many "likes"
*Good documentation
*Test backed
A: You may want to try using ARC. It provides with a collection of parsers and serializers that allow the conversion of triples from/to multiple formats.
A: I would recommend you to use RDF API for PHP. RAP is a software package for parsing, querying, manipulating, serializing and serving RDF models.
A: Last time I looked at RDF, Redland was the tool of choice. It has a PHP interface, I suggest looking at that.
| |
doc_23537169
|
Similar to iterating over shared keys in two dictionaries , except the idea is not to iterate but rather get the set so it can be used to get the subset of dicts.
d1 = {'a':[1,2], 'b':[2,2]}
d2 = {'e':[3,2], 'b':[5,1], 'a':[5,5]}
d3 = {'b':[8,2], 'a':[3,3], 'c': [1,2]}
So intersection manually is simple
d1.keys() & d2.keys() & d3.keys()
but what about n-dimensional list? I feel like there is a better way than this:
d_list = [d1, d2, d3]
inter_keys = {}
for i in range(len(d_list)):
if i == 0:
inter_keys = d_list[i]
inter_keys = inter_keys & d_list[i].keys()
Then getting a subset
subsets = []
for n in d_list:
subsets.append( {k: n[k] for k in inter_keys} )
and finally use it to get the value subset
v = [ x.values() for x in subsets ]
*
*really the last part is formatted as v = np.array([ np.array(list(x.values())) for x in subsets ]) to get the ndarray as:
[[[2 2] [1 2]]
[[5 1] [5 5]]
[[8 2] [3 3]]]
I was thinking there may be an approach using something like the numpy where to more efficiently get the subset, but not sure.
A: I think your code can be simplified to:
In [383]: d_list=[d1,d2,d3]
In [388]: inter_keys = d_list[0].keys()
In [389]: for n in d_list[1:]:
...: inter_keys &= n.keys()
...:
In [390]: inter_keys
Out[390]: {'a', 'b'}
In [391]: np.array([[n[k] for k in inter_keys] for n in d_list])
Out[391]:
array([[[1, 2],
[2, 2]],
[[5, 5],
[5, 1]],
[[3, 3],
[8, 2]]])
That is, iteratively get the intersection of keys, followed by extraction of the values into a list of lists, which can be made into an array.
inter_keys starts as a dict.keys object, but becomes a set; both work with &=.
I don't think there's a way around the double loop with dict indexing, n[k] as the core. Unless you can use the values or items lists, there isn't a way around accessing dict items one by one.
The sub_sets list of dict is an unnecessary intermediate step.
All the keys and values can be extracted into a list of lists, but that doesn't help with selecting a common subset:
In [406]: big_list = [list(d.items()) for d in d_list]
In [407]: big_list
Out[407]:
[[('a', [1, 2]), ('b', [2, 2])],
[('e', [3, 2]), ('b', [5, 1]), ('a', [5, 5])],
[('b', [8, 2]), ('a', [3, 3]), ('c', [1, 2])]]
A: Assuming that the lists of values in your dictionaries are of the same length, you can use this approach:
import numpy as np
d1 = {'a':[1,2], 'b':[2,2]}
d2 = {'e':[3,2], 'b':[5,1], 'a':[5,5]}
d3 = {'b':[8,2], 'a':[3,3], 'c':[1,2]}
d_list = [d1, d2, d3]
inter_map = {} if len(d_list) == 0 else d_list[0]
for d_it in d_list[1:]:
# combine element lists based on the current intersection. keys that do not match once are removed from inter_map
inter_map = {k: inter_map[k] + d_it[k] for k in d_it.keys() & inter_map.keys()}
# inter_map holds a key->value list mapping at this point
values = np.array([item for sublist in inter_map.values() for item in sublist]).reshape([len(inter_map.keys()),
2 * len(d_list)])
# real_values restructures the values into the order used in your program, assumes you always have 2 values per sublist
real_values = np.zeros(shape=[len(d_list), 2 * len(inter_map.keys())])
for i, k in enumerate(inter_map.keys()):
real_values[:, 2*i:2*(i+1)] = values[i].reshape([len(d_list), 2])
Please note that this code is not deterministic, since the order of keys in your map is not guaranteed to be the same for different runs of the program.
| |
doc_23537170
|
[Table]
id, userId, locationId, type, timestamp
---------------------------------------
1 5 19 0 2017-03-28 03:05:48
2 5 19 1 2017-03-29 00:57:57
Is there a way to perform a sql that:
LIRFU = Last Inserted Row For User = SELECT * FROM Table WHERE userId = $userId ORDER BY timestamp DESC LIMIT 1.
*
*Inserts a row ($userId, $locationId, 1) if LIRFU.type = 0.
*Inserts a row ($userId, $locationId, 0) if LIRFU.type = 1 AND LIRFU.locationId != $locationId.
A: Let's call your table, User_Types.
Here's the statement to insert a row with sample data (5,19,1) if LIRFU.type = 0:
INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, 19, 1 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0;
You can make this into a prepared statement in PHP by replacing the data with ?.
$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, ?, 1 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 0");
$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 0
$stmt->execute();
Here's the statement to insert a row with sample data (5,19,0) if LIRFU.type = 1 AND LIRFU.locationId != 19:
INSERT INTO User_Types (userId, locationId, type)
SELECT @userId:=5, @locationId:=19, 0 from dual
WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1
AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId;
The same idea when it is prepared in PHP:
$stmt = $db->prepare("INSERT INTO User_Types (userId, locationId, type) SELECT @userId:=?, @locationId:=?, 0 from dual WHERE (SELECT type FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) = 1 AND (SELECT locationId FROM User_Types WHERE userId = @userId ORDER BY timestamp DESC LIMIT 1) <> @locationId");
$stmt->bind_param('ii', $user_id, $location_id);
//if LIRFU.type = 1 and LIRFU.locationId != $location_id
$stmt->execute();
| |
doc_23537171
|
I have a table with the collation utf8mb4_bin (case sensitive) but the user should perform case insensitive query, the past query is this
SELECT SQL_CALC_FOUND_ROWS * FROM utenti WHERE nome LIKE _utf8mb4 ? COLLATE utf8mb4_unicode_ci ORDER BY id_utente ASC
I know I can not use this syntax with prepared statements, whats is the best way? I thought forcing stored value and query value to lowercase, but I think is not the best way to do it.
A: You should be able to apply a case-insensitive collation to the column, and then compare that to your parameter:
SELECT * FROM utenti
WHERE nome COLLATE utf8mb4_unicode_ci LIKE ?
ORDER BY id_utente ASC
P.S.: I recommend to remove SQL_CALC_FOUND_ROWS. It has no purpose if you don't use LIMIT. It can only make the performance suck.
A: All you need to do is convert your value to uppercase in php and wrap your column with upper in the query.
select * from table where upper(column) like ?
With the ? being set to the uppercase value of the string you're looking for.
| |
doc_23537172
|
module portal {
$stateProvider.state('portal', {
url: '/demo',
template: tpl.html,
abstract: true,
resolve: {
demoResolve:function(){
return 'foo';//here i am returing a promise
}
});
}
module portal.directives{
export class demoDirevtive{
static $inject =['demoResolve'];
constructor(demoResolve){
console.log(demoResolve)
var directive: ng.IDirective = {};
directive.link = (scope, element, attrs, ctrl) => {
};
directive.restrict = "EAC";
return directive;
}
}
}
but i am getting error of unknown provider
A: From reading their code it doesn't seem like it's possible, they have a local variable that they inject into the controller you define on the view, it's not accessible via $inject service as well.
Easiest solution would be to put it on the controller's scope, and then use it in the directive.
You can also create a real service, that will hold all the resolved objects in your application, i.e.:
resolve: {
demoResolve: ['myResolvingService', function(resolver) {
resolver.myValue = 'Foo';
return 'Foo';
}]
I know it's not what you were looking for, but it just doesn't look like it's supported.
A: Here is example how to pass resolve value to directive via controller:
.state('something.edit', {
url: '/:id',
template: '<something-edit title="title"></something-edit>',
controller: function($scope, $title){
$scope.title = $title;
},
resolve: {
$title: ()=>{
return 'Something Edit';
}
}
});
A: They added support for this in 2016.
This is the github thread:
https://github.com/angular-ui/ui-router/issues/2664#issuecomment-204593098
The important part is:
in 0.2.19 we are adding $resolve to the $scope, allowing you to do "route to component template" style
template: <my-directive input="$resolve.simpleObj"></my-directive>,
| |
doc_23537173
|
So can I take for instance:
*
*(Bob|Robert)( & | and)(Sally|Jane)
and have it processed to return a list/table such as:
*
*Bob and Jane, Bob & Jane, Bob and Sally, Bob & Sally, Robert and Jane, Robert & Jane, Robert and Sally, Robert & Jane
So I can then run a test on each output against the regex to see which returns a value? Clearly in the example all would work but the regex's I have have many 'pipes' and branches and I'd just like to get the entire list and be able to test to make sure ALL of them work.
A: Don't do this. For one thing, it's nearly impossible. It's literally impossible for an open-ended expression like .+ or \d+. Bob.+Jane, for example, matches infinitely many strings. So do many more subtle examples, like Hello World!+ or even \d{3,} (three or more digits).
In other words, identifying all possibilities is going to be extremely difficult or downright impossible for anything other than a trivial regex. For example, generating all possibilities for .{16} (that is, all 16-character strings) would result in 3.4 * 10^38 possibilities to check. And that's if you limit yourself to ASCII characters. If you check 1,000,000 strings per second, it will take 1.07 * 10^25 years, or about 13,820,512,820 times the estimated age of the universe. Also, good luck finding a hard drive to hold that much data. You would need to convert a large chunk of the earth into binary storage.
A better solution is to generate a bunch of realistic strings that you might actually encounter, then create unit tests using them. As you go forward, you may find additional cases that should work but don't. So, write a new test, then revise the regex until all tests (old and new) pass.
A: I think Ed Cottrell answered your question well as stated.
My interpretation is that your ultimate goal is to make it easier to read/interpret/debug your expression.
To that end, maybe you could use free spacing mode.
That would let you separate out groupings and sub expressions onto separate lines, complete with comments.
A: You can generate possible matches but it's not a good way to test regex. Whether you can generate all possible matches depends on the regex. I don't believe it's the problem people make it out to be though as you can limit output in a variety of ways. A regex pattern can easily be infinite or have a huge number of permutations. This means you need to do something for those cases.
I debug my regular expressions by reading more carefully, checking the manual, running tests on the command line and breaking them up into parts if I have to.
I don't know of any libraries for generating possible regex matches given a pattern. It's not very useful for testing unless you want something such as to create the first and last possible match. That or unless you have one of those giant single line huge nesting regexes such as the one that parses HTML or the even more complicated one for parsing email addresses. A lot of times people try to pack things into one regex that are better spread out for readability and reusability.
If you generate the first possible match, that might be useful for testing. You can also potentially extend that and not normally get too many results. It should not have problems with infinite patterns.
An infinite pattern will happen with +, *, {n,}. You can still have very large patterns without using any of those. {hugenumber,} is an obvious example. [^something] can also create a lot of permutations as well as [a-z]{8} which is 26^8. Most people before the regex do a count of the length so you can and should use that. It is difficult though as the length is distributed across each infinite operator and makes what's below a lot harder (unless you short circuit at the max length but you have to go far down a tree sometimes or have to traverse it first to work out those bounds if you do it like that). If you have a regex like this:
a+b+c+
With a maximum length of 5 it expands to:
a{3}b{1}c{1}
a{1}b{3}c{1}
a{1}b{1}c{3}
a{2}b{2}c{1}
a{2}b{1}c{2}
That'll increase exponentially as the max length increases.
If you have +, *, {n,} etc a cheap work around is to change + to {1,max}, * to {0,max} and {n,} to {n,max} where max is something reasonable. In reality, it's pretty rare you would expect an infinite string, there's got to be some reasonable limit, even if really high. It's not to max it so you can print your entire range but so that you at least have an upper bound to work with that's workable. You can still work somewhat with inf but it's not worth it.
I don't do this to test regex. Instead it works better as a generator for sequences. This can be used for password cracking, code generation, boiler plate generation, automation, etc. Care has to be taken to make sure the use is justified and not creating too much bloat. As in if you think you need to create a huge sequence for something, you might be using this as a way to achieve that level of bloat when there might be another approach to the problem.
Regex is under utilised in my opinion for generating ranges. For example, not many languages would let you express a range of all padded numbers of a given length with as little as:
\d{6}
This will generate 000000 to 999999. That's a million entries times 6 characters so 6MB at least. You can see with this that you'll rapidly create something that consumes a lot of memory. Wrapping the regex processor in an iterator is a good idea, especially one that can skip positions which should be possible with regex. To handle infinite sequences or huge, it's best to have a way to configure an implicit limit or maximum.
To start you'll want to parse your regex. You can do this yourself but if you want it for testing you'll want to use the parser for your specific platform and that is likely to be difficult as the internals are unlikely to be exposed to higher level languages. A generic parser can still be of use some as long as you're not doing anything too fancy.
If you want to make something that will support all kinds of complex possibilities in regex such as backreferences, etc then I would consider abandoning hope now.
Once you process it, the handing is quite simple:
(Bob|Robert) (&|and) (Sally|Jane)
[Bob,Robert] * [ ] * [&,and] * [ ] * [Sally,Jane]
It's the Cartesian products of the unions. It's a bit more complex when nested further.
abc?[zy]((xy|yz)(ab|ba)|xx)
[ [ab, abc] * [z, y] * [ [ [xy, yz] * [ab, ba] ], [xx] ] ]
ab * [, c] * [z, y] * [ [xy, yz] * [ab, ba], xx ]
The second alternative is if you explicitly encode the empty set which might be recommended to avoid bloat. You can represent the empty set a few ways. [, c] would break if [] but I'm not sure that [] is possible except for an empty regex or strange cases of malformed regex. You might also want to watch out for ambiguous regexes.
First match is just take the first of each range:
[ [ab] * [z] * [ [xy] * [ab] ] ]
[ [ab] * [z] * [xy] * [ab] ]
[ ab * z * xy * ab ]
[ ab, z, xy, ab ]
abzxyab
Reduce all down to one element, you can also do other indexes like random, as long as it reduces down to one. When all sets are length 1, the cartesian product operation becomes an append operation. I've used * instead of x for cartesian product as it is less confusing mixed with alpha characters.
You can calculate the number of combinations as such:
1 * 2 * 2 * [ 2 * 2 + 1 ]
2 * 2 * [ 2 * 2 + 1 ]
4 * 5
20
That is, you reduce each range to it's length. At this point that * operator becomes a real multiplication operator rather than cartesian product. A separator becomes a plus. You can see with this multiplication that the number of combinations can grow very quickly.
In your case it's 2*2*2 (8).
However, if you use the i flag for case insensitivity, it becomes:
(2^3 + 2^6) * (1 + 2^3) * (2^5 + 2^4)
31104
You can see that an AST for basic regex can be quite easy to build. It's nested arrays (arbitrary dimensions) with arbitrary length.
If you don't have infinite matches or have an implicit limit then you can convert everything into iterators. You'll want range iterators for things such as a-z.
The easiest way is to have aggregate iterators using an iterator interface. In your high level language you should have an easy way to wrap arrays into an iterator interface if they don't automatically implement one. Your high level language will likely provide an aggregate iterator as well.
You can recursively wrap each node in the tree like that (depth first is easiest) and then have a single iterator at the top that will represent 0 to the total number of permutations in your regex.
That's the simplest approach but if you dive in further and make more complex abstraction it's also possible dereference any part or create masks, etc. At this point it's not as simply. You might want to try variants in a certain order, etc.
A trick to work against an existing parser is to brute force. It's not a perfect art but can work in simply cases. If you want to resolve something like [a-zA-Z] you can try against your regex engine with all characters to see which match. This is not good at all when it comes to different character sets though. Only ascii regex. Character set is something important to consider. In unicode two dots alone can lead to millions of combinations.
Contrary to the impression being given here, while a regex expression can represent a very large search space, you do not have to explore all of it or generate all of it. You can map the regex to its parameters and jump to any specific part of it. You do not have to generate the entire search space to explore it.
Much of this you should be able to do in your head, as it is required to read and write regex that you understand. Your problem here is likely your white space. Too many people ignore whitespace as unimportant and fall into that trap. I recommend you set your IDE to subtly display whitespace.
Example from script I use that utilise the same concepts as above:
AST (simplified, ors flattened, single child scopes flattened parent, adjacent literals merged, consecutive ors into ranges):
["scope",
["literal", "x"],
["repeat", [0, 3], ["literal", "y"]],
["literal", "zfff"],
["range", "a", "d"]
["repeat",[4, 5], ["range", "0", "9"]],
["literal", "n"]
]
Expression: xy{,3}z(fff)(a|b|c|d)\d{4,5}n
Combinations: 1760000
Position 0: xzfffa0000n
Position 1: xzfffa0001n
Position 2: xzfffa0002n
Position Middle -1: xyzfffd99999n
Position Middle: xyyzfffa0000n
Position Middle + 1: xyyzfffa0001n
Position Last: xyyyzfffd99999n
Not that after a while regex patterns for matching diverges from regex for pattern generation. You'll not need many of the complex features in regex but you will want to add complex features not found in it.
This one demonstrates that you don't need to traverse the whole search space (it would be impossible to run on anything but the most powerful super computers otherwise):
AST (full):
["scope",
["repeat", [9],
["or",
["scope", ["range", "a", "z"]],
["scope", ["range", "A", "Z"]]
]
]
]
Expression: (\l|\L){9}
Combinations: 2779905883635712
Position 0: aaaaaaaaa
Position 1: aaaaaaaab
Position 2: aaaaaaaac
Position Middle -1: zZZZZZZZZ
Position Middle: Aaaaaaaaa
Position Middle + 1: Aaaaaaaab
Position Last: ZZZZZZZZZ
Note that without arbitrary precision integers much larger than this will break.
You can map your AST to objects to make life easier, where the first parameter is the object type and the others are the initialisation parameters. Your AST is almost like a configuration for dependency injection.
Here is the result for your regex:
AST (full):
["scope",
["or", ["scope", ["literal", "Bob"]], ["scope", ["literal", "Robert"]]],
["literal", " "],
["or", ["scope", ["literal", "&"]], ["scope", ["literal", "and"]]],
["literal", " "],
["or", ["scope", ["literal", "Sally"]], ["scope", ["literal", "Jane"]]]
]
Expression: (Bob|Robert) (&|and) (Sally|Jane)
Combinations: 8
Position 0: Bob & Sally
Position 1: Bob & Jane
Position 2: Bob and Sally
Position Middle -1: Bob and Jane
Position Middle: Robert & Sally
Position Middle + 1: Robert & Jane
Position Last: Robert and Jane
There a lot of other things you can do like give it the start of a regex and have it reverse that to an initial starting index.
Be wary of naysayers.
| |
doc_23537174
|
def action = UnsecuredAction(BodyParsers.parse.json).async { implicit request =>
// use json
}
This seems to be possible when using Play's build-in Action, but not with silhouette's UnsecuredAction and SecuredAction. Is there a way to do this without having to fall back to silhouette's (Un)SecuredRequestHandler or having to check manually if the body is actually JSON?
A: You can parse your request body to JSON by using async(parse.json).
For example:
def index = silhouette.SecuredAction.async(parse.json) { implicit request =>
// Write your code here...
}
| |
doc_23537175
|
A: Add this to your PYTHONPATH environment variable:
/usr/lib/python2.7/dist-packages/oauth/
| |
doc_23537176
|
For example:
1)I select Job with ID 3 and move it to the selectedJobs TreeView
2)I select Job with ID 1 and move it to the selectedJobs
Now what happens is that the order in the selectedJobs will be:
Job 3
Job 1
What i need is tht when i add Job with ID 1 it would go in from of the Job with ID 3.
I tried to use a custom Comparer:
public class IntegerComparer : IComparer
{
private int _colIndex;
public IntegerComparer(int colIndex)
{
_colIndex = colIndex;
}
public int Compare(object x, object y)
{
int nx = int.Parse((x as ListViewItem).SubItems[_colIndex].Text);
int ny = int.Parse((y as ListViewItem).SubItems[_colIndex].Text);
return nx.CompareTo(ny);
}
}
But the problem with that is that it puts Job with id 10, 11 etc before 2, 3 and etc..
A: You can use the sorting feature of the ListView:
http://msdn.microsoft.com/en-us/library/ms996467.aspx
or insetad of adding the job straight from the ListView1 to the ListView2 you could populate a list of LineItem(or a tailored object) ordered by Id and you could use that list as DataSource for the ListView2
A: You can use the custom sorting.To do this, you must implement IComparer class and set ListViewItemSorter property. Following link has a sample implementation:
http://csharpexamples.com/c-sort-listview-items-columns/
| |
doc_23537177
|
public class PrintUnicode {
public static void main(String[] args) {
System.out.println("Olá Mundo!");
}
}
I am using Eclipse, so I exported the project to a Runnable Jar File. After that, I went to cmd (Windows 7) and ran the generated jar file.
The result was:
Olß Mundo!
Is there an easy way to avoid this error?
A: Found the solution. Just change to:
public class PrintUnicode {
public static void main(String[] args) {
System.console().printf("Olá Mundo!");
}
}
The error with System.out happens because:
By default, Java encodes Strings sent
to System.out in the default code
page. On Windows XP, this means a
lossy conversion to an "ANSI" code
page. This is unfortunate, because the
Windows Command Prompt (cmd.exe) can
read and write Unicode characters. (source here)
| |
doc_23537178
|
1.Check if the instance has a tag "Terminate_On"
If yes:
2.Check if the instance should be terminated today
If yes:
3.Remove instance termination protection if enabled
Terminate the instance
I'm stuck on part 3: don't know how to remove protection if enabled
response=ec.modify_instance_attribute(instance_ids,"disableApiTermination", "true" )
File "/var/runtime/botocore/client.py", line 312, in _api_call
"%s() only accepts keyword arguments." % py_operation_name)
TypeError: modify_instance_attribute() only accepts keyword arguments.
If i modify as this one:
ec.modify_instance_attribute(InstanceIds=instance_ids,"disableApiTermination", "true" )
Then getting:
non-keyword arg after keyword arg (lambda_function.py, line 34)
import boto3
import collections
import datetime
import time
import sys
ec = boto3.client('ec2', 'eu-west-1')
ec2 = boto3.resource('ec2', 'eu-west-1')
from datetime import datetime
from dateutil.relativedelta import relativedelta
date_after_month = datetime.now()+ relativedelta(days=7)
#print date_after_month.strftime('%d/%m/%Y')
today=datetime.now().strftime('%d/%m/%Y')
def lambda_handler(event, context):
instance_ids = []
reservations = ec.describe_instances(
Filters=[
{'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']},
]
).get('Reservations', [])
for reservation in reservations:
instances = reservation['Instances']
for instance in instances:
instance_ids.append(instance['InstanceId'])
tags = {}
for tag in instance['Tags']:
tags[tag['Key']] = tag['Value']
if 'TerminateOn' in tags:
if tags["TerminateOn"]==today:
#remove termination protection if enabled
ec.modify_instance_attribute(instance_ids,"disableApiTermination", "true" )
#terminate instance
ec.terminate_instances(InstanceIds=instance_ids)
else:
print "No need for termination"
if not 'TerminateOn' in tags:
ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])
print("Stopping instances: {}".format(','.join(instance_ids)))
A: According to boto3 modify_instance_attribute documentation, try this (not tested code):
ec.modify_instance_attribute(
InstanceIds=instance_id,
DisableApiTermination={'Value': True})
| |
doc_23537179
|
I want to create a sidebar nav that is fixed on desktop and tablets, but collapses into a hamburger menu that is fixed to the top on mobile using Bootstrap 4. A lot of the examples I found used the now outdated affix property. The other examples were collapsible, but I want the sidebar to always be open on desktop and tablet. I attached photos of how I designed it on desktop and mobile for further reference.
A: I know you are asking about bootstrap, but since you anyway use external library for such thing, maybe this small script would be a solution for you. It does exactly what you need: https://github.com/grzegorzgit/Litomobile
If your menu is based on ul and li, this script automaticaly creates animated mobile menu and icon for the window size you want.
| |
doc_23537180
|
How can I modify this code so that on every ACTION_DOWN onTouchEvent() a circle is drawn on that point and previously drawn circle also not erased.
public class TestView3 extends View {
private static final String TAG = "TestView3";
Paint paint = new Paint();
float mX,mY;
public TestView3(Context context, AttributeSet attributeSet){
super(context);
Log.d(TAG, "TestView3: constructor called");
paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw: called");
//canvas.drawLine(0,0,20,20,paint);
//canvas.drawLine(20,0,0,20,paint);
canvas.drawCircle(mX,mY,10,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "onTouchEvent: Action_down happend");
mX = x;
mY = y;
break;
}
return true;
}
}
A: You have to store your circles in a list and draw each of them in the onDraw method.
The following edited code worked for me.
public class TestView3 extends View {
private static final String TAG = "TestView3";
Paint paint = new Paint();
float mX,mY;
Bitmap mBitmap;
Canvas mCanvas;
ArrayList<Point> arrayList = new ArrayList<>();
public TestView3(Context context, AttributeSet attributeSet){
super(context);
Log.d(TAG, "TestView3: constructor called");
paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "onDraw: called");
//canvas.drawLine(0,0,20,20,paint);
//canvas.drawLine(20,0,0,20,paint);
for(int i = 0;i < arrayList.size();i++){
Point point = arrayList.get(i);
canvas.drawCircle(point.x,point.y,10,paint);
// Draw line with next point (if it exists)
if (i + 1 < arrayList.size()) {
Point next = arrayList.get(i + 1);
canvas.drawLine(point.x, point.y, next.x, next.y, paint);
}
}
// canvas.drawCircle(mX,mY,10,paint);
}
/* protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}*/
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "onTouchEvent: Action_down happend");
mX = x;
mY = y;
arrayList.add(new Point((int)x,(int)y));
invalidate();
break;
}
return true;
}
}
| |
doc_23537181
|
I've run into the following problem: on IE7 only, if I call drawImage() after drawing anything to the canvas, excanvas does not draw the image at the desired x,y coordinates. I have looked on the excanvas project page/ google group, and found that there are known issues with the drawImage() function.
( for example: http://code.google.com/p/explorercanvas/issues/detail?id=104&q=IE7 )
I have tried restoring the identity matrix, as suggested here: Excanvas vml positioning issue , though it appears to have had no effect.
Attached is a simple html document demonstrating this issue:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="excanvas.js"></script>
<script type="text/javascript">
window.onload = function(){
var icon, ctx;
icon = new Image();
icon.width = "20";
icon.height = "20";
icon.src = "http://www.shangalulu.com/resources/images/icons/small/30.png";
icon.onload = function(){
var ctx;
ctx = document.getElementById('the_canvas').getContext('2d');
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(500,0);
ctx.lineTo(500,500);
ctx.lineTo(0,500);
ctx.lineTo(0,0);
ctx.moveTo(200,200);
ctx.lineTo(300,200);
ctx.lineTo(300,300);
ctx.lineTo(200,300);
ctx.lineTo(200,200);
ctx.moveTo(0,0);
ctx.lineTo(500,500);
ctx.moveTo(0,500);
ctx.lineTo(500,0);
ctx.stroke();
ctx.drawImage(icon, 190, 190, 20, 20);
ctx.drawImage(icon, 240, 240, 20, 20);
ctx.drawImage(icon, 290, 290, 20, 20);
return;
}
}
</script>
</head>
<body>
<canvas id="the_canvas" width="500" height="500"></canvas>
</body>
</html>
If you need the excanvas library to run this, you can grab it from here: http://code.google.com/p/explorercanvas/
The above script should do the following:
*
*it should draw an outline of the outer edges of the canvas (so you can see it)
*it should draw a 100x100 rectangle in the middle of the canvas.
*it should draw two lines that cross through the center of the canvas.
*it should draw three images: one on the top left corner of the inner box, one at the center, and one on the bottom right corner of the inner box.
What I would like to know is: Is there a known patch/workaround to this problem?
A: I've been pulling my hair on that one too...
I was only able to find a workaround, which works fine as long as you do not apply transformations before drawing your image. It implies that you replace the function drawImage in excanvas.js with that one:
contextPrototype.drawImage = function(image, var_args) {
var dx, dy, dw, dh, sx, sy, sw, sh;
// to find the original width we overide the width and height
var oldRuntimeWidth = image.runtimeStyle.width;
var oldRuntimeHeight = image.runtimeStyle.height;
image.runtimeStyle.width = 'auto';
image.runtimeStyle.height = 'auto';
// get the original size
var w = image.width;
var h = image.height;
// and remove overides
image.runtimeStyle.width = oldRuntimeWidth;
image.runtimeStyle.height = oldRuntimeHeight;
if (arguments.length == 3) {
dx = arguments[1];
dy = arguments[2];
sx = sy = 0;
sw = dw = w;
sh = dh = h;
} else if (arguments.length == 5) {
dx = arguments[1];
dy = arguments[2];
dw = arguments[3];
dh = arguments[4];
sx = sy = 0;
sw = w;
sh = h;
} else if (arguments.length == 9) {
sx = arguments[1];
sy = arguments[2];
sw = arguments[3];
sh = arguments[4];
dx = arguments[5];
dy = arguments[6];
dw = arguments[7];
dh = arguments[8];
} else {
throw Error('Invalid number of arguments');
}
/////////////////////////// MODIFIED BIT ///////////////////////////
var vmlStr = [];
vmlStr.push('<g_vml_:image src="', image.src, '"',
' style="position:absolute;',
' top:', dy, 'px;',
' left:', dx, 'px;',
' width:', dw, 'px;',
' height:', dh, 'px;"',
' cropleft="', sx / w, '"',
' croptop="', sy / h, '"',
' cropright="', (w - sx - sw) / w, '"',
' cropbottom="', (h - sy - sh) / h, '"',
' />');
/////////////////////////// END OF MODIFIED BIT ///////////////////////////
this.element_.insertAdjacentHTML('BeforeEnd',
vmlStr.join(''));
};
What it does is simply create a VML image directly inside the pseudo canvas, instead of wrapping it inside a group as it was originally done. For some reason, the original code was causing a left and top padding to appear around the image, and can't figure out why. Until we can understand the reason for that, we won't be able to find a proper fix...
| |
doc_23537182
|
java version "1.8.0_31"
Groovy Version: 2.4.0
Gradle 2.3
But i am getting this error when running the test.
Exception in thread "main" java.lang.NoClassDefFoundError: java/util/HashMap$Ent
ry
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2693)
Running a simple groovy script with above setup and the below Build.gradle is fine.
Build.gradle looks like this:
buildscript {
repositories {
jcenter()
}
}
apply plugin: 'java'
apply plugin: 'groovy'
repositories {
jcenter()
mavenCentral()
}
dependencies {
def seleniumVersion = "2.45.0"
def phantomJsVersion = '1.1.0'
// selenium drivers
compile "org.seleniumhq.selenium:selenium-firefox-driver:$seleniumVersion"
compile "org.seleniumhq.selenium:selenium-support:$seleniumVersion"
compile("com.github.detro.ghostdriver:phantomjsdriver:$phantomJsVersion") {
transitive = false
}
// geb
compile 'org.codehaus.geb:geb-core:0.7.2'
compile 'org.codehaus.geb:geb-spock:0.7.2'
// spock
compile 'org.spockframework:spock-core:0.6-groovy-1.8'
//junit
testCompile group: 'junit', name: 'junit', version: '4.7'
}
task runGebScript (dependsOn: 'classes', type: JavaExec) {
main = 'test'
classpath = sourceSets.main.runtimeClasspath
}
Can someone please help.
A: According to Gradle dependency report for the build you included, the Groovy version used for testCompile configuration is 1.8.5. Only groovy 2.x is JDK8 compatible. I would do as ataylor suggests and bump Spock version. If you use 1.0-groovy-2.4 then you'll be using Groovy 2.4.1. Also, I would suggest updating version of Geb while you're at it - the latest is 0.10.0. Your dependency versions are way out of date.
A: Something is trying to use the inner class HashMap.Entry, which no longer exists in Java 8. It's difficult to tell where without a complete stack trace.
However, you're using this version of spock: org.spockframework:spock-core:0.6-groovy-1.8. That version is not compatible with groovy 2.0+. Try updating the dependency to org.spockframework:spock-core:1.0-groovy-2.4.
| |
doc_23537183
|
My problem is when I am editing a xhtml file from my project and have a link to another file, when I go through it doing ctrl+click is bringing me to this target folder, when I obviusly want to go to the file which is into webapp directory. If I try to edit the file, Eclipse is warning me that is a derived file.
Is there a way to avoid that issue?
EDITED
That's my project's classpath content:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources/bundles"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources/classes/interna"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources/hibernate-mappings"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources/styles/headers/premium"/>
<classpathentry excluding="**" including="**/*.java" kind="src" output="target/classes" path="src/main/resources/styles/css/premium"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
A: I use a Working Set to exclude selected files/folders from Eclipse views.
You can create/modify/choose a Working Set in various ways, for example: on the toolbar of the Project Explorer, click the "View Menu" button to open the drop-down menu of display options; there you can select an existing working set from the list or create a new one by selecting "New...".
A: The target/m2e-wtp/web-resources folder contains "automatically generated resources", for example a filtered web.xml, so the file in the webapp directory (if any) could be not indentical to the one that is opened by Eclipse.
However check "What is this web resources folder?" and expecially "That web resources folder is causing me some trouble, can i get rid of it?".
| |
doc_23537184
|
The test code is as follows:
#include <iostream>
using namespace std;
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/algorithms/distance.hpp>
using namespace boost::geometry;
int main() {
cout << "!!!Hello World!!!" << endl;
model::d2::point_xy<int> p1(1, 1), p2(2, 2);
cout << "Distance p1-p2 is: " << distance(p1, p2) << endl;
return 0;
}
The error is as follows:
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_funcs.h:114:5:
required by substitution of 'template<class _InputIterator>
typename std::iterator_traits::difference_type
std::distance(_InputIterator, _InputIterator) [with _InputIterator
= boost::geometry::model::d2::point_xy<int>]'
..\src\test.cpp:22:50: required from here
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_types.h:166:53:
error: no type named 'iterator_category' in 'class
boost::geometry::model::d2::point_xy<int>'
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_types.h:167:53:
error: no type named 'value_type' in 'class
boost::geometry::model::d2::point_xy<int>'
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_types.h:168:53:
error: no type named 'difference_type' in 'class
boost::geometry::model::d2::point_xy<int>'
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_types.h:169:53:
error: no type named 'pointer' in 'class
boost::geometry::model::d2::point_xy<int>'
c:\program files\mingw64\bin\../lib/gcc/x86_64-w64-
mingw32/4.7.1/include/c++/bits/stl_iterator_base_types.h:170:53:
error: no type named 'reference' in 'class
boost::geometry::model::d2::point_xy<int>'
A: This is why you should be sparing with using-directives. You have:
using namespace std;
using namespace boost::geometry;
dragging all the names within these namespaces into the global namespace. That includes both std::distance and boost::geometry::distance and (judging from the error message) std::distance was chosen as the better overload.
If you remove using namespace std;, and qualify with std:: where necessary, then all should be fine. Alternatively, if you really want to keep the namespace pollution, then write the qualified name, boost::geometry::distance.
| |
doc_23537185
|
I have recently been doing a lot of work on the site and most recently decided to try to sort the history out for html4 browsers, in doing so I have checked the site in IE and found that a problem has developed with the way the data from some of the ajax calls is being displayed (only affecting IE - not FF).
The URLS are structured as follows:
sitename.dev/main_category/sub_category
if I just enter sitename.dev/main_category everything works fine but if I click the link for one of the sub categories at sitename.dev/main_category/sub_category the results are loaded but not displayed properly in IE. If I type the address into the browser for hard reload all works fine
WORKING (through hard reload):
Not working through ajax:
Because it is ajax loaded content I cannot inspect the dom, but my function appears to be firing correctly and the ajax call is returning the correct results.
Here is the code for my ajax call
function leftsort_click(event) { //main sort click (left menu)
var page = window.name, page_index,
api = $('#right_pane').jScrollPane({
showArrows: true,
maintainPosition: false
}).data('jsp');
if (!$(this).hasClass('sort_cat')) {
$('ul.sort_ul li, ul.cat_items li').removeClass('active');
$(this).addClass('active');
var sid = $(this).attr('id');
var title = $(this).html();
var loadUrlx= page;
if ((sid != '') && (sid != 'undefined')) {
loadUrlx += '/'+sid;
}
if($('.rpp_btn.active').length>=1){
var res_per_page = $.trim($('.rpp_btn.active').html());
page_index = $.trim($('.res_page_select.active a').html());
if (($('.rpp_btn.active').hasClass('just_clicked'))||(!$('.res_page_select').hasClass('just_clicked'))) {
page_index = '1';
}
if ((page_index != 1) || (res_per_page != 25)) {
loadUrlx += '/' + page_index + '/' + res_per_page;
}
$('.rpp_btn, .res_page_select').removeClass('just_clicked');
}
loadUrlx = b_url + loadUrlx;
if (History.enabled) {
History.pushState(null, null, loadUrlx);
}
$.ajaxSetup({
cache: false
});
$("#result_area").load(loadUrlx, function() {
$("#result_table").trigger("update");
api.reinitialise();
tsizer();
});
}
}
Any help or suggestions would be very much appreciated
A: worked this one out, i was injecting a div into a tbody - Ie's not happy about that.
| |
doc_23537186
|
HTML code:
<form action="/flight_ticket/book" name="myform" method="post">
.
.
.
Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
<a href="#" id="names" onclick="addFields();">Enter names</a>
<div id='container'/>
</div>
<br/><br/>
</form>
</body>
JS code:
function addFields(){
var number = parseInt(document.getElementById("nooftickets").value);
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Name " + (i+1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
But when I run it on browser, after clicking the "Enter names", I don't see any changes in the browser!
What have I got wrong?
A: What you are doing is trying to fetch the value of the noofticktes which is defined as a name in the HTML but in your code, you are using document.getElementById('noofticktes').value which is throwing an undefined error as there is no id defined as noofticktes.
So, just change your code on from:
var number = document.getElementById("nooftickets").value;
To this:
var number = document.getElementsByName("nooftickets")[0].value;
you will be able to make your code work.
One small update in your code would be if you are trying to clear/remove all the contents of the element container just use the container.innerHTML='' instead of looping and removing each element.
Here is the updated Snippet of your code.
function addFields() {
debugger;
var number = document.getElementsByName("nooftickets")[0].value;
var container = document.getElementById("container");
container.innerHTML = '';
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Name " + (i + 1)));
var input = document.createElement("input");
input.type = "text";
input.name = "name" + i;
//input.required= true;
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
<form action="/flight_ticket/book" name="myform" method="post">
. . . Enter the number of tickets to be booked:
<input name="nooftickets" type="text"><br/><br/>
<a href="#" id="names" onclick="addFields();">Enter names</a>
<div id='container' />
</div>
<br/><br/>
</form>
A:
function addFields() {
// body...
var input = '';
var number = document.getElementById('number').value;
for(var i=0;i<number;i++)
{
input +="<input id='number"+i+"' name='number"+i+"'><br>";
}
document.getElementById('container').innerHTML = input;
}
<form action="/flight_ticket/book" name="myform" method="post">
Enter the number of tickets to be booked:
<input name="nooftickets" id="number" type="text"><br/><br/>
<a href="#" id="names" onclick="addFields();">Enter names</a>
<div id='container'/>
</div>
<br/><br/>
</form>
| |
doc_23537187
|
A: Do you mean creating SQLite database? The SQLiteDatabase::openOrCreateDatabase() will create sqlite database and it's part of the android SDK:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
| |
doc_23537188
|
But in here i'm having a trouble to get a list of UserRole's user list ( Supervisors).
My View
@Html.DropDownList("drpsup", ViewBag.SupervisorList as System.Web.Mvc.SelectList, "-- Select Supervisor--", new { @class = "form-control", id = "drpdsuplst" })
My Model
public class Supervisors
{
public int UserId { get; set; }
public string UserName { get; set; }
}
My Controller
public ActionResult InterviewerManagement()
{
UserBusiness _ub = new UserBusiness();
var sRole =_ub.GetSupervisors();
ViewBag.SupervisorList = new SelectList(supList, "UserId", "UserName", 0);
My Business Class
public IList<Supervisors> GetSupervisors()
{
var AllUsr = iuserrepository.GetList(x => x.UserId != null);
var xRole = irolerepository.GetSingle(x => x.RoleName.Equals("Supervisor"));
var yRole = iusersinrolerepository.GetList(x => x.RoleId.Equals(xRole.RoleId));
// var supRole = iuserrepository.GetList(x => x.UserId != null).Select(x=>x.UserId.Equals(yRole.Where(d=>d.)).ToList();
return supRole;
}
return View();
}
In my business class i just comment var supRole.... i know littlefix to it solve the problem.But o have no idea to do it.
| |
doc_23537189
|
{
"name": "vendor/Project",
"description": "description_text",
"repositories": [
{
"type": "pear",
"url": "http://pear.php.net"
}
],
"require": {
"jakeasmith/http_build_url": "dev-master",
"phpmailer/phpmailer": "dev-master",
"pear-pear/Text_Diff": "*",
"pear-pear/Net_IDNA2": "*",
"pear-pear/HTTP_Request2": "2.2.1"
},
"require-dev": {
"phpunit/phpunit": "< 4.0.0"
}
}
And when I'm trying to execute command php composer.phar install I got this:
Loading composer repositories with package information
Initializing PEAR repository http://pear.php.net
Installing dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for pear-pear/http_request2 2.2.1 -> satisfiable by pear-pear.php.net/HTTP_Request2[2.2.1].
- pear-pear.php.net/HTTP_Request2 2.2.1 required pear-pear.php.net/net_url2 >=2.0.0.0 -> no matching package found.
Potential causes:
- A typo in the package name
- The package is not available in a stable-enough version according to your minimum-stability setting
see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.
Read <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.
Why I'm getting an error? should I really store all pear dependencies in my composer.json file for the HTTP_Request2 extension?
P.S. If I run php composer.phar install with
"pear-pear/Archive_Tar": "*",
"pear-pear/Console_Getopt": "*",
"pear-pear/Structures_Graph": "*",
"pear-pear/XML_Util": "*",
"pear-pear/PEAR": "*",
"pear-pear/Net_URL2": "*"
and after this add a string: "pear-pear/HTTP_Request2": "2.2.1" and run php composer.phar update - everything is work like a magic! But I don't think that this is the right way.
A: Fixed by renaming:
"pear-pear/HTTP_Request2": "2.2.1"
to
"pear-pear.php.net/HTTP_Request2": "2.2.1"
| |
doc_23537190
|
By the way I have a loop in my pl/sql procedure that will call the java procedure multiple times (i.e. my code is flipping between PL/SQL and Java Stored Procedures), so does this slow down the performance)?
A: Any switch from one language to another will involve an overhead (it might be small but it'll still be there). If it's in a loop it will be accentuated.
Keep it simple and if you can stick to PL/SQL then do so.
Tom Kyte (Oracle Corporation Vice President and Guru) has a mantra which seems fitting to repeat here:
(Reference: http://tkyte.blogspot.com/2006/10/slow-by-slow.html)
*
*You should do it in a single SQL statement if at all possible.
*If you cannot do it in a single SQL Statement, then do it in PL/SQL.
*If you cannot do it in PL/SQL, try a Java Stored Procedure.
*If you cannot do it in Java, do it in a C external procedure.
*If you cannot do it in a C external routine, you might want to seriously think about why it is you need to do it…
| |
doc_23537191
|
I have an app with a pretty large user base. The app uses profiles. The profiles are are deserialized from file when starting the app.
In new releases the profile class sometimes gets new properties. If the profile is deserialized from an older version these properties will be uninitialized. Where as they will have some set default values if the profile is created with the current version of the app.
Is there a simple way of initializing a property with a default value if the serialized version doesn't have it?
A: You can specify a method to run after deserializing where you could set default values:
using System.Runtime.Serialization;
[Serializable]
class Car
{
public int Id { get; set; }
public string Make { get; set; }
public int Doors { get; set; }
public string Foo { get; set; } // added property
...
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
if (string.IsNullOrEmpty(this.Foo))
this.Foo = "Ziggy";
}
}
You might want to consider ProtoBuf-NET which is a data contract binary serializer. It is much more flexible about these things, more options, faster and creates smaller output. I just double checked to be sure, and ProtoBuf will not undo fields it doesnt have information for. So:
[ProtoContract]
class Car
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Make { get; set; }
[ProtoMember(3)]
public int Doors { get; set; }
[ProtoMember(4)]
public string Foo { get; set; } // new prop
public Car()
{
this.Foo = "Ziggy";
}
...
}
If there is no serialized value for Foo, the old value from the ctor is retained. So you could initialize new properties there and not have to worry about them getting reset to null. If you have a lot of properties like Bitmap, Font and Rectangle you might want to stay with the BinaryFormatter.
| |
doc_23537192
|
I'm using the iText library to create a pdf template and Primefaces to display the content on a web application.
When I ran the first test to see if all the libraries were all set, it was displayed normally. But then I made some changes, and it seems that something is caching my first test in memory and it is the only thing displayed, no matter what changes I make it keeps the same first content. I´ve already cleaned up my netbeans project, closed the IDE and also restarted the computer.
Thats is my tag on the jsf page:
<p:media value="#{atividadeController.pdfContent}" player="pdf" width="100%" height="700px"/>
And here is my method in the managed bean, which is a SessionScoped:
public String preparePdf()
{
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Font fontHeader = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
Font fontLine = new Font(Font.FontFamily.TIMES_ROMAN, 14);
Font fontLineBold = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
//Writing document
Chunk preface = new Chunk("GERAL", fontHeader);
document.add(preface);
Calendar cal = Calendar.getInstance();
cal.setTime(current.getData());
int year = cal.get(Calendar.YEAR);
int month = 1 + cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String dateStr = day+"/"+month+"/"+year;
Paragraph dataAndHour = new Paragraph(dateStr, fontLine);
document.add(dataAndHour);
document.close();
pdfContent = new DefaultStreamedContent(new ByteArrayInputStream(output.toByteArray()), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
return "/views/view_atividade_pdf";
}
There is no exception on the server log.
I really aprecciate any help. Thanks in advance
| |
doc_23537193
|
A: There's the set P of decision problems that can be solved by a deterministic Turing machine in polynomial time.
Then there's the set NP of decision problems that can be solved by a non-deterministic Turing machine in polynomial time, i.e. those whose solution can be verified in polynomial time given some witness string.
A deterministic Turing machine can simulate a non-deterministic one, so we know that there is an exponential-time algorithm to solve NP problems. We don't know however whether we don't in fact have P = NP.
An NP-complete problem is an NP problem that is at least as hard as any other NP problem. For example, SAT is NP-complete because it can effectively encode a non-deterministic Turing machine and solving SAT means simulating that machine. You can show NP-completeness of a problem decision problem A by demonstrating that a previously known to be NP-complete problem B can be reduced to A in polynomial time. This means that if A can be solved in polynomial time, B can be solved in polynomial time too, thus in a sense A is at least as hard as B.
but we have some NP problems which can be solved in polynomial time as well
Exactly, because P is a subset of NP.
NP complete problems can't be solved in polynomial time
We don't know that for sure.
doesn't this contradict the property of calling NP complete problems to be NP
Not at all. Yes there are problems in NP that we know to be also in P. That doesn't mean that there are no problems in NP that are not in P. But of course we don't know the latter. It could even be the case that every NP-complete problem is in P, in the case P = NP.
| |
doc_23537194
|
pecl install PDO_DBLIB
and I get the follow message
pear/PDO_DBLIB requires PHP extension 'pdo' version >=1.0
But in http://php.net/manual/es/ref.pdo-dblib.php, it says that is an EXPERIMENTAL pdo, so do you know another PDO that I can use to conect with sql server in CentOS 5
Thanks to every one!
A: See this bug report on php.net. One of the comments includes steps to get around this particular problem. Basically the work around is to download the package, modifying the package.xml to remove the dependency, and then attempt to install the package locally
$ pecl download pdo_dblib
$ tar -xzvf PDO_DBLIB-*.tgz
Remove from package.xml and save:
<dep type="ext" rel="ge" version="1.0">pdo</dep>
$ mv package.xml ./PDO_DBLIB-X.X
$ cd PDO_DBLIB-X.X
$ pecl install package.xml
Or, you can just tell PECL to skip dependencies...
$ pecl install -n pdo_dblib
| |
doc_23537195
|
private static void SetLastModifiedTimeUser<TEntity>(TEntity entity) where TEntity : class
{
PropertyInfo propertyInfo;
propertyInfo = entity.GetType().GetProperty("LastModifiedUser");
if (propertyInfo != null)
propertyInfo.SetValue(entity, IdentityHelper.UserName, null);
}
As you can see, the method accepts a generic type. Every class passed to this method will contain a property named 'LastModifiedUser'. Is there a way I can access this property without using reflection? I don't think there is, but I thought I'd ask.
A: Yes, if all your entities have LastModifiedUser property, then you can make all entities inherit from base class, or implement some interface like
public interface IModifyable
{
string LastModifiedUser { get; set; }
}
Then just add this constraint (or make your method non-generic, accepting IModifyable)
where TEntity : class, IModifyable
And your code will look like:
private static void SetLastModifiedTimeUser<TEntity>(TEntity entity)
where TEntity : class, IModifyable
{
entity.LastModifiedUser = IdentityHelper.UserName;
}
A: Have your class inherit from an interface that defines a LastModifiedUser property.
public interface ILastModifiedUser
{
public string LastModifiedUser { get; set; }
}
Change your method declaration to
private static void SetLastModifiedTimeUser(ILastModifiedUser entity)
A: If you can't modify all the classes to implement a common interface you can use dynamic
private static void SetLastModifiedTimeUser<TEntity>(TEntity entity) where TEntity : class
{
dynamic d = entity;
d.LastModifiedUser = IdentityHelper.UserName;
}
Otherwise it is as simple as shown by Robert Harvey.
A: If you can't add an interface to your objects, consider this approach.
The first time it encounters each Type (TEntity), it looks up the property and gets the property's SetMethod. Then, on each use, it creates invokes the method.
var one = new EntityOne();
LastModifiedTimeUserSetter.Set(one);
Console.WriteLine(one.LastModifiedUser);
public static class LastModifiedTimeUserSetter
{
public static void Set<TEntity>(TEntity entity)
{
var method = Properties.GetOrAdd(typeof (TEntity), GetSetMethod);
var action = (Action<string>) Delegate.CreateDelegate(typeof (Action<string>), entity, method);
action(IdentityHelper.UserName);
}
static MethodInfo GetSetMethod(Type type)
{
var prop = type.GetProperty("LastModifiedUser");
if (prop == null)
return null;
return prop.GetSetMethod();
}
static readonly ConcurrentDictionary<Type, MethodInfo> Properties = new ConcurrentDictionary<Type, MethodInfo>();
}
Going further
There is a way to further improve performance by using the System.Reflection.Emit.MethodBuilder. And building a method that takes Entity and sets the property.
public static class LastModifiedTimeUserSetter
{
public static void Set<TEntity>(TEntity entity)
{
var action = (Action<TEntity>) Properties.GetOrAdd(typeof(TEntity), CreateDynamicSetMethodDelegate);
if(action != null)
action(entity);
}
static Delegate CreateDynamicSetMethodDelegate(Type type)
{
return CreateDynamicSetMethod(type).CreateDelegate(GetActionType(type));
}
static DynamicMethod CreateDynamicSetMethod(Type typeWithProperty)
{
var methodBuilder = new DynamicMethod(
"Dynamic_" + typeWithProperty.FullName + "_SetLastModifiedUser",
typeof (void),
new[] {typeWithProperty});
EmitSimpleAssignmentMethod(methodBuilder,
GetIdentityHelperUserNameGetMethod(),
GetPropertySetMethod(typeWithProperty));
return methodBuilder;
}
static MethodInfo GetIdentityHelperUserNameGetMethod()
{
return typeof(IdentityHelper).GetProperty("UserName").GetGetMethod();
}
static MethodInfo GetPropertySetMethod(Type type)
{
var prop = type.GetProperty("LastModifiedUser");
if (prop == null)
return null;
return prop.GetSetMethod();
}
static void EmitSimpleAssignmentMethod(DynamicMethod methodBuilder, MethodInfo getMethod, MethodInfo setMethod)
{
var il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Call, getMethod, null);
il.EmitCall(OpCodes.Call, setMethod, null);
il.Emit(OpCodes.Ret);
}
static Type GetActionType(Type type)
{
return typeof (Action<string>).GetGenericTypeDefinition().MakeGenericType(type);
}
static readonly ConcurrentDictionary<Type, Delegate> Properties = new ConcurrentDictionary<Type, Delegate>();
}
See an Article from MSDN magazine about XBOX Live.
| |
doc_23537196
|
Jupyter notebook snapshot
for the .ipynb file:
https://mega.nz/file/m25R2QZb#21OKd7DTASEmOymuFcOiOQwZaf8fhMzHLeQc8XzyKUI
Anybody know how to avoid this error, thanks for replying .
A: In your code, you give the DataFrame x to the fit function. If you check closely, the first zipped item in the loop for xi, target in zip(X, y): is the column names, not the first data item. You can check that by printing xi in the loop.
So what you want to do is convert your data to an array beforehand:
x=np.array(df.iloc[0:100 , [0,2]])
or alternatively what you did for the targets y as well, use only the values of the DataFrame:
x=df.iloc[0:100 , [0,2]].values
| |
doc_23537197
|
The response looks like as below :
//OK[25,24,23,22,21,20,19,8,8,8,8,8,18,17,16,15,14,8,13,12,11,10,9,9,8,8,8,7,4,6,5,4,3,2,34,1,["[Ljava.lang.String;/2600011424","17501-20000-39010","1152963","Not Available","Open","2222","01/15/2012","0.00","1663.07","02/09/2012","02/15/2012","4446.36","2783.29","2038.71","02407.65","03/11/2012","486.76","07135.7900","0","01/26/2012","001122 AAA BBB CCC","1","Y","01/23/2012","E"],0,5]
Though the content type is application/json in the response, I am not sure on how to process this JSON format.
Any help is appreciated.
A: Check JSON in Java. Should be pretty easy to use.
A: That isn't actually JSON, but if you strip off the //OK from the front then it would be.
Strip through characters then run it through a JSON parser. Several are listed just after the diagrams on the JSON homage.
| |
doc_23537198
|
import React, { useState } from "react";
const App = () => {
const [students, setStudents] = useState([
{ id: 1, title: "Akita from place1", race: "Akita", gender: 'female' },
{ id: 2, title: "Akita from place2", race: "Akita", gender: 'female' },
{ id: 3, title: "Akita from place3", race: "Akita", gender: 'female' },
{ id: 4, title: "Chihuahua from place4", race: "Chihuahua" , gender: 'male' },
{ id: 5, title: "Cockapoo from place5", race: "Cockapoo" , gender: 'male'},
{ id: 6, title: "Dachshund from place6", race: "Dachshund", gender: 'male' },
{ id: 7, title: "Dutch Shepherd from place7", race: "Dutch Shepherd" , gender: 'female' },
{ id: 8, title: "Bulldog from place8", race: "Bulldog", gender: 'male' },
{ id: 9, title: "Goldador from place9", race: "Goldador", gender: 'female' },
]);
const filterData = (e: any) => {
console.log(e.target.value);
if (e.target.value === "male") {
const filteredData = students.filter((student) => {
return student.gender === "male";
});
setStudents(filteredData);
}
if (e.target.value === "female") {
const filteredData = students.filter((student) => {
return student.gender === "female";
});
setStudents(filteredData);
}
};
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData} />
Female: <input type="checkbox" name='female' value='female' onChange={filterData} />
{students
.map((student: any) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
export default App;
A:
const {
useState
} = React;
const App = () => {
const [students, setStudents] = React.useState([{
id: 1,
title: "Akita from place1",
race: "Akita",
gender: 'female'
},
{
id: 2,
title: "Akita from place2",
race: "Akita",
gender: 'female'
},
{
id: 3,
title: "Akita from place3",
race: "Akita",
gender: 'female'
},
{
id: 4,
title: "Chihuahua from place4",
race: "Chihuahua",
gender: 'male'
},
{
id: 5,
title: "Cockapoo from place5",
race: "Cockapoo",
gender: 'male'
},
{
id: 6,
title: "Dachshund from place6",
race: "Dachshund",
gender: 'male'
},
{
id: 7,
title: "Dutch Shepherd from place7",
race: "Dutch Shepherd",
gender: 'female'
},
{
id: 8,
title: "Bulldog from place8",
race: "Bulldog",
gender: 'male'
},
{
id: 9,
title: "Goldador from place9",
race: "Goldador",
gender: 'female'
},
]);
const [filtered, setFiltered] = useState([])
const filterData = (e) => {
const {value, checked} = e.target;
//check if value not in state and checked is true then add value to state
if(!filtered.includes(value) && checked){
setFiltered([...filtered, value])
}else{
setFiltered(filtered.filter(f=>f!==value))
}
};
const filteredStudent = filtered.length > 0 ? students.filter(s => filtered.includes(s.gender)) : students;
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData}/>
Female: <input type="checkbox" name='female' value='female' onChange={filterData}/>
{filteredStudent
.map((student) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render( <
App / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
A: It does not work because you are filtering all the female out and updating the state, this means that after clicking one button once, the filtered values does not exist in state anymore. To fix this, you could track the filter type in state and derive the filtered students during render.
Note that you could use radio buttons so only one gender can be selected at a time.
import React, {useState} from "react";
const App = () => {
const [students, setStudents] = useState([
{id: 1, title: "Akita from place1", race: "Akita", gender: 'female'},
{id: 2, title: "Akita from place2", race: "Akita", gender: 'female'},
{id: 3, title: "Akita from place3", race: "Akita", gender: 'female'},
{id: 4, title: "Chihuahua from place4", race: "Chihuahua", gender: 'male'},
{id: 5, title: "Cockapoo from place5", race: "Cockapoo", gender: 'male'},
{id: 6, title: "Dachshund from place6", race: "Dachshund", gender: 'male'},
{id: 7, title: "Dutch Shepherd from place7", race: "Dutch Shepherd", gender: 'female'},
{id: 8, title: "Bulldog from place8", race: "Bulldog", gender: 'male'},
{id: 9, title: "Goldador from place9", race: "Goldador", gender: 'female'},
]);
const [filter, setFilter] = useState<null | string>(null)
const filterData = (e) => {
setFilter(e.target.checked ? e.target.value : null)
};
const filteredStudent = filter ? students.filter(s => s.gender === filter) : students;
return (
<div>
<h3>app</h3>
Male: <input type="checkbox" name='male' value='male' onChange={filterData}/>
Female: <input type="checkbox" name='female' value='female' onChange={filterData}/>
{filteredStudent
.map((student) => {
return (
<div key={student.id}>
{student.id}-{student.title}-{student.race}-{student.gender}
</div>
);
})}
</div>
);
};
export default App;
| |
doc_23537199
|
Status |= (int)states.Reading;
What is the "|=" operator in C#?
"Status" is defined thusly:
public static int Status
...with an accessor and mutator (or "getter" and "setter"), while "states" is defined this way:
[Flags]
public enum states
A: While using the enumerators if you have specified [Flags] attribute on top of an "enum" member, this enables the user to select more than one enumerators in a single go.
What I mean is this:-
if this is your enumerator:-
[Serializable, DataContract(Namespace = "Company.Domain.LOB.Handler")]
[Flags]
public enum BankItemStatus
{
[EnumMember]
UnBatched,
[EnumMember]
Batched,
[EnumMember]
Sent,
[EnumMember]
ReplyReceived,
[EnumMember]
Closed
}
Now if you use the Enum like this:-
BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
BankItemStatus bankItemStatus = BankItemStatus.Sent;
The final value preserved by bankItemStatus would be BankItemStatus.Sent.
You can check it like this:-
if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //FALSE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE
Now if you do it like this:-
BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
bankItemStatus |= bankItemStatus.Sent
You will see that bankItemStatus now has both the enum members.
You can check it like this:-
if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //TRUE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE
Hope that helps in understanding the use of |= operator in C# (in context of Enumerators).
A: It's the "bitwise logical OR" operator, as defined here.
x |= y is equivalent to x = x | y
Also, if you want to learn more about the "|" operator itself, you can do so here.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.