text
stringlengths 0
13M
|
---|
Title: Array won't load when you first click on the link Angularjs?
Tags: javascript;jquery;arrays;angularjs;json
Question: ```// SETTING UP SERVICES
app.service("PictureService", function($http) {
var Service = {};
Service.pictureLinkList = [];
// GETTING PICTURE LINKS FOR PAGE
$http.get("data/img_location.json")
.success(function(data) {
Service.pictureLinkList = data;
})
.error(function(data,status) {
alert("Things went wront!");
});
Service.findImgById = function(id) {
for(var item in Service.pictureLinkList) {
if(parseInt(Service.pictureLinkList[item].id) === parseInt(id)) {
return Service.pictureLinkList[item];
}
}
}
return Service;
});
// COMMENT SERVICE START*****************************************
app.service("CommentService", function($http) {
var comService = {};
comService.commentList = [];
// GETTING COMMENTS FROM JSON FILE
$http.get("data/comments.json")
.success(function(response){
comService.commentList = response;
for(var item in comService.commentList){
comService.commentList[item].date = new Date(comService.commentList[item].date).toString();
}
})
.error(function(data,status){
alert("Things went wrong!");
});
comService.findCommentById = function(id) {
var comArr = [];
for(var item in comService.commentList) {
if(parseInt(comService.commentList[item].imgId) === parseInt(id)) {
comArr.push(comService.commentList[item]);
}
}
return comArr;
};
return comService;
});
// Controller
app.controller("pictureDetails", ["$scope", "PictureService", "CommentService", "$routeParams", function($scope, PictureService, CommentService, $routeParams) {
$scope.imgById = PictureService.findImgById($routeParams.id);
$scope.commentsById = CommentService.findCommentById($routeParams.id);
}]);
```
Here is the HTML:
```<ul>
<li ng-repeat="item in commentsById">
<div class="panel panel-primary text-center"><h3>Posted by: {{ item.postedBy }} at </h3><p>{{ item.date }}</p></div>
<div class="panel-body text-center">{{ item.comment }}</div>
</li>
```
Comments.json file:
``` [
{"id": 1, "imgId": 1, "comment": "Pretty good sketching there pal!", "date": "October 1, 2014 11:13:00", "postedBy": "John"},
{"id": 2, "imgId": 1, "comment": "Nice one keep working on your skills", "date": "January 17, 2016 11:48:00", "postedBy": "John"}
]
```
First of all, I have just started using Angularjs and really like it as a framework. The problem is when I load the html page $http service reads the json file and returns objects which gets assigned to an array. Then i use ng-repeat to go through the array and read values.
When i load the page first time the array is empty, i click on a link and go back then the array and the page gets loaded. why is that?
If I am not clear with my question please let me know. Any help is greatly appreciated.
Here is the accepted answer: ```$scope.$watch( function(){ return CommentService.commentList; }, function(comments) {
for(var item in comments) {
if(parseInt(comments[item].imgId) === parseInt($routeParams.id)) {
$scope.commentsById.push(comments[item]);
}
}
console.log($scope.commentsById);
});
$scope.commentsById = [];
```
adding this piece to the controller worked, was reading a book on Angularjs and they explained it like $watch variables watches any given array and assigns it to anything.
If need more explanation let me know. It works perfectly now, i click on it once and the comments are loaded. Loads the whole comment array in one attempt.
|
Title: Ignore a multiple occurrence of a tag while comparing using xmlUnit
Tags: regex;xml;xmlunit
Question: I have an XML file which looks like below.
Expected XML
```<doc>
<tag>
<file>a.c</file>
<line>10</line>
<type>c</type>
<tag>
<tag>
<file>b.h</file>
<line>14</line>
<type>h</type>
<tag>
<tag>
<file>d.he</file>
<line>49</line>
<type>he</type>
<tag>
</doc>
```
Now XML for testing
```<doc>
<tag>
<file>a1.c</file>
<line>10</line>
<type>c</type>
<tag>
<tag>
<file>b1.h</file>
<line>14</line>
<type>h</type>
<tag>
<tag>
<file>d1.he</file>
<line>49</line>
<type>he</type>
<tag>
</doc>
```
I want to compare this file with another XML file which has same structure.
I am using xmlUnit for comparison. While comparing I want to ignore XML tag ```<file>```
Below is the comparison code which I wrote
```public static Diff compareXML(String expXMLPath, String genXMLPath)
throws IOException, SAXException {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
final List<String> ignorableXPathsRegex = new ArrayList<String>();// list of regular expressions that custom difference listener used during xml
//comparison
ignorableXPathsRegex
.add("\\/doc\\[1\\]\\/tag\\[1\\]\\/file\\[1\\]\\/text()");
Diff diff = null;
try(FileInputStream fileStream1 = new FileInputStream(expXMLPath)) {
try(FileInputStream fileStream2 = new FileInputStream(genXMLPath)) {
InputSource inputSource1 = new InputSource(fileStream1);
InputSource inputSource2 = new InputSource(fileStream2);
diff = new Diff(inputSource1, inputSource2);
RegDiffListener ignorableElementsListener = new RegDiffListener(
ignorableXPathsRegex);
diff.overrideDifferenceListener(ignorableElementsListener);
return diff;
}
}
}
```
This is not working if XML file has more than one ```<tag>...</tag>``` block. I basically need a regex here which ignores all the ```<file>``` tag which are under ```<doc><tag>```
I want the comparison of expected and test XML to show that both are same by ignoring the value of file tag, so ```diff.similar()``` should return ```true```
Please suggest how to do it.
Comment: I found the solution. ignorableXPathsRegex
.add("\\/doc\\[1\\]\\/tag\\[1\\]\\/file\\[1\\]\\/text()"); tells to check only for the first tag. We should use ignorableXPathsRegex
.add("\\/doc\\[1\\]\\/tag\\[\\d*\\]\\/file\\[1\\]\\/text()"); to ignore all the inside all the
Comment: It would be easier to understand your goal if you added the expected result compared to your file structure.
Here is another answer: I found the solution.
```ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[1\]\\/file\[1\]\\/text()");
```
tells to check only for the first tag.
We should use
```ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[\\d+\]\\/file\[1\]\\/text()");
```
to ignore all the ```<file>``` inside all the ```<tag>```
|
Title: Write to file, keep changes and append to them
Tags: fortran;fortran90;gfortran
Question: I have a program that creates values for the matrix ```u```, and this changes for every iteration ```f```, I want to write out the value of ```u(2,2)``` for every iteration ```f```. So for example ```u(2,2)=5 f=1```, ```u(2,2)=9 f=2```, and so on.
Now ```test(u,n,f)``` only writes the last value.When it have met my criteria to stop the do loop. I don't want my subroutine to overwrite the file plot.txt every time, I want it to keep ```u(2,2)``` for every iterations. I want it to look like this
```5 1
9 2
10 3
```
but not it only writes
```15 25
```
How can this be fixed?
```subroutine test(u,n,f)
!input
integer 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 n,f,write_unit
real(8) 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 u(n+2,n+2)
!lokale
integer 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 i,j
real(8) 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 vek_x,vek_y
!Skriver vektor verdier til fil som gnuplot skal bruke
open(newunit=write_unit,access='sequential',file='plot.txt',status='unknown')
write(write_unit,*)'# x y vx vy'
vek_x=u(2,2)
!write(write_unit,*) vek_x,f
write(write_unit,*) vek_x,f
write(write_unit,*)''
close(write_unit,status='keep')
```
"Program" that creates different values for ```u```
```do f=1,1000
do j=2,n+1
do i=2,n+1
u(i,j)=(u(i+1,j)+u(i-1,j)+u(i,j+1)+u(i,j-1))/4
!u(i,j)=(1-omega)*u(i,j)+omega*1/4*(u(i+1,j)+u(i-1,j)+u(i,j+1)+u(i,j-1))
end do
end do
if (u(2,2) .eq. 15) then
exit
end if
call test(u,n,f)
end do
```
Here is the accepted answer: Just open the file for appending
```open(newunit=write_unit,access='sequential',file='plot.txt',position='append',status='old',action='write')
```
if that is what you wanted.
For the first time to may want to just create it empty
```open(newunit=write_unit,access='sequential',file='plot.txt',status='replace')
close(write_unit)
```
|
Title: Coin Flip Simulator - Python
Tags: python
Question: I started learning python (it is also the first programming language I am learning) about 6 weeks ago, and I am working on various small projects for practice.
On this one, I am trying to build a coin flip simulator that will keep asking the player to toss the coin until they say no and returns the results in a dictionary, see code below
The problem with my code is that when I type "no" to break out of the while loop it calls coin_flip() once more, and I do not understand why. E.g. if the player plays 4 times, the program tosses the coin 5 times.
Also, I am using this project as a means to practice while loops, so if you could troubleshoot along those lines, I would appreciate it greatly.
Thanks in advance!
import random
```def coin_flip():
if random.randint(0, 1) == 1:
return 'Head'
else:
return 'Tails'
def coin_flip_simulator():
coin_dict = {'Head': 0, 'Tails': 0}
ask_play = input('Would you like to flip a die? Enter Yes or No: ').upper()
if ask_play[0] == 'Y':
flip = coin_flip()
coin_dict[flip] += 1
print(flip, coin_dict)
while ask_play[0] != 'N':
flip = coin_flip()
coin_dict[flip] += 1
ask_play = input('Would you like to flip again? ').upper()
print(flip, coin_dict)
print(f'Thank you for playing! Your total score is {coin_dict}')
else:
print('No worries!')
coin_flip_simulator()
```
Comment: You can use just one `while` loop with no `if` outside.
Here is another answer: You are calling coin_flip() again after the user says "N". You can remove that duplicate code, something like this:
```import random
def coin_flip():
if random.randint(0, 1) == 1:
return 'Head'
else:
return 'Tails'
def coin_flip_simulator():
coin_dict = {'Head': 0, 'Tails': 0}
ask_play = input('Would you like to flip a die? Enter Yes or No: ').upper()
#This will only run as long as the user keeps saying no
while ask_play[0] != 'N':
flip = coin_flip()
coin_dict[flip] += 1
print(flip, coin_dict)
ask_play = input('Would you like to flip again? ').upper()
print(f'Thank you for playing! Your total score is {coin_dict}')
print('No worries!')
coin_flip_simulator()
```
Comment for this answer: Use `input()` for python 3. OP is using python 3.
Here is another answer: Glad to hear you are starting in the amazing world of Python. I put together some code based on what you were trying to achieve. Please give this code a try and let me know if it works.
```import random
def coin_flip():
if random.randint(0, 1) == 1:
return 'Head'
else:
return 'Tails'
def coin_flip_simulator():
coin_dict = {'Head': 0, 'Tails': 0}
player_name = input('What is your name? \n ')
ask_player = input(f'{player_name}, Would you like to flip a coin? (Y/N): ').upper()
while ask_player != 'N':
flip = coin_flip()
coin_dict[flip] += 1
print(f"Current Score is: ==> {coin_dict}")
ask_player = input(f'Would you like to flip again? ').upper()
print(f'\nNo worries,{player_name}!, thank you so much for playing! \nYour total score was => {coin_dict}')
coin_flip_simulator()
```
Here is another answer: An option that should do the job below, preserving the behavior in messages you want (I think)
```import random
def coin_flip():
if random.randint(0, 1) == 1:
return 'Head'
else:
return 'Tails'
def coin_flip_simulator():
coin_dict = {'Head': 0, 'Tails': 0}
ask_play = input('Would you like to flip a die? Enter Yes or No: ').upper()
if ask_play[0] == 'Y':
while ask_play[0] != 'N':
flip = coin_flip()
coin_dict[flip] += 1
print(flip, coin_dict)
ask_play = input('Would you like to flip again? ').upper()
print(f'Thank you for playing! Your total score is {coin_dict}')
else:
print('No worries!')
coin_flip_simulator()
```
You played twice the first time. Just removed some lines and it makes it
Comment for this answer: @Daphoque I granted the code of the minimal corrections from original to make it working. That's how you see what is wrong. Rewriting the stuff does not help. And elegance has no place in learning!
Comment for this answer: I see you never faced any student or people to seriously teach to, my dear friend. :)
Comment for this answer: Your if "if ask_play[0] == 'Y':" is useless, the answer is checked with the while below.
Comment for this answer: Indeed, but efficiency yes :) We're not asking you to rewrite the stuff, but you can help to improve the efficiency of the code when you see something wrong, and help people to code in a better way :D
|
Title: I have an odd-shaped image with text in it. How can I get the text to stay within the image even when scrolling?
Tags: html;css;image
Question: I have an image on my page that's got rough edges to look kind of torn and has an inner shadow to look like it's kind of an indentation of the page. I want the content that's on top of it to scroll under the edges of the image without going outside of the visible image. The image is a PNG and is transparent around the torn effect, but I still can't get it to hide under the background.
http://kellygoekenphotography.com/portfolio.php
Comment: Tangential, but consider using a responsive design to minimize scrolling. I like the effect, but (at least at higher resolutions) there's a little scrolling box and a lot of wasted space.
Comment: To start, read a little about responsive web design if you aren't familiar. Then perhaps try to create a background which can repeat horizontally and/or vertically. This could be quite difficult with the torn edge effect on all sides; you might choose to simplify it to better use real estate. It would be easy to have a torn effect down one or both sides.
Comment: Well I thought so to but I added an image at the top that had some transparency and it still scrolled under the image as though it had no transparency.
Comment: @TimMedora, yeah I understand what you're saying. What would you recommend? I'm fairly new to the design world.
Comment: Welcome to SO. Please read the [FAQ] and [Ask] for tips on writing good questions. In your case, you given no information that would help someone answer your question, starting with your Javascript, HTML and CSS code.
Comment: The problem is that it's a `background`; you'll need to position an actual image, or another element containing an image/background-image, for the content to scroll 'under'/'behind'.
Here is the accepted answer: The problem is that you only have one image. Whether it is transparent or not is not going to affect it because in any case, it's underneath the text (or else you wouldn't be able to see the text). What you want to do is separate it into two images; one with just the background (silver shiny part) and another with only the ripped part and a transparent center. You would then place the background image underneath the text and the cutout image on top of the text (in the z-index).
Edit:
OK I didn't notice that your background image has a transparent outside. What you want to do is this:
Keep the background image as it is
Take the original image file (I'm assuming Photoshop), and make the outside white instead of transparent.
Then take the center and make that transparent instead. So all you should have is the white frame around it.
Get rid of any layer effects
Save that image as your foreground
Make the text scroll on top of the background like you originally had it
Position this new image right on top of that area in exactly the same place as the background image
Edit2:
I just realized that won't work either because your page background is not white, but it has some sort of squiggly thing. I therefore thought of another alternative.
BG image will be the silver background without the layer effect above it. Just the plain old ordinary silver part however keep the transparent border around it as it is now.
Top image will be only the layer effect on a transparent background without the silver part. With this image as well, make sure you keep the transparent border around the image as well.
This way the text will be underneath the shadow effect, so when it scrolls at the top, the abrupt cut line won't be quite so obvious. You will probably see it a bit, but it will at least minimize the effect. Of course, the shadow effect will also be on top of the images and text, so you might not like this solution either.
Comment for this answer: This seems like it should work, but for some reason it's not! There must be something in my code that's not right somehow...
Comment for this answer: If you refresh the page, I added the image to it.
Comment for this answer: #content {
width:575px;
min-width:575px;
max-width:575px;
float:right;
z-index:2;
background:url(images/imgbg01.png) no-repeat;
min-height:500px;
}
#cotext {
padding-left:25px;
padding-right:25px;
color:#fff;
max-height:350px;
overflow-y:auto;
overflow-x:hidden;
border:none;
text-align:center;
position:relative;
z-index:3;
}
Comment for this answer: Ah okay, yes, thank you. I see where I went wrong! Thank you!
Comment for this answer: Thank you for all the help! I think the shadow only effect would be cool but I think I'll see how the first option goes. In fact, I'm only going to be able to put the top and bottom on as separate images as if I do one whole image over the top, I can't click on the images behind it. But it will do the same thing. Thank you once again!
Comment for this answer: Can I see what you have so far?
Comment for this answer: See my edit. I didn't notice that the background image was transparent around the border.
Comment for this answer: Good point about not being able to click on the links. I overlooked that.
Here is another answer: Replace this line
```<div id="content">
```
with this
```<div id="content" style="margin-top: 22px;">
```
Comment for this answer: I have this currently, and it creates a straight line instead of going under the actual image.
Here is another answer: Looks like you're nearly there.
For your cotext div, try positioning it 20px from the top.
```<div id="cotext" style="position:relative;top:20px;">
```
Should fit better this way.
Comment for this answer: This just moves it down instead of creating the under the image scroll effect I'm looking for.
|
Title: reusing objects instantiated from database
Tags: python
Question: Sorry if this is too simple but I'm new to databases.
Say that I have a data base with two tables, one for persons and one for countries. Each person has a country associated with them.
I wan to load the items in these tables into python objects in a lazy way. Right now I'm looping through all the rows in 'persons' and instantiating objects for them. So for each 'person' I get an object, now if I want to access the country associate with a person, I get the country_id and instantiate a brand new 'country' instance (even if all persons have the same country). For example if person1.country is XXX and person2.country is XXX the object ids are different
```class Person(object):
def __init__(self, id):
self.id = id
def country():
...
country_id = (gets id from db here)
self.country = Country(country_id)
```
so I'll get
```id(person1.country) -> 123
id(person2.country) -> 456
```
What is the most pythonian way to have both persons share the same country instance?
Thanks for the help
Comment: Are your `Person` instances also stored in the database? You really want to use a ORM to handle your database -> object mapping, like SQLAlchemy. Don't do this manually.
Here is another answer: you can have a many to one relationship where many countries are associated with on person. person will have a country_id as foreign key constraint to the associated country id. you basically have to do a lookup for the associated country and assign the correct id from country. For a country table you would probably want to pre-fill the table with all the known countries.
the constraint prevents you from having unmatched id's in the case where you decided to delete an entry in the country table. You can define other properties such as how entries will be deleted if a country is removed from the table or updated. i.e you can have the country_id set to null in the people table or delete all the people associated with that country. look up foreign key constraints and you should find more material about the various constraint properties. you can make it illegal to delete a country if there is still a person associated with the entry.
```CREATE TABLE Person (
id BIGINT NOT NULL,
country_id BIGINT NOT NULL,
etc ...,
PRIMARY KEY(id),
FOREIGN KEY(country_id) REFRENCES Country(id)
)
CREATE TABLE Country(
id BIGINT NOT NULL,
etc..,
)
```
Here is another answer: You could implement ```Country``` as a singleton pattern.
Although I have to ask -- why does it matter? As long as ```person1.country == person2.country```, why do you care if the ids are the same?
Comment for this answer: Then it sounds like singleton might be a good solution for you.
Comment for this answer: Thanks for the feedback, I have to read on singletons but to answer your question I do care because I have many persons, and each country is doing expensive IO operations. I can cache the operations for one country, but that doesn't help if the next country is a different instance.
|
Title: post facebook QuestionObject through graph api / php sdk
Tags: facebook;facebook-graph-api;facebook-php-sdk
Question: ```
Possible Duplicate:
Add Facebook “Question” over Graph API?
```
I was looking in graph API of facebook, there I only find about reading the information related to a question or all questions. see https://developers.facebook.com/docs/reference/api/question/
But I can't find any help regarding posting a question to wall. Please guide me if there is any way of doing this.
Thanks.
Comment: same as http://stackoverflow.com/questions/5687221/add-facebook-question-over-graph-api/7936995#7936995
Here is another answer: Currently there is no possibilities for application to publish Questions and Question Options via Graph API. Only "white-listed" application allowed to do so (which means you need a special agreement with Facebook on that)
Comment for this answer: No, not possible. Questions are currently read-only via the public APIs that facebook has allowed us to use.
Comment for this answer: Thanks for answering. Is there any way of posting question using php/javascript sdk?
Here is another answer: Till now facebook doesn't allow to post question using graph.You can read questions from facebook.see this tutorial https://developers.facebook.com/blog/post/590/
|
Title: Using listings package with beamer/block environments for displaying source code
Tags: beamer;listings;sourcecode
Question: I use beamer with ```semiverbatim``` environment to show source code.
```\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}
\setbeamercolor{block title example}{fg=white,bg=red!75!black}%
\setbeamercolor{block body example}{fg=black,bg=white!70!red}%
\begin{document}
\begin{frame}[fragile]{Code}
\begin{example}[Code]
\begin{semiverbatim}
class Hello {
...
}
\end{semiverbatim}
\end{example}
\end{frame}
\end{document}
```
However, I want listings package which provides features such as highlighting and source code numbering. So, I tried this.
```\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}
\usepackage{listings}
\lstset{numbers=left, numberstyle=\tiny, stepnumber=1,firstnumber=1,
numbersep=5pt,language=Java,
stringstyle=\ttfamily,
basicstyle=\footnotesize,
showstringspaces=false
}
\begin{document}
\begin{frame}[fragile]{Code}
\begin{block}
\begin{lstlisting}[firstnumber=1, caption=Getting labels, label=glabels]
class Hello {
...
}
\end{lstlisting}
\end{block}
\end{frame}
\end{document}
```
However, I can't compile it to get an output.
My questions are:
How can I use listings package with beamer/blocks?
Or how can I show source code with line number listing and keyword highlighting with beamer/blocks?
Here is the accepted answer: Beamer blocks need a title (```\begin{block}{_title_}```), even if it is empty (```\begin{block}{}```).
```\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}
\usepackage{listings}
\lstset{numbers=left, numberstyle=\tiny, stepnumber=1,firstnumber=1,
numbersep=5pt,language=Java,
stringstyle=\ttfamily,
basicstyle=\footnotesize,
showstringspaces=false
}
\begin{document}
\begin{frame}[fragile]{Code}
\begin{block}{Getting labels}
\begin{lstlisting}[firstnumber=1, label=glabels, xleftmargin=10pt]
class Hello {
...
}
\end{lstlisting}
\end{block}
\end{frame}
\end{document}
```
|
Title: Cordova adding port to external links on cordova run browser
Tags: javascript;node.js;cordova;socket.io;localhost
Question: I'm building a test chat app client with node.js, socket.io and cordova.
Executing ```cordova run browser``` browser opens to http://localhost:8000.
In index.js of my cordova chat client app i got code to connect to my server side socket.io:
```var socket = io.connect('https://node-socket.io-address/');
socket.on('connect', function() {.............
```
Problem is that i receive this kind of error:
So as you can see there is a port (8000) added to the link. This problem is not occuring when I run app on android device (cordova run android).
Why cordova is adding port to external links ? Can disable port adding to external links on cordova run browser ?
Comment: Actually I remove it completely because it was causing another errors (refuse to connect to resorce) but its not the case ;). Why there is a port added to link placed in Javascript - with added port to the end of the url addess is just not correct
Comment: @stdob-- yes Im aware of that - but I would have to know what port is using by my heroku test server (its not 443 because there is connection timeout erron in chrome dev console)
Comment: @robert what config do you mean ? I just run : cordova run browser and this will open up browser with adress localhost:8000. In my server app (which is running constantry) I got:
http.listen(process.env.PORT || 8000, function(){
console.log('listening on *:8000');
})
Comment: Did you configure CSP (Content-Security-Policy) correctly in your index.html?
Comment: What does your config look like? e.g. app.set('port', process.env.PORT || 8000); process.env.PORT is set by the environment you run your code.
Comment: You can simple add default https port: `var socket = io.connect('https://node-socket.io-address:433/');` (or another port if different)
Here is the accepted answer: It's not cordova adding port to your URL, it's socket.io client, here:
``` this.port = opts.port || (global.location && location.port ?
location.port :
(this.secure ? 443 : 80));
```
When port is not defined, it defaults to port of application. That is probably a bug in socket.io, since it makes sense only if webpage and server are hosted from same node. Your problem originates from the fact, that it is cordova which serves your application (on localhost:8000) and socket.io assumes that websocket will be on same port.
To avoid it, you should add port to URL or the ```opt```ions object.
Comment for this answer: That's what I thought at first - to add port to link but I dont know what port is used by my socket.io backend application hosted on Heroku - I tried :443 (since my Heroku url was on https) but it didnt work ;). Is there any solution (maybe online solution) to check port having only URL ?
Comment for this answer: Hmm i don't know how to use it - but I will check it out. Got any tips for that ? Anyway thank you for your answer - bounty is yours ;)
Comment for this answer: You should use Heroku's HTTP routing feature to do that.
|
Title: size of the disk is more than the size of the files on the disk
Tags: windows;windows-7;disk-space
Question: I am using windows 7. my c: drive capacity is 75 gb. where the Os is located. The size of the files on the disk is only 50 gb including hidden files. But used space of c drive shows 60Gb. Where the 10gb space goes? I think it might be due to the files that are burned to a dvd disk long time before. every time burn a files to a dvd. size of C: drive gets increased. how to resolve the problem? how to get back my disk space?
Comment: Fragmentation has NOTHING to do with this!!!! See my answer below
Comment: An additional part of it may be system restore images, which happen for most driver installs/updates and somewhat randomly as windows awkwardly does. Download the free [ccleaner](http://www.piriform.com/ccleaner), navigate to Tools > System restore. You should have quite a few options to remove. If you want to limit the hard drive space those take, I can post that too.
Comment: Fragmentation!!
Comment: @cybernard - Uh, what you describe is known as "internal fragmentation".
Here is another answer: The size calculated by adding up file sizes in Windows Explorer is known to be inaccurate. The only correct usage figure is in the 'pie' chart.
There are a number of Microsoft articles which explain some of the places the space can be.
http://blogs.technet.com/b/askcore/archive/2013/03/01/where-did-my-space-go.aspx
http://blogs.msdn.com/b/ntdebugging/archive/2008/07/03/ntfs-misreports-free-space.aspx
http://blogs.msdn.com/b/ntdebugging/archive/2008/10/31/ntfs-misreporting-free-space-part-2.aspx
You can also use programs like Treesize and WinDirStat to investigate.
Here is another answer: First listen to the other people who have already stated the different between a gigabyte and a billion bytes. A 75gb hard drive really stores about 69.8gb of stuff.
Second, when you store a file it uses a minimum of 1 cluster, and has to use whole number of clusters. You can not allocated 2.5 cluster, it is really 3 clusters.
Here is a functional example. Lets say your cluster is 4k (or 4096 bytes) if you save a document on your hard drive that is 1,000 bytes then 3096 bytes of space are wasted. The end of every single file on the hard drive generates some amount of waste. The only except are files that are exactly sized in increments of 4k. So 4096 multiplied by any whole number.
If you have collection of 1,000 icons using 1000 bytes on a 4k cluster then each one wastes 3096 bytes. Roughly 3k. 3k *1000 = approx 3 megabytes of wasted space.
Every file system has this basic issue. You can adjust the cluster size on some file systems with in certain limits. FAT is the least flexible. FAT32 is slightly flexible. NTFS has the most flexibility of all the windows file systems. It is possible with NTFS to have a cluster size of 512 bytes, and this reduces the waste to less than 1% but some waste still exists.
To clear up the fragmentation non-sense. Fragmentation, just makes it harder for the operating system to find the entire file slowing down access to the file. It can not increase or decrease the amount of available space.
However, it is possible that the software you are using creates the DVD in a temporary file and then burns the file. After the file is burnt it likely deletes the file and you get some hard drive space back. DVD can be as large as 4.6gb or 8.5gb if it is dual layer. A deletion of a temporary file of this size would make a big impact on free space on a hard drive of this size.
Comment for this answer: If this does not completely account for the space you could have a more than 1 partition on your hard drive and one of them could be hidden. Check "Disk Management".
Comment for this answer: @DanielRHicks While the wikipedia page does say that, it does not make it true. Even wikipedia says "this article has multiple issues". Dictionary.com "fragmentation" definition #4. The space at the end of the cluster is simply slack or wasted space. Fragmentation is breaking a file into parts to fill available free spaces that are to small for the whole file. The wasted space has to be less than 1 cluster(even by a single byte) and therefore the wasted space can not be fragmented.
Comment for this answer: What you're describing is known as ["internal fragmentation"](http://en.wikipedia.org/wiki/Fragmentation_%28computing%29).
Comment for this answer: I first heard that definition in 1972 or 1973. Explained by David A. Nelson, a respected consultant. You can argue that the terminology is poorly chosen, but you cannot (validly) argue that the term does not mean what I said it means.
Here is another answer: All drives are formatted, and as such lose a portion of their total capacity. For example a 2TB Hard Drive only has 1.81GB Usable space after it is formatted.
This is because the partition table takes up the part of the drive you cannot see.
http://en.wikipedia.org/wiki/Disk_partitioning
^ Hope this helps a bit more.
Comment for this answer: A 2TB disk shows as 1.81TB in Windows because of the different ways disk manufacturers and Microsoft measure storage. Disk manufacturers use the normal decimal method where 1TB = 1,000,000,000,000. Microsoft uses a binary based system where 1K = 1024 so that 1TB = 1,099,511,627,776.
|
Title: Can't load CSS stylesheet in moodle
Tags: html;css;html-email;moodle
Question: I run a Moodle 2.9 server, and while configuring the email to be sent to the user, I created a CSS stylesheet to be included to format said email. However, when I try the email, it appears non-formatted. I'm putting the text in question in a php variable inside a config file in moodle like this.
```$string['newusernewpasswordtext'] = '
<html>
<head>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic);
@import url(https://fonts.googleapis.com/css?family=Roboto+Condensed:400,400italic);
@font-face{
font-family:FontAwesome;
src:url(https://netdna.bootstrapcdn.com/font-awesome/2.0/font//fontawesome-webfont.eot?#iefix) format(\eot\'),
url(https://netdna.bootstrapcdn.com/font-awesome/2.0/font//fontawesome-webfont.woff) format(\'woff\'),
url(https://netdna.bootstrapcdn.com/font-awesome/2.0/font//fontawesome-webfont.ttf) format(\'truetype\'),
url(https://netdna.bootstrapcdn.com/font-awesome/2.0/font//fontawesome-webfont.svg#FontAwesome) format(\'svg\');
font-weight:400;font-style:normal;
}
@import url("http://xxx/mail.css");
h1 {
font-size: 3.5em;
color: #E52B38;
font-family: \'Roboto\', sans-serif;
line-height: 100%;
font-weight: 400;
letter-spacing: 2px;
}
</style>
```
I also tried including or linking the css file from within the body tags, to no avail. I have seen that the fonts are being loaded since one single element on the email has an inline formatting and is being rendered accordingly. However, i do not want to resort to inline formatting.
Thanks and I'm open to any suggestions
Comment: Emails are a fickle beast. Common wisdom dictates that all styles should actually be inlined, as some clients will strip out and blocks. My suggestion would be to author the email as you normally would, than use an inliner tool. Something like this: http://templates.mailchimp.com/resources/inline-css/ or even this: http://zurb.com/ink/inliner.php
Comment: You're going to run into issues using pseudo's either way: https://www.campaignmonitor.com/css/
Comment: I hear ya, that's where we're still at for email :(
Comment: Yea, it should probably be entered statically, either through your email build system or manually. When the email arrives, it'll be timestamped anyway, so it won't look funny if a user opens the email two years from now. If you ABSOLUTELY must have that dynamic (boss is making you), use JavaScript's `new Date().getFullYear()` , and place the static year next to it in a block. That way you cover both bases as there will be email clients that do not support JS.
Comment: Tried zurb and the pseudo elements got lost, as i was guessing they would. Thanks anyway
Comment: thanks! i used a mixed solution, putting the complex elements in images and Voila!! i don't like it, is so 1996 but it works, so thanks!!
Comment: i need to show the current year in that same email (loaded automatically), any ideas? :)
Comment: I took the lazy route and put it statically...thanks man!!
|
Title: Problem with dhcp in Debian
Tags: debian;ip-address;dhcp;static-ip
Question: I try to have a static ip adress on an host.
I execute the following commands :
```$ ip address eth0 441.508.4524 netmask 441.508.4524
$ route add default gw 441.508.4524
```
But later my IP address changes on ```441.508.4524``` unless I have commented the request command in ```dhcplient.conf``` and I have put into ```/etc/network/interfaces``` the following:
```iface eth0 inet static
address 441.508.4524
netmask 441.508.4524
gateway 441.508.4524
```
Please help me I don't understand why my ip changes ?
Thanks in advance.
Narglix
Here is another answer: ```/etc/network/interfaces``` holds your default configuration... so if you need a permanent static IP, put it in there like this:
```iface eth0 inet static
address <THE IP YOU WANT>
netmask 441.508.4524
gateway <THE IP OF YOUR GATEWAY (Usually your router)>
```
The commands you executed only adjusts your configuration temporarily.
Comment for this answer: You also need to remove the line for dhcp, or at least you should.
iface eth0 inet dhcp # <== Remove this
Comment for this answer: I don't see the difference than I have made
Comment for this answer: @user32433 - Your IP shouldn't change when that is in your interfaces file.
|
Title: Google API Authentication for server
Tags: php;google-api;oauth-2.0;google-calendar-api
Question: I've been trying to get Google's Calendar API working in a PHP web application, but I'm having a hard time getting authenticated.
What I want to do is to allow users to interact with calendars of a single account known by the server.
Each type of scenario covered in the OAuth 2.0 docs talks about "user consent" which involves a login form and the individual user logging in, but I want the server itself to authenticate directly and obtain an access token for itself.
Is there some part of OAuth or some alternative mechanism I can use to do this?
Here is the accepted answer: In order to do this, you must go through the steps for user consent and then copy the access tokens it gives you into the PHP code.
The usual procedure for OAuth is like this:
Send user to authentication page.
User comes back with $_GET['code']
Send $_GET['code'] to OAuth server for a token
Store token in database for the user (or session, if it's very short lived)
But when doing it with a single calendar like this, you modify step 4. Instead, you dump the token to screen and copy it into your PHP file as variables, instead of putting it in the database. Then when you go to pass the access token to the server, you just pass the known, static token rather than a dynamic token from the database / session.
Comment for this answer: I've been using this exact method for a calendar since December with no issues, and the events on this calendar update so frequently that I know it's still working. I think access tokens do have a lifetime, but it's measured in months, not days or hours.
Comment for this answer: Thanks, but isn't the access token itself short lived? I'd have to do this manually all the time.
Comment for this answer: This only applies to older oauth1, not current oauth2
Here is another answer: See mathewh's answer here:
How to automate login to Google API to get OAuth 2.0 token to access known user account
The lightbulb for me is when you get the access token you get a refresh_token as well... you use this token to "refresh" your access token once it expires.
There is no way around a manual authorization step the first time.
|
Title: How can I define an array in my Objective-C header file?
Tags: c;objective-c
Question: I have this code in my main file:
```int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
```
How do I define it in my header so that I can access the variable throughout my class?
Here is another answer: You can't define it in your header. You have to declare it in your header and define it in a source (```.m```) file:
```// In MyClass.h
extern int grid[];
// In MyClass.m
int grid[] = {...};
```
Comment for this answer: compiles, but when I'm in a different function in the *.m file, the compiler complains that it's undefined.
Comment for this answer: Any header file which needs to use grid[] needs to have an "extern int grid[]" declaration in it, or needs to #include another header file which has the extern declaration. See also http://stackoverflow.com/questions/309801/declarations-definitions-initializations-in-c-c-c-java-and-python
Comment for this answer: you want to define it at the "top level" of the .m file (ie. outside of all functions). By convention, global variables such as this are defined at the top of the .m file, just below any #import or #include statements.
Here is another answer: ```extern int grid[];
```
Let's suppose you had some code like this:
```int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
int arr_sum(int* arr, int len)
{
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int main(int argc, char** argv)
{
printf("%d\n", arr_sum(grid, sizeof(grid)/sizeof(int) ));
return 0;
}
```
If you wanted to separate this out into two different files, say, you could have the following, for example:
in grid.c:
```int grid[] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ,
1 , 2 , 3 , 2 , 3 , 2 , 3 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ,
1 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ,
1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 ,
1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 };
```
In main.c:
```extern grid[];
int arr_sum(int* arr, int len)
{
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}
int main(int argc, char** argv)
{
printf("%d\n", arr_sum(grid, sizeof(grid)/sizeof(int) ));
return 0;
}
```
Comment for this answer: i think with "construct" he meant how he defines the array. but then again this is about objective-c . i've got no clue about that. but looks like it is similar to normal C.
Comment for this answer: how do I construct the array in the implementation file?
Comment for this answer: it compiles, but if i try to access the array from a different function to where it was defined, the compiler throws an error :/
Comment for this answer: You'll need the extern in a header file called "externals.h" -- or something like that. It will hold all of your external variable declarations. In your source file containing main, *don't* include the externals.h file, but do include the actual definitions of those external variables.
Comment for this answer: You shouldn't need to construct it anywhere else. Have the code that you listed above in main.c, and put "extern int grid[]" in a common header file used by the other source files that use grid. Or if you don't want the header, just put the extern wherever grid is used.
Comment for this answer: Is grid defined within the scope of a function? You have to move it to a more global scope if you want to use it in other functions.
Comment for this answer: @litb: Objective-C is a *strict* superset of C. In this case, the question has absolutely nothing to do with any part of the new features of Objective-C, it's a pure C question.
|
Title: Viewpager with diffrent page number
Tags: java;android;android-viewpager
Question: My app has 10 items on home screen. Each of them has sub-categories that are different (say item1 his 5, item8 his 3)
my question is about the best practice to implement such a problem.
what I've already tried is using a fragment page adapter to load pages(categories), but it does not seem to solve my problem.
```@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return x.newInstance();
case 1:
return y.newInstance();
case 2:
return z.newInstance();
default:
return null;
}
}
```
Here is the accepted answer: can you provide more details? do you refer to the Tab as item?
is each category presneted by the same Class? because if that's the case then provide arguments to the newInstance method where you specify the category and the number of items you need like so:
```public class Frag_UserItems extends Fragment {
...
public static MyFragment newInstance (int itemsNumber, Category category){
// assuming category is an enum
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.setInt("num", itemsNumber);
bundle.setString("category", category.toString());
fragment.setArguments(args);
return fragment;
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_items, container, false);
//fetch the arguments and get the data from the reposotry
// and filter them how you want
Bundle args = getArguments();
int num = args.getInt("num");
String num = args.getString("category");
List<MyItem> items = ...
// bind view..
initview(rootView, items);
return rootView;
}
}
```
T think you can store the fragment instances in an array also, or you can pass the index number to the newInstance method and there you would deal with creating the fragment based on the index, that way it will reduce getItem to:
```@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
public class Frag_UserItems extends Fragment {
...
public static MyFragment newInstance (int position){
// assuming category is an enum
Bundle bundle = new Bundle();
MyFragment fragment = new MyFragment();
bundle.setInt("num", position);
fragment.setArguments(args);
return fragment;
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_user_items, container, false);
//fetch the arguments and get the data from the reposotry
// and filter them how you want
Bundle args = getArguments();
int num = args.getInt("num");
List<MyItem> items = ...
// bind view..
initview(rootView, items);
return rootView;
}
}
```
this is basicly following the Factory method pattern.
I hope this helps
Comment for this answer: Well the answer above should cover you, use the second example and nwrite a method that filters the objects based on what position you are at in the viewpager
Comment for this answer: I'm mean by item a product that has a categories **ex(item 0 has A, B, C )** of elements I want to put on tapped layout and switch between them with viewpager. yes, each category presneted by the same Class.
Comment for this answer: Thanks for your help, greatly appreciated.
Here is another answer: You should give us more information about what you are going to do! But as far as I understood, you have some items and each of them have some sub-items. If it was me, I would do that with nested RecyclerView!
Here I found a good article for helping you with:
https://android.jlelse.eu/easily-adding-nested-recycler-view-in-android-a7e9f7f04047
I hope it's what you're trying to do.
|
Title: PHP OO: Calling methods on abstract classes?
Tags: php;oop
Question: Please could someone help with the following?
We have the following classes:
abstract class Element{}
abstract class Container extends
Element{}
abstract class Field extends
Container{}
The 'Element' base class has the following properties and methods:
```//Element class
private $errors = array();
public function __construct()
{
}
public function setError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return "<li>".implode("</li>\n",$this->errors);
}
```
The 'Container' just groups the elements (objects).
The 'Field' class calls the 'setError' method of the base class and passes a value like this:
```//Field class
$this->setError("foo");
```
For some reason the 'errors' property in the base class doesn't get the value added to it and Im guess its something to do with how the object is instantiated because obviously the abstract classes are not instantiated by default.
The only instantiation of the field is in its inherited form which is:
```Text extends Field{}
$field = new Text(etc, etc)
```
How would you get about resolving this?
Comment: can you show the full code for element and field classes
Comment: "Favor object composition over class inheritance." (c) GoF
Comment: How is this question unclear for whoever felt the next to vote it down?
Here is the accepted answer: Works for me : http://codepad.viper-7.com/Ool7zn
```<?php
abstract class Element
{
protected $errors = array();
public function setError($error)
{
$this->errors[] = $error;
}
public function getErrors()
{
return "<li>".implode("</li>\n",$this->errors);
}
}
abstract class Container extends Element{}
abstract class Field extends Container{}
class Text extends Field{}
$t = new Text;
$t->setError('foobar');
echo $t->getErrors();
?>
```
Comment for this answer: Can you paste your code into your answer so that we don't lose the solution, please.
Comment for this answer: note that you didn't show how it is called + it really doesn't matter how it is called.
Comment for this answer: Thanks Teresko but the 'setError' method is not called like that.
Comment for this answer: I did show how its called. It's called within the 'field' class and ofcourse it matters how its called. You cant call it out of thin air but thanks anyway.
Comment for this answer: Theres obviously something else going on but Tereskos example is good because it shows this should work so going to put this as answered.
Here is another answer: You're going to have to set the $errors member variable to protected in class Element.
```//Element class
protected $errors = array();
```
Right now, when you call the inherited setError() function on the Text class instance, the Text class instance does not have its own $errors array, so PHP does you the 'favor' of creating one on the fly within the instance of the Text class. However, this is a different $errors member variable from the one in the Elements base class.
Setting the $errors member variable to 'protected' allows the instance of the Text class to interact with the variable in the Element base class, so that PHP does not do you the 'favor' of creating a new $error member (belonging only to the Text class) on the fly.
Comment for this answer: You're not re-declaring $errors in any of the inheriting classes?
Comment for this answer: Also, what method in the Field class contains the call to $this->setError("foo")?
Are you calling that same (inherited) method on the Text class? I.e. $text->theMethod() (with theMethod being inherited from Field).
Comment for this answer: FYI, might be best to have the code of all the classes involved.
Comment for this answer: Thanks DWight, good answer but didn't work. Is it because the 'setError' method is called in 'Field' class but its actually 'Text' class thats gets instantiated. I know 'Text' is inheriting 'Field' but thought Id ask?
Comment for this answer: No not re-declaring $errors anywhere. In the 'field' class is a method named 'validate', this is an abstract method for near enough all inheriting classes. The 'Text' class only has a 'getfield' method. Sorry.
Comment for this answer: How is adding something that has no relevance to the question going to help. There are so many classes and functionality shared between them its only going to confuse matters but thanks anyway Galen.
|
Title: (GWTP) Can "placeManager.revealPlace(request)" open a URL in a new Tab?
Tags: gwt;gwtp
Question: In GWTP, to open a URL in a new tab, we can use this:
```PlaceRequest request =new PlaceRequest(NameTokens.getorder).with("myID", myID);
String url =
Window.Location.createUrlBuilder().setHash(placeManager.buildHistoryToken(request)).buildString();
Window.open(url, "_blank", null);
```
Can we not to use ```Window.open``` & just use ```placeManager``` to achive the same thing (ie open a URL in a new Tab).
```PlaceRequest request =new PlaceRequest(NameTokens.getorder).with("myID", myID);
placeManager.revealPlace(request);
// this code will open the url (ex: mydomain.com#getorder;myID=15 ) in the current browser.
```
The problem of ```Window.open(url, "_blank", null);``` is that sometime it opens to new tab & sometime it opens to a new Window which is inconsistent.
Here is the accepted answer: Try this one
```Window.open(url, "", "");
```
or
```Window.open(url, "", null);
```
|
Title: How to disable "browse" button on defaultDirectory wizard page
Tags: inno-setup
Question: I want to show the user to wich directory the program will be installed. But I do not want to allow him to change that directory. So I thought about disabling the "browse" button and greying the field where you can type a path (disabling anyone from typing in there).
I have read this question, which is about preventing the user to select a wrong directory. In a comment by TLama I saw this:
```
Wouldn't be the Next button is greyed until the user chooses the right folder quite misleading ? What if I as the user forget the right directory ? Wouldn't be better to disable the choose folder edit box or skip that page at all ?
```
But the User asking the Question did not want to do it the suggested way so there is no further hint for this solution. Could you please tell me how to do this?
(Note: Sorry for opening a new question on such a similar topic, but as a new user I can't see another way of asking for help)
Here is the accepted answer: You can disable the directory edit box with the browse button this way:
```[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
[Code]
procedure InitializeWizard;
begin
WizardForm.DirEdit.Enabled := False;
WizardForm.DirBrowseButton.Enabled := False;
end;
```
|
Title: How to resize an event in full calendar without the code "editable = true"
Tags: javascript;events;resize;fullcalendar
Question: I need to manually resize the event in ```fullcalendar``` without the code ```editable=true```, because I have added a dropdown inside the event and
to work its click I suppose prevent the editable property(```editable=false```). Now the dropdown is working but the resize property been disappeared. Even I tried the property resizable(```resizable=true```). How can I bring both the codes?
sample code
```$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,agendaFourDay'
},
views: {
agendaFourDay: {
type: 'agenda',
duration: { days: 4 },
buttonText: '4 day'
},
},
defaultView: viewDefault,
//minTime: '07:00:00',
//maxTime: '21:00:00',
allDaySlot: false,
eventClick: updateEvent,
selectable: true,
selectHelper: true,
select: selectDate,
editable: false,
resizable: true,
events: "JsonResponse.ashx?eids=" + eIds + "&searchText=" + searchText,
//events: {
// url: 'JsonResponse.ashx',
// type: 'POST',
// data: {
// eIds: $('#hdnCustomerIds').val()
// },
// error: function () {
// alert('there was an error while fetching events!');
// }
//},
defaultDate: dateDefault,
eventDrop: eventDropped,
eventResize: eventResized,
eventRender: function (event, element, view) {
debugger;
// event.stopPropagation();
$(element).find('.fc-title').prepend('<a href="javascript:void(0);" class="delete-event-link" style="color:#fff">' + event.customerid + ',</a>');
$(element).find('.fc-title').html('<select class="dropdown" style="color:black";" onchange="OnchangeEventStatus(this,'+event.id+')"><option >Volvo</option><option value="saab">Saab</option><option value="opel">Opel</option><option value="audi">Audi</option></select>');
$(element).find('.dropdown').click(function (e) {
e.stopImmediatePropagation(); //stop click event, add deleted click for anchor link
});
$(element).find('.delete-event-link').click(function (e) {
e.stopImmediatePropagation(); //stop click event, add deleted click for anchor link
window.top.location.href = "/Sr_App/Customer_Profile.aspx?CustomerId=" + event.customerid;
});
//$(element).find('.fc-title').prepend('<a href="javascript:void(0);" class="delete-event-link" style="color:#fff">' + event.customerid + ',</a>');
element.qtip({
content: {
text: qTipText(event.start, event.end, event.description),
title: '<strong>' + event.title + '</strong>'
},
position: {
my: 'bottom left',
at: 'top right'
},
style: { classes: 'qtip-shadow qtip-rounded' }
});
}
});
```
Comment: i got the solution, just add the property `editable:false` for _fullCalendar_
`$('#calendar').fullCalendar({
selectable: true,
editable:false,
events: "JsonResponse.ashx?eids=" + eIds + "&searchText=" + searchText,
......
....
});
Here is the accepted answer: i got the solution, just add the property ```editable: false``` for fullCalendar
```$('#calendar').fullCalendar({
selectable: true,
editable: false,
events: "JsonResponse.ashx?eids=" + eIds + "&searchText=" + searchText,
......
....
});
```
|
Title: WPF: Selectable usercontrol - How?
Tags: c#;wpf
Question: I’m new to C# and WPF and have a problem I hope you can help with.
I have a WPF application with a stackpanel to which I add usercontrols by code to display the information stored in an instance of a class. The user can create instances, and musty be able to edit and delete instances of the class by selecting the usercontrol. The usercontrol contains a canvas for making a simple sketch as part of the information stored in the instance.
My problem is: How do I make the usercontrol selectable, so that the user can select an instance for editing or deleting, and so that I can address the canvas by code in a particular instance?
I hope you can help me.
/Morny
Comment: Put the UserControl in the ItemTemplate of a ListBox. Start reading here: [Data Templating Overview](https://msdn.microsoft.com/en-us/library/ms742521.aspx).
Comment: Could you show some code?
|
Title: Can you boot/install/restore a MacBook Pro with a MacBook Air USB stick?
Tags: usb;installation;macbook-pro;macbook-air
Question: The new MacBook Airs don't have optical drives, so you can't install or restore the OS via DVD. They include a little USB stick for this purpose:
I have a MacBook Pro and a MacBook Air. Does anyone know if it will work with my MacBook Pro? I'm thinking about removing my optical drive to put in another HD. The only sticky situation I might get into is if I need to do an install or restore on the road without an external DVD drive.
(Good article on replacing optical drive with hard drive enclosure: remiel.info/post/1601242301/making-the-leap-to-ssd-on-a-macbook)
Here is the accepted answer: Your question implicitly has two parts. First, yes it is possible to restore other Macs with a USB stick. I routinely use an OS X Install DVD on a large USB stick or external. However, I'm not sure if you can use the MacBook Air USB restore stick to restore your MacBook Pro. At least for DVDs that come with other Macs, those are locked to the machine and can't be used on other machines.
So your best bet would be to clone the restore disk that came with your MacBook Pro to another USB stick and then replace your optical drive with another hard drive.
Here is another answer: Apparently Not:
```
Can I use the MacBook Air Software
Reinstall Drive to install software on
other Macs?
No. The software will only install on
the MacBook Air it shipped with.
```
http://support.apple.com/kb/HT4399
|
Title: How can I know if the omxplayer is playing or not?
Tags: python;process;raspberry-pi;raspbian;omxplayer
Question: new to programming, I would like to know if there is any way to know if a video is running or not with omxplayer, preferably by returning a boolean, in recent Raspian versions.
If there isn't, how can I get something that does?
The command I'm using to open omxplayer:
```omxc = Popen(['omxplayer', '-b', wakeup])
```
Comment: What do you mean? Does it return a boolean if I run just `omxplayer` ?
Comment: You can just check if the `omxplayer` is running or not, why are you doing this, maybe there is another option to check that.
Comment: I mean if a video is currently being played on Pi you cannot detect that. The only thing you can do is to check whether the `omxplayer` is currently opening or not and based on that concluded a video is being played. `omxplayer` is a player app and when you run it it doesn't return anything.
|
Title: In git, how can I undo the local deletion of an annotated tag that has not been pushed?
Tags: git;git-tag
Question: I accidentally deleted an annotated tag locally that I did not intend to delete. I have not yet pushed the tag's deletion to the remote. I would like to undo this mistake.
```$ git tag -n999
v1.0.0 Initial release
$ git tag -d v1.0.0
Deleted tag 'v1.0.0' (was 1a2b3c4)
```
I've searched online and here on Stack Overflow in an attempt to find a solution. Despite the seeming straightforward nature of this action, I have not had any luck finding a solution.
How can I undo the local tag deletion, reverting the tag to the state it was before I deleted it?
Here is the accepted answer: FYI, I've never done this before prior to answering this question.
But after googling your question, I found this article:
https://dzone.com/articles/git-tip-restore-deleted-tag
I tested its advice, and it worked for me.
In summary:
Use this to get the list of annotated tag objects that have been removed:
```git fsck --unreachable | grep tag
# if don't have grep because you're on windows, you can use this:
git fsck --unreachable | sls tag
```
Use this to examine the findings from the previous command:
```git show KEY
```
Use this to restore the tag:
```git update-ref refs/tags/NAME KEY
```
Here is another answer: ```
```$ git tag -d v1.0.0
Deleted tag 'v1.0.0' (was 1a2b3c4)
$
```
```
That deleted the local ref ```refs/tags/v1.0.0```. To put it back,
```git tag v1.0.0 1a2b3c4
```
That's why the deletion mentioned the object id in the db. Git won't clean objects out of the db until they've been unreachable through any ref for two weeks or more (say ```git help config``` and search for gc.*expire), specifically so it doesn't snatch things out from under in-flight operations and ordinary mistakes and second thoughts. You can hang a ref on any object.
Comment for this answer: The annotated tag is an object. If you don't have a refname for it, then you don't have a refname for it. If you do, then you do. `git tag -d` removes the refname. `git tag` puts it back. Only repack and prune (and the convenience commands that invoke them, like gc) removes objects from the object db, deleting a refname does absolutely nothing to the object db.
Comment for this answer: That's it. You fetch or create tag objects, git automatically makes (ordinary) `refs/tags` refs for them. That's the entirety of the special treatment for them.
Comment for this answer: This looks to be a good way to restore a non-annotated tag, assuming you still have the deleted hash available. It wouldn't restore an annotated tag with message, etc., however.
Comment for this answer: Looks like I stand corrected. It I am inferring correctly, the hash returned on deletion is the reference to the tag object. Calling `git tag` (without `-a`) creates a lightweight tag (i.e. just a pointer) pointing at the tag object. Since that's a pointer to a tag object, the end result is the same as creating an annotated tag: a named pointer to a tag object, and thus it's a full-fledge annotated tag. This a correct analysis?
|
Title: Swipe Between Activities
Tags: android;android-activity;fragment;swipe
Question: I have 2 activities where i want to switch between them with swipe, i've done a lot of research on google but couldn't find a solution, as i am working with bitmaps (images) i have most of code written inside the onCreate() method of Activity, is there any solution for this, or how can i convert the activity like it is into a fragment
Comment: Why dont you use Fragments with ViewPager?
Comment: It's not hard to convert, just a little changes in activities will do the job! Good luck
Comment: i have created an activity to display sdcard images and to select from them so i can display in the other activity (edit activity) where i can edit them, i don't know if i can convert activity into fragment exactly like it is now
Here is the accepted answer: You can do it by using GestureDetector. Below is the sample snippet.
```// You can change values of below constants as per need.
private static final int MIN_DISTANCE = 100;
private static final int MAX_OFF_PATH = 200;
private static final int THRESHOLD_VELOCITY = 100;
private GestureDetector mGestureDetector;
// write below code in onCreate method
mGestureDetector = new GestureDetector(context, new SwipeDetector());
// Set touch listener to parent view of activity layout
// Make sure that setContentView is called before setting touch listener.
findViewById(R.id.parent_view).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// Let gesture detector handle the event
return mGestureDetector.onTouchEvent(event);
}
});
// Define a class to detect Gesture
private class SwipeDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
float dy = e1.getY() - e2.getY();
float dx = e1.getX() - e2.getX();
// Right to Left swipe
if (dx > MIN_DISTANCE && Math.abs(dy) < MAX_OFF_PATH &&
Math.abs(velocityX) > THRESHOLD_VELOCITY) {
// Add code to change activity
return true;
}
// Left to right swipe
else if (-dx > MIN_DISTANCE && Math.abs(dy) < MAX_OFF_PATH &&
Math.abs(velocityX) > THRESHOLD_VELOCITY) {
// Below is sample code to show left to right swipe while launching next activity
currentActivity.overridePendingTransition(R.anim.right_in, R.anim.right_out);
startActivity(new Intent(currentActivity,NextActivity.class));
return true;
}
}
return false;
}
}
//Below are sample animation xml files.
anim/right_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromXDelta="-100%p"
android:toXDelta="0" />
</set>
anim/right_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromXDelta="0"
android:toXDelta="100%p" />
</set>
```
Comment for this answer: It is working fine , thank you, but what i want is to see the slide effect and the activity to be turned on already, after all these tries i am considering to convert every activity into fragments, thank you again !
Comment for this answer: i have already achieved the result i wanted using fragments, thanks again for answer !
Comment for this answer: For slide effect you can use animation and activity's overridePendingTransition method..Check my updated answer. but yes I agree using fragment is correct way.
Here is another answer: There are some libraries for you:
https://github.com/ikew0ng/SwipeBackLayout
https://github.com/liuguangqiang/SwipeBack
https://github.com/sockeqwe/SwipeBack
|
Title: How to pass url params in secure way in react
Tags: reactjs;react-router-dom
Question: I am working on a react application. I have a route like this
```/dashboard/:name/:id/:role``` and if I open this link like this ```/dashboard/Ram/32142/Plumber```. So here from URL params, I am getting user details. Is there any secure way to pass params using react-router.
Here is another answer: You can use ```this.props.match.params.name```
Comment for this answer: @skyshine Until and unless it is on client-side it is not secure. Anyone can read it. So, we should avoid any such information on client side.
Comment for this answer: I can access using this.props.match.params.name.But here my question how to pass params in secure way like "/dashboard/ewrew/234322/ewoirewr"
Comment for this answer: In web using route params only we identify user related details. Here i am asking secure way like making base64 encoding string
|
Title: android parse special format txt file
Tags: android;algorithm;parsing;readfile;country
Question: I need a help to parse a special format file in Android.
The File content is pasted as follow.
????en
AL|Albania
DZ|Algeria
AD|Andorra
AO|Angola
AO_Bengo|Bengo
AO_Benguela|Benguela
AO_Bie|Bie
AO_Cabinda|Cabinda
AO_Cuando Cubango|Cuando Cubango
AO_Cuanza Norte|Cuanza Norte
AO_Cuanza Sul|Cuanza Sul
AO_Cunene|Cunene
AO_Huambo|Huambo
AO_Huila|Huila
AO_Luanda|Luanda
????en
The file content startwith character "????" I need parse country code and city code in a high way.
Here is the accepted answer: Document is pretty chaotic... maybe you may use not parser, but something like this:
``` ArrayList<String> countries = new ArrayList<String>();
ArrayList<String> sities = new ArrayList<String>();
ArrayList<String> codes= new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while ((line = br.readLine()) != null) {
if(!line.contains("?")){
String[] data = line.split(("\\|"); // this part maybe you should modify by yourself
codes.add(data[0]);
countries.add(data[0]);
cities.add(data[0]);
}
}
br.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
```
Hope it will be useful.
Comment for this answer: may be my question is not clear. But your answer is helpful for my question. Thx.
|
Title: Can't make a post call in react
Tags: jquery;ajax;reactjs
Question: I'm learning react and I have started by creating a CRUD app in react. I am able to make the get calls but the post calls don't go through for some reason. My App.js file is:
```import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import $ from 'jquery'
import request from "../node_modules/superagent/superagent";
import axios from 'axios'
import {UserForm} from './components/userForm'
class App extends Component {
constructor(props){
super(props)
this.state = {
users: [],
name: '',
email: '',
password: ''
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handlePostRequest = this.handlePostRequest.bind(this);
}
handleInputChange(state, event) {
this.setState({[state]: event.target.value});
}
handlePostRequest(event) {
var data = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
axios.post('http://localhost:8080/api/users', {
data: data
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
/*request
.post('http://localhost:8080/api/users')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ name: this.state.name, email: this.state.email, password: this.state.password })
.end(function(err, res){
console.log(res.text);
});
var self
event.preventDefault()
self = this
console.log(this.state);
var data = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
// Submit form via jQuery/AJAX
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/users',
data: data
})
.done(function(result) {
self.clearForm()
this.setState({result:result})
}).bind(this)
.fail(function(jqXhr) {
console.log('failed to add the user');
}).bind(this)*/
}
componentDidMount() {
this.App();
}
//making a get call
App() {
return $.getJSON('http://localhost:8080/api/users')
.then((data) => {
console.log(data);
this.setState({users:data});
})
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React CRUD App</h2>
</div>
<div className = "Crud-App" >
<div className = "users-list" >
<ul>
{this.state.users.map( user =>
<li key = {user._id} >
{user.name}
</li>
)}
</ul>
</div>
<UserForm handleInputChange = {this.handleInputChange} name = {this.state.name}
email = {this.state.email} password = {this.state.password} />
</div>
</div>
);
}
}
export default App;```
And my userForm component file is:
```import React from 'react'
export const UserForm = (props) => (
<form>
<label> Name: </label> <input onChange={props.handleInputChange.bind(this, 'name')}
value={props.name} />
<label> Email: </label> <input type="text" onChange={props.handleInputChange.bind(this, 'email')}
value={props.email} />
<label> Password: </label> <input type="text" onChange={props.handleInputChange.bind(this, 'password')}
value={props.password} />
<button type="button" className = "pure-button pure-button-primary" onClick={props.handlePostRequest}>Add User</button>
</form>
)```
I have tried ajax, axios, superagent and fetch so far as you can see the commented code in the App.js file. But pressing the submit button does [email protected]. Any help would be appreciated. Thanks
Here is the accepted answer: Stateless function components do not have a ```this```. You should not re-bind the ```onChange``` handlers in your ```UserForm``` component.
Also, rewrite your handler signature so that it only takes the ```event``` argument:
``` constructor(props) {
super(props);
this.makeHandleInputChange = this.makeHandleInputChange.bind(this);
}
makeHandleInputChange(state) {
return e => {
this.setState({[state]: event.target.value});
};
}
```
Lastly, update your usage of ```UserForm```:
```<UserForm
makeHandleInputChange={this.makeHandleInputChange}
name={this.state.name}
email={this.state.email}
password={this.state.password} />
```
and the definition of ```UserForm``` itself:
```export const UserForm = (props) => (
<form>
<label> Name: </label>
<input
onChange={props.makeHandleInputChange('name')}
value={props.name} />
{ /* ...the rest of the components here... */ }
</form>
)
```
EDIT: You are not passing the ```handlePostRequest``` as a prop to the ```UserForm```.
```<UserForm
makeHandleInputChange={this.makeHandleInputChange}
handlePostRequest={this.handlePostRequest}
name={this.state.name}
email={this.state.email}
password={this.state.password} />
```
Comment for this answer: The event handler is only called with the `event` argument, you should pass a handler with the correct signature. See edit.
Comment for this answer: See final edit. You're never pass the `handlePostRequest` prop to the `UserForm` component. :)
Comment for this answer: Without binding it throws an error saying "cannot read property 'target' of undefined"
Comment for this answer: I made the suggested changes but the post call still doesn't work. When I type data into the form fields, the state changes correctly but the post call that I have written doesn't work for some reason, i.e. pressing the "Add User" button doesn't send a post call
Comment for this answer: Thanks mate. Works like a charm. :)
|
Title: Insert Query not working
Tags: mysql
Question: I have applied a insert query but its giving error .
```$registerquery = mysql_query("INSERT INTO `registration`(`Activation`) VALUES('".$activation."') WHERE email= '". trim($_POST['email']) ."'");
```
Comment: `INSERT`'s don't have a `WHERE` clause. Did you mean to use an `UPDATE`?
Comment: Actually i am going to take the value from the session .thanks for correcting me
Comment: What's the error say, Did you run mysql_connect first, and select a database? Also you should look into other methods of connecting to a sql database. As mysql_ functions are depreciated.
Comment: Past the immediate issue, you are taking `$_POST['email']` directly without any filtering in any way? Bad practice.
Here is the accepted answer: Use update statement instead of INSERT to use where clause
```$registerquery = mysql_query("UPDATE `registration`
SET `Activation` = '".$activation."
WHERE email= '". trim($_POST['email']) ."'"
);
```
Here is another answer: if you want just update a column in table so you need an ```UPDATE``` not ```INSERT``` .
and also you should sanitize you POST variable to prevent sql injection.
``` $email = mysql_real_escape_string($_POST['email'])) ;
$registerquery = mysql_query("UPDATE `registration`
SET `Activation` '".$activation."'
WHERE email= '". trim($email) ."'");
```
Please move to PDO or mysqli as mysql is already deprecated.
Here is another answer: It seems you are trying to overwrite an existing value use an UPDATE statement and not an INSERT statement this is the reason why it is not working. INSERT works when you are trying to insert a new value there should not be a condition in it (where clause).
Here is another answer: check this ```registration```(```Activation```) it does not seem correct, the ` should maybe be ' and maybe you should start the query with @ in order to avoid sql injection attack
Comment for this answer: Back ticks (`) are allowed in mysql, are used to denote field names, So should not be used around `registration`. See http://stackoverflow.com/questions/261455/using-backticks-around-field-names
|
Title: Phone won't play the on-click sound
Tags: java;android;audio;onclicklistener
Question: I am currently developing an android application in which purpose is to play a large variety of every-day sounds on click.
I have 3 activities : home, animaux and transports.
Home is fine, animaux is fine (it plays all the sounds without any problems).
But I want to integrate admob on Transports acivity. Ads display well, but when I cluck on the sounds buttons, nothing happens. If you could help me understand my mistake and how to fix it, it would be very nice !
Here is transports.java
```public class Transports extends Activity {
private AdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxx"
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="@+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private MediaPlayer mPlayer = null;
/** Called when the activity is first created. */
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
Button btn_sound_sncf2 = (Button) findViewById(R.id.sncfnew);
btn_sound_sncf2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playSound(R.raw.sncf2);
}
});
Button btn_sound_sncf1 = (Button) findViewById(R.id.sncf1);
btn_sound_sncf1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playSound(R.raw.sncf1);
}
});
}
@Override
public void onPause() {
super.onPause();
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
}
private void playSound(int resId) {
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
```
And here is the transports.xml code :
```<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Transports" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="left"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxx"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
android:gravity="top" >
</com.google.ads.AdView>
<Button android:id="@+id/sncfnew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/sncf1"
android:layout_below="@+id/sncf1"
android:layout_marginTop="38dp"
android:text="@string/sncfnew" />
<Button android:id="@+id/sncf1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:text="@string/sncf1" />
</LinearLayout>
</RelativeLayout>
```
I wonder if the problem isn't in my xml file : I have a lot of difficulties to maker a clear interface with the linearlayout required by admob.
Here is the accepted answer: You aren't actually setting the listeners. You have that code in a method:
```public void onCreate1(Bundle savedInstanceState) {
```
that is never called. Move that code to the actual ```onCreate()``` method and it should work fine.
|
Title: Insert an image StaggeredGridView that is upload by the user !! The argument type 'File' can't be assigned to the parameter type 'String'
Tags: string;image;file;flutter;staggered-gridview
Question: I want to create a StaggeredGridView and fill it with images that the user uploads. The problem is that the type of StaggeredGridView is String or ```ImageProvider<Object>``` and the file is ```PickedFile``` or File
What is the solution ??
```class GalleryClassOneState extends State<GalleryClassOne> {
List<File> arrayImage = [];
File sampleImage;
final _picker = ImagePicker();
// @override
// void initState() {
// super.initState();
// DatabaseReference images =
// FirebaseDatabase.instance.reference().child("NeuralNetwork");
// }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Galeria clase 1'),
),
body: Container(padding: EdgeInsets.all(8), child: galeria(arrayImage)),
floatingActionButton: FloatingActionButton(
onPressed: _optionsDialogBox,
tooltip: 'Pick Image',
child: Icon(Icons.add_outlined),
),
);
}
Widget galeria(List<File> arrayImage) {
return StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: 11,
itemBuilder: (BuildContext context, int index) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.deepPurple,
child: Column(
children: <Widget>[
Image.network(arrayImage[index])
],
),
),
);
},
// staggeredTileBuilder: (int index) => new StaggeredTile.fit(1),
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 2 : 1),
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
);
}
}
```
Here is another answer: We will need to work with the images as bytes instead of files. First, make ```arrayImage``` a ```List<Uint8List>```. Here we will store a list of the byte arrays representing an image loaded in memory. Update the ```galeria()``` method to accept a ```List<Uint8List>``` as well.
Now in the ```optionsDialogBox()``` method, we will use the results of the ```_picker``` like so:
```_picker.getImage(source: ImageSource.gallery).then((pickedFile) {
// read the bytes from the PickedFile
pickedFile.readAsBytes().then((bytes) {
// add the image as bytes to the arrayImage list and update the UI
setState(() => arrayImage.add(bytes));
});
});
```
When we create our ```Image``` widget, we will use the ```Image.memory()``` constructor passing to it the bytes representing our image.
```Image.memory(arrayImage[index])
```
|
Title: HTML body margin and padding set to zero cause image in box to be clipped
Tags: html;css
Question: I have a logo laid out in a box at the top of my page using the following style elements:
```div.imgBox {
margin: 0%;
padding: 1%;
border: 0px;
background-color: #00A7FF;
}
div.imgBox img {
display: inline;
margin: 0px;
padding: 1%;
border: 0px solid #00A7FF;
}
```
Which does an okay job of allowing me to position the image how I want it in an area at the top of my page (along with some other elements such as nav items). I'd like the whole thing to display without a border so it fills up the whole of the top of the browser window. I can achieve this by adding:
```body {
margin: 0px;
padding: 0px;}
```
But when I do this it causes the image in the box to be clipped. I'm sizing the image in the html:
```<img alt="Logo" src="images/Logo.gif" style="width:15%; height:15%">
```
The image only clips when I add the body margin and padding, my question is: how do I get the elements at the top of the page to display so they take up the whole browser window width and go right to the top without the image clipping?
Here is the whole source, as requested:
``` div.imgBox {
margin: 0%;
padding: 1%;
border: 0px;
background-color: #00A7FF;
}
div.imgBox img {
display: inline;
margin: 0px;
padding: 1%;
border: 0px solid #00A7FF;
}
.hdrBox {
display: inline;
float: left;
margin: 0px;
width: 100%;
background-color: #00A7FF;
}
a:link {
color: #FFFFFF;
background-color: transparent;
text-decoration: none;
color: #FFFFFF;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: #FFFFFF;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: #FFFFFF;
background-color: transparent;
text-decoration: none;
}
a:active {
color: #FFFFFF;
background-color: transparent;
text-decoration: none;
}
navBar{
float: right;
right: 5vw;
top: 10vw;
list-style-type: none;
margin: 0;
padding: 0;
}
navElement{
font-family: "Arial", Helvetica, sans-serif;
font-size: 2vw;
color: #FFFFFF;
float: right;
display: block;
width: 10vw;
border: 0.25vw solid #FFFFFF;
padding-left: 1vw;
padding-bottom: 0.25vw;
padding-top: 0.25vw;
margin: 0.25vw;
}
```
That's in style tags in the head section of the HTML and then some fairly simple (until I get the style sorted!) HTML in the body:
```<body>
<div class="imgBox">
<img alt="Logo" src="images/Logo.gif" style="width:15%; height:15%">
<navBar>
<navElement><a href="#contact">Contact</a></navElement>
<navElement><a href="#examples">Examples</a></navElement>
<navElement><a href="#services">Services</a></navElement>
<navElement><a href="#profile">Profile</a></navElement>
<navElement><a href="#home">Home</a></navElement>
</navBar>
</div>
<div class="hdrBox">
</div>
```
I plan to move the style elements to a separate CSS once I've got it sorted. This works fine but when I add the aforementioned body margin padding elements to the start of this it clips the image.
This is how it displays in Firefox. Note the clipping on the text at the bottom and left of the logo, minor admittedly but still annoying the heck out of me!
Comment: Do you have a live link?
Comment: Can you upload a test page that reflects the issue? Makes it a lot easier since we're dealing with an image issue.
Comment: I'm not seeing any cutoff. All that happens is the whitespace disappears. What browser are you using?
Comment: Is it doing it for you on the online version? If not, you may try clearing your cookies.
Comment: Bah, cache, not cookies. Anyways, the image you show is exactly what I see, which seems normal. How would you want it to look?
Comment: Sounds good. I don't suppose you're trying to make it to where the image doesn't shift. As in, remove the white by filling it with blue?
Comment: But there are no white gaps. Not even in your image. Unless you're talking about on the bottom of the blue?
Comment: I can't see any clipping of text at the bottom nor left either
Comment: Sorry, no building this locally before deploying to my hosting service
Comment: http://www.helpyouin.com/indexTest.html uploaded to this address - pls ignore annoying dialogs!
Comment: Firefox and have also tried in ie
Comment: Have uploaded image as it appears in my browser window - note the clipping of the text at the bottom and left - this is in the online version and also how it appears locally.
Comment: I don't appear to have any cookies for this URL. Gotta go to work now so won't be able to try anything until this evening
Comment: Will post image when home, maybe being too fussy/expecting too much of the web
Comment: @David not fussed about whether it moves much, just want no white gaps if possible. Btw, displays perfectly on my phone! Samsung, chrome browser
Comment: @dura thanks, another piece of the puzzle!
Comment: Apologies for confusion. There are no white gaps around blue header because I've added the body margin padding =0, which does as expected. The issue is when I do this I get clipping of the logo (bits of the text missing at bottom and left) this is what the uploaded image shows but apparently it's peculiar to my home system.
Comment: It is sounding increasingly likely that the issue is peculiar to my home setup. You guys all say it looks okay in your browsers. I've been doing this on a thinkpad hooked up to a second monitor via IBM docking station. Is it possible that the browser is struggling with a system running two monitors at different resolutions? This might be a forehead slap moment! Will have a play when I get home in around 5 hours. First time in ages that I've done any web stuff and first time with this setup. Will post here later with outcome.
Here is another answer: I must apologise, I think it must have been my twin screen setup! It displays perfectly on my laptop when I run it in single screen mode. MASSIVE facepalm! When I reconnect the second monitor and refresh the clipping is still evident (although apparently slightly less so since a reboot so maybe Dave had something with the cache issue?) Thanks to all who've contributed and SIGNIFICANT apologies for having wasted your time on this! Really should have stripped it down to basics and tried to remove all variables before posting, I've overcomplicated the issue (gonna claim noob numpty for my lack of experience in website building as the cause).
Anyway, big thank you for being my rubber ducks (Coding Horror - Rubber Duck Problem Solving)
Tempted to give myslef a downvote for this...
|
Title: Elasticsearch mapping: How to analyze or map to numeric fields?
Tags: elasticsearch;mapping;elasticsearch-analyzers
Question: I want to index the ```month``` field of a bibtex entry into elasticsearch and make it searchable via the ```range``` query. This requires the underlying field type to be some kind of numeric datatype. In my case ```short``` would be sufficient.
The bibtex ```month``` field in its canonical form requires a three character abbreviation, so I tried to use the ```char_filter``` like so:
```...
"char_filter": {
"month_char_filter": {
"type": "mapping",
"mappings": [
"jan => 1",
"feb => 2",
"mar => 3",
...
"nov => 11",
"dec => 12"
]
}
...
"normalizer": {
"month_normalizer": {
"type": "custom",
"char_filter": [ "month_char_filter" ],
},
```
And put up mappings like this:
```...
"month": {
"type": "short",
"normalizer": "month_normalizer"
},
...
```
But it doesn't seem to work since the ```type``` field doesn't support normalizers like this, as well as it doesn't support analyzers.
So what would be the approach to implement such a mapping as shown in the ```char_filter``` part so there are range query possibilites?
Here is the accepted answer: Your approach intuitively makes sense, however, normalizers can only be applied to ```keyword``` fields and analyzers to ```text``` fields.
Another approach would be to leverage the ingest processors and use the ```script``` processor to do that mapping at indexing time.
Below you can find a simulation of such a ```script``` processor that would create a new field called ```monthNum``` based on the month present in the ```month``` field.
```POST _ingest/pipeline/_simulate
{
"pipeline": {
"processors": [
{
"script": {
"source": """
def mapping = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
ctx.monthNum = mapping.indexOf(ctx.month) + 1;
"""
}
}
]
},
"docs": [
{
"_source": {
"month": "feb"
}
},
{
"_source": {
"month": "mar"
}
},
{
"_source": {
"month": "jul"
}
},
{
"_source": {
"month": "aug"
}
},
{
"_source": {
"month": "nov"
}
},
{
"_source": {
"month": "dec"
}
},
{
"_source": {
"month": "xyz"
}
}
]
}
```
Resulting documents:
```{
"docs" : [
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 2,
"month" : "feb"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 3,
"month" : "mar"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 7,
"month" : "jul"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 8,
"month" : "aug"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 11,
"month" : "nov"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 12,
"month" : "dec"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"monthNum" : 0,
"month" : "xyz"
},
"_ingest" : {
"timestamp" : "2019-05-08T12:28:27.006Z"
}
}
}
]
}
```
Comment for this answer: Thank you, those are two completely new aspects to me, I'll dig into it right away ! :) I think scripting is the way to go anyway, because i can't even guarantee that every `month` entry follows the three character guidelines.
|
Title: Make a GIF play exactly once with Python Wand
Tags: python;python-3.x;gif;animated-gif;wand
Question: I can create an animated GIF like this:
```from wand.image import Image
with Image() as im:
while i_need_to_add_more_frames():
im.sequence.append(Image(blob=get_frame_data(), format='png'))
with im.sequence[-1] as frame:
frame.delay = calculate_how_long_this_frame_should_be_visible()
im.type = 'optimize'
im.format = 'gif'
do_something_with(im.make_blob())
```
However, an image created like this loops indefinitely. This time, I want it to loop once, and then stop. I know that I could use ```convert```'s ```-loop``` parameter if I were using the commandline interface. However, I was unable to find how to do this using the Wand API.
What method should I call, or what field should I set, to make the generated GIF loop exactly once?
Here is another answer: You'll need to use ```ctypes``` to bind the wand library to the correct C-API method.
Luckily this is straightforward.
```import ctypes
from wand.image import Image
from wand.api import library
# Tell Python about the C-API method.
library.MagickSetImageIterations.argtypes = (ctypes.c_void_p, ctypes.c_size_t)
with Image() as im:
while i_need_to_add_more_frames():
im.sequence.append(Image(blob=get_frame_data(), format='png'))
with im.sequence[-1] as frame:
frame.delay = calculate_how_long_this_frame_should_be_visible()
im.type = 'optimize'
im.format = 'gif'
# Set the total iterations of the animation.
library.MagickSetImageIterations(im.wand, 1)
do_something_with(im.make_blob())
```
|
Title: The app is disconnected after a second
Tags: r;shiny;r-markdown;shiny-server
Question: I ran shiny app in linux.
I open the browser in the url: http://(631)541-6603:4949/sample-apps/MonitorUI/
The page is open but after a second disconnected.
I check the log file and it write to me this massage:
Error in eval(expr, envir, enclos) :
You are attempting to load an rmarkdown file, but the
rmarkdown package was not found in the library. Ensure that
rmarkdown is installed and is available in the Library of the
user you're running this application as.
Calls: local -> eval.parent -> eval -> eval -> eval -> eval
Execution halted
I already downloaded the "rmarkdown" package. and it updated.
What is the problem? i don't find anything for this problem in the web.
the sample app that given by shiny-server package:http://(631)541-6603:4949/sample-apps/hello/ is working so what is the problem?
Thanks.
Comment: I get this error when I go on the page :`Error in library("RODBC") : there is no package called 'RODBC'`, did you install that package?
Comment: Yes, it wasn't easy. this made problems too. But I found something in the web.
|
Title: MPMoviePlayerController controls hide \ show notification?
Tags: ios;mpmovieplayercontroller
Question: How can I detected when user touch to hide or show the MPMoviePlayerController controls ?
Is there a notification or other way ?
Comment: There is unfortunately no such thing.
Comment: Maybe if you explained a bit what you where trying to achieve, we could suggest a workaround?
Comment: @Till
I have MPMoviePlayerController in full screen. the video frame is diffrent then the MPMoviePlayerController frame (depends on the video offcourse),
I want to detect when the user tap on the area outside the video but inside the MPMoviePlayerController.
For example, like in UIImageView and UIImage when you can know the size of the uiimage insdie the uiimageview. thanks for trying to help.
Here is the accepted answer: The official answer would be; not possible.
Reasoning:
The ```MPMoviePlayerController``` is to be regarded entirely opaque and should not be modified / accessed other than the documentation supports.
From its reference:
```
Consider a movie player view to be an opaque structure. You can add
your own custom subviews to layer content on top of the movie but you
must never modify any of its existing subviews.
```
However, you may get away by adding you own gesture recognizer to the view hierachy exposed by that controller. Make sure that your newly introduced gestures dont interfere with the existing (```requireGestureRecognizerToFail``` etc.).
But note, that is subject to break on every new iOS release as you will need to modify its existing gesture recognizers and that might be considered as a dealbreaker for submitting to iTunes. From my personal experience, that is not commonly detected by apple's review team and therefore could be an option.
The only "perfectly legal" option you have is disabling the control interface altogether (setting ```MPMovieControlStyle```, to ```MPMovieControlStyleNone```) and adding your own, resembling the original interface as far as you need it. Note that the complete functionality of that original interface is not entirely trivial - plan more than a day for that task. I have done loads of stuff like that and I can tell you that even after that experience, I would plan a week for fully implementing those things.
|
Title: ASP.NET Core MVC Select with dynamic searchig
Tags: javascript;asp.net;asp.net-mvc;asp.net-core
Question: I have a Login page, and I want to implement when an user type the username for example "Jh", because he is called Jhon, then next to the Login form there is a selectlist, and listing all the usernames from the database that contains Jh, and it should be dynamic, I mean if the input changes then update the search automatically.
Here is my view
```<div class="row justify-content-center">
<div class="col-md-7">
<form asp-action="Login">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
@if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
@ViewBag.Message
</span>
}
@Html.HiddenFor(x => x.ReturnUrl)
<div class="form-group">
<label asp-for="UserId" class="control-label"></label>
<input asp-for="UserId" class="form-control" />
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
@*<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="RememberLogin" /> @Html.DisplayNameFor(model => model.RememberLogin)
</label>
</div>
</div>*@
<div class="form-group">
<input type="submit" value="Bejelentkezés" class="btn btn-primary w-100" />
</div>
</form>
</div>
<div class="col-md-5">
<div class="form-group col-md-6">
<select asp-for="UserId" asp-items="ViewBag.Users" size="6" multiple class="form-control"></select>
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
</div>
</div>
<script>
$("#search_id").keyup(function () {
//call ajax method
});
</script>
```
Here is my controller (Im using stored procedures):
``` public IActionResult Login(string ReturnUrl = "/")
{
LoginModel objLoginModel = new LoginModel();
objLoginModel.ReturnUrl = ReturnUrl;
string sqlQuery = "execute GetUsers";
var result = _context.GetUsers(sqlQuery);
ViewBag.Users = new SelectList(result, "UserId", "UserId");
return View("Login");
}
```
Here is another answer: I write a simple demo here without any third part plugin, It is a basic demo to show how to achieve dynamic search, You can refer and make some changes to meet the needs of your own project. I hople it is what you want.
Model
```public class Student
{
public string Id { get; set; }
public string Name { get; set; }
}
```
View
```@model Student
<input asp-for="@Model.Name" oninput="Search(this.value)"/>
<div id="result"></div>
@section Scripts
{
<script>
function Search(data) {
var value ={
"name": data
}
$.post({
url: 'https://localhost:7209/Home/Download1',
ethod: 'Post',
data: value,
success: function (data) {
result = '';
for (var i = 0;i<data.length;i++){
result = result +'<tr><td>'+data[i].id+'</td><td>'+data[i].name+'</td></tr>';
}
document.getElementById("result").innerHTML = '<table class="table table-striped table-bordered zero-configuration dataTable" role="grid">'
+'<thead><tr><th>Id</th><th>Name</th></tr></thead>'
+'<tbody>'+result+'</tbody>'
+'</table>';
}
})
}
</script>
}
```
Home/Download1
```[HttpPost]
public IActionResult Download1(string name)
{
//For testing convenience, I just hard code here, you can change it and select data from database
var result = Students.Where(x => x.Name.Contains(name)).ToList();
return Json(result);
}
```
Demo
Comment for this answer: HI @kajahun123, If my answer help you resolve your issue, could you please accept as answer? Thanks.
|
Title: i have problem in accuracy when i merge 2 cnn to binary classification for 1D data
Tags: python;tensorflow;conv-neural-network
Question: i have problem in accuracy when i merge 2 cnn to binary classification for 1D data
the code
```history = model_combined.fit(X_train, Y_train, epochs=5, batch_size=64,verbose = 1,validation_data=(X_test,Y_test))
```
```ValueError: Layer \"model_9\" expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 12) dtype=float32>]\n"```
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Please edit your question to improve readability.
Comment: Welcome to Stack Overflow! Please take the [tour]. I've edited your question to improve the readability. For future reference, please read [code formatting help](/editing-help#code). See also [How to ask a good question](/help/how-to-ask).
|
Title: Combine three Images into single image in asp.net
Tags: c#;html;css;asp.net;image
Question: In my web application, I have 3 images I need to combine into a single images(vertical alignment) images. I have code for two images into single image but they are merged side by side. I need up and down and also how to add third image.
The code I found on the web:
I tried code for 2 images:
.aspx:
```<div>
<asp:Button ID="Button1" runat="server" Text="Merge" onclick="Button1_Click"/>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/Flower2.jpg" Height="129px" Width="210px"/><br />
<asp:Image ID="image2" runat="server" ImageUrl="~/Images/Flower4.jpg" Height="129px" Width="210px"/><br />
<asp:Image ID="MergedCombinedImage" runat="server" />
</div>
```
.cs
```protected void Button1_Click(object sender, EventArgs e)
{
string img1path = MapPath("~/Images/Flower2.jpg");
string img2path = MapPath("~/Images/Flower4.jpg");
// Load two Images to be combined into Image Objects
System.Drawing.Image img1= System.Drawing.Image.FromFile(img1path);
System.Drawing.Image img2= System.Drawing.Image.FromFile(img2path);
// Create a Resultant Image that’ll hold the above two Images
//Here i am creating the final image with width as combined width of img1 and img2 and height as largest height among img1 and img2
using (Bitmap FinalBitmap = new Bitmap(img1.Width + img2.Width, img2.Height > img1.Height ? img2.Height : img1.Height)) //This condition how can i add img3
{
using (Graphics FinalImage = Graphics.FromImage(FinalBitmap))
{
// Draw the first image staring at point (0,0) with actual width and height of the image, in final image
FinalImage.DrawImage(img1, new Rectangle(0, 0, img1.Width, img1.Height));
// and Draw the second image staring at point where first image ends in the final image and save changes
FinalImage.DrawImage(img2, img1.Width, 0);
FinalImage.Save();
// Write the bitmap to an image file and you’re done
FinalBitmap.Save(MapPath("~/ResultImages/Outputimg.jpg"));
MergedCombinedImage.ImageUrl = "~/ResultImages/Outputimg.jpg";
}
}
}
```
Here is the accepted answer: Well, the code you have is merging it side by side. Actually, all of it is. I guess you didn't write it yourself, but instead just grabbed it from somewhere. All you really need to do is a small swap in the logic and you are done:
The new bitmap you instantiate is a sum of both widths and the max height out of the two images is chosen. You need to swap this to be a sum of max heights and the max width.
Then you draw the first image to it's full size. This can be left untouched.
Then you proceed to draw the second image at the X that corresponds to where the first image ends. Instead, you should set the starting X coordinate for the second image to 0 and the Y coordinate to the first image's height.
Comment for this answer: Check the line where you are instantiating the final image, as well as the line where you draw the second image. Somewhere you are not providing the correct height. Just to be sure, add the changes you ended up with as a second code block, this way we don't have to be guessing.
Comment for this answer: Hi Boris Makogonyuk, i followed your instructions and i did changes in my code but i get result image vertically formed but second image not showing properly i attached image to my code i updated with image name like `Image Not form well` my code please see once
Comment for this answer: `using (Bitmap FinalBitmap = new Bitmap(img1.Height + img2.Height, img2.Width > img1.Width ? img2.Width : img1.Width))` The first argument for the Bitmap constructor is Width and then Height. Just swapping the property called does not change the order of the parameters automagically for you. Change it to `using (Bitmap FinalBitmap = new Bitmap(img2.Width > img1.Width ? img2.Width : img1.Width, img1.Height + img2.Height))`
Comment for this answer: i made changes what your said i updated my code can you please see my updated code and please tell me where i did mistake
Comment for this answer: Yes, but you would need to calculate the total Width and Height separately first and then iterate through the collection of images drawing them in whatever order you want. Try doing it yourself first and if you can't figure it out - open a new question. People will help you with your code, maybe even with someone's code, but nobody will write it for you. Here is an example of merging multiple images into one: http://stackoverflow.com/questions/13248897/merge-an-array-of-bitmaps-into-a-single-bitmap
Comment for this answer: Hi, thank you for your responding, By using the above code is it possible to take multiple images and merge into single image.can you please tell me. I need to add another image and how can i take `using (Bitmap FinalBitmap = new Bitmap(img2.Width > img1.Width ? img2.Width : img1.Width, img1.Height + img2.Height))` this condition into another image and is it possible to take multiple images.Please tell me
|
Title: how delete a data in core data with tableview
Tags: ios;objective-c;uitableview;core-data
Question: I can not find how to delete a core data entity instance from my table view.
This is how I update the table view with information from core data:
```- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Datos * record = [self.fetchedRecordsArray objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@ ",record.punto];
UIImage* image = [UIImage imageWithData:record.imagen];
cell.imageView.image = image;
return cell;
}
```
and I am trying to use the following function to delete the entity instance, but it isn't working:
```-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
```
Comment: Why not to use NSFetchedResultsController??
Here is another answer: You need to delete the entity instance from the managed object context:
```NSManagedObjectContext *moc = record.managedObjectContext;
Datos * record = [self.fetchedRecordsArray objectAtIndex:indexPath.row];
[self.fetchedRecordsArray removeObject:record];
[moc deleteObject:record];
NSError *error;
if (![moc save:&error]) {
NSLog(@"Save error181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16 %@", error);
}
```
this goes in ```tableView:commitEditingStyle:forRowAtIndexPath:```
(Assuming that ```Datos``` is your managed object subclass)
Comment for this answer: Forgot the save. Debug, is the object deleted? What is the save error?
Comment for this answer: The error is that whatever you're using to populate the table (provide the row count) isn't having an item removed. My answer is now removing an item from your array and Core Data. That should cover the bases. What do you use the return the row count?
Comment for this answer: ok, yes it is, but the error is the index of the row of tableview i update my question
Comment for this answer: the error is not the elimination of the data in the core data, the error is not cleared in the tableview, I'm using [tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: indexPath] withRowAnimation: UITableViewRowAnimationAutomatic], but does not work
Comment for this answer: return [self.fetchedRecordsArray count];
Here is another answer: Well, i'm not sure where you get your data from your CoreData but you need to call a that kind of snippet, it won't delete by itself when deleting row
```- (void) deleteElement:(NSString*)elementId{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"YourTable" inManagedObjectContext:self.managedObjectContext]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"id=%@",elementId]];
NSError *error=nil;
NSManagedObject *fetchedElement = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];
[self.managedObjectContext deleteObject:fetchedElement];
if (![self.managedObjectContext save:&error]) {
NSLog(@"problem deleting item in coredata : %@",[error localizedDescription]);
}
}
```
And your code should look like :
```-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self deleteElement:idOfElementToDelete];
}
```
this is the error:
'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Comment for this answer: I'm sorry, you're right the error is not the elimination of the data in the core data, the error is not cleared in the tableview, I'm using [tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: indexPath] withRowAnimation: UITableViewRowAnimationAutomatic], but does not work
Comment for this answer: You shouldn't add another problem in an answer, it won't help somebody with the same problem, and could be confusing. It is better to add a comment.
Your new error has nothing to do with CoreData, it says that if you delete a row, the new total should match the number given in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
Comment for this answer: You can check that link http://stackoverflow.com/questions/5043729/core-data-example-invalid-update-invalid-number-of-rows-in-section-0
It is about inserting a new row but it is the same issue.
|
Title: Can we assign custom name for network interface on Windows 10?
Tags: network-programming;windows-10;naming-conventions;network-interface
Question: Currently when I connect a second USB ethernet device on windows PC, it shows up as Ethernet 2(or any other name which OS allocates depending on port). Can we customize this name for a specific device that is connected? For example if I connect a second USB wifi adapter from Netgear, I need it to be "Netgear" instead of "wi-fi 2" ?
Comment: I assume you mean programmatically, since you posted here instead of e.g. http://superuser.com/? Then you need to be more specific, like telling us in what programming language you're working, what you have tried so far, how it did or didn't work etc. Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and of course [the help pages](http://stackoverflow.com/help) (if you haven't done it yet).
Comment: I know that we can rename the interface manually and through the system registry. But I need something which is persistent. I want to know what aspect of windows is responsible for assigning names to network interfaces automatically. I looked through the network driver and host controller driver codes but I could not find where exactly the name allocation is done.
|
Title: Joda Time - Get date difference
Tags: java;jodatime
Question: I'm currently trying to get the difference between two date and return the difference in months. Somehow i can't get it right (read other threads about JT). Here's what i have so far:
```public final class DateUtils {
private static DateTime dateTime = new DateTime();
private static Integer months;
/**
* Gets the difference in months, between local time and user's birth date
*/
public static Integer getMonthDiff(User user) {
months = Months.monthsBetween(dateTime, user.getUserDetails().getBirthDate()).getMonths();
return months;
}
}
```
I'm using this Class / Method throughout my code, in order to get for example, users with the account created last year (just an example).
```public List<User> findCreatedLastYear() {
List<User> users = findAll();
List<User> tempList = new ArrayList<>();
for (User user : users) {
if( DateUtils.getMonthDiff(user) == 12){
tempList.add(user);
}
}
LOGGER.log(Level.INFO, String.format("{%d} user(s)created an account last year", tempList.size()));
return tempList;
}
```
My JUnit test fails and i'm not sure where the mistake is.
```@Test
public void testFindLastYear() throws Exception {
User user = userService.findAll().get(0);
user.setAccountCreated(new DateTime(2014, 3, 3, 0 , 0, 0));
Assert.assertNotNull(userService.findCreatedLastYear());
}
```
It fails as it found 0 users with that condition. However i'm not using a DB (i'm generating the users through a class).
The cause I think is that somewhere i'm not using Joda Time correctly.
Here is what i get from UT: INFO: {0} user(s)created an account last year
Here is how i generate (simulate a DB).
List users = new ArrayList<>();
```for (int i = 0; i < size; i++) {
User user = new User();
user.setUsername("username_" + i);
user.setPassword("psd_" + i);
user.setEmail("username_" + i + "@dnet.org");
user.setAccountCreated(new DateTime());
user.setLastLogin(new DateTime());
UserDetails userDetails = new UserDetails();
userDetails.setFirstname("FirstName_" + i);
userDetails.setLastname("LastName_" + i);
userDetails.setBirthDate(new DateTime());
user.setUserDetails(userDetails);
users.add(user);
}
```
Comment: Wouldn't it be easier to retrieve data using SQL (assuming you're using DB connection)? SELECT e FROM User e WHERE e.dateCreated BETWEEN :before AND :after
Comment: How does your test fail? You do get an empty list even if no matches are found. Also, why are you only testing for `== 12`? Do you only want to find from the same month last year?
Comment: I'm testing for 12 as my method should return the diff in months. So I want to get all users from the list where the diff between their birthdate and current system time is 12.
Comment: It doesn't have to be like this exactly, interested in othere approaches as well for this.
|
Title: How do I stretch the Y axis in chart.js?
Tags: chart.js
Question: I'm looking to product a fairly small-sized comparative line chart where the actual data values aren't significant (the associated data table always accompanies the chart) but the point of the chart is to visually show the daily/weekly trend.
At full size the graph looks nice.
But when the containing div is constrained to shrink the size, the graph Y-scale shrinks much more in proportion than the X-scale.
What I need instead is something that looks like this.
What am I missing? I can't find any options that affect this.
Here is another answer: You can set the ```maintainAspectRatio``` option to false in the root of the options object
Comment for this answer: Beautiful!
I assumed there had to be *something* that controlled this, just wasn't looking in the right place, or for the right concept. Thanks!
|
Title: Target a different div on hover?
Tags: css;css-selectors
Question: I need to know whether it is possible to target a different element within a selector, eg: 'when I hover over this element, change this OTHER element'; something like:
```#gallery li:hover {
h2 {display:block}
}
```
So in the above example I'm trying to say that when I hover over the #gallery div, the h2 element will display as block.
CodePen: http://codepen.io/sad_muso/pen/JKdBox
Many thanks for your help
Comment: Obvious duplicate of http://stackoverflow.com/questions/4502633/how-to-affect-other-elements-when-a-div-is-hovered, which could have been found by googling for "css hover target other element".
Comment: This seems like more of a javascript solution. Im not sure if its possible in css but I can definitely provide a solution in jquery.
Comment: Not unless the element in question is nested within the element hovered over, or is the next direct sibling (using the `+` selector). Otherwise, explore javascript solutions.
Comment: It depends on where that elements is present in your markup.
Comment: To give a sensible answer we really need to see your HTML, please look at the "*[mcve]*" guidelines.
Here is another answer: See the css written by you is not valid as in side ```{}``` you can use css property but you cannot define any other element.
But yes there are some selector's in css like ```+```, ```~```.
Suppose the html is like this
```<ul>
<li>
<h2>...</h2>
</li>
</ul>
```
Then on hover of li you can do something in ```h2``` by applying css for child div like this.
```li:hover h2{
color:red;
}
```
```
A simple space defines that ```h2``` is child element of ```<li>```.
```
Suppose html is like this
```<ul>
<li>...</li>
<h2>...</h2>
</ul>
```
Then you can use this css to do something on ```h2``` on ```li``` hover
```li:hover + h2{
color:red;
}
```
```
```+``` defines that ```h2``` is placed next to ```li```
```
These are some examples of using css for appyling something on different element.
But if this doesn't meets you requirement then the only solution is to use jquery. In jquery it doesn't matter where are the elements written you can simply do like this
```$('li').hover(function(){
$('h2').css('color','red');
});
```
```
In above answer i am using ```<h2>``` as a child of ```<ul>``` just to give you example on the css rules but for valid html you can't use ```<h2>``` as a direct child of ```<ul>```.
```
Comment for this answer: I understand that you're just giving an example here, but you should probably specify that you cannot put `h2` as a direct child of `ul`.
|
Title: 'Unknown Provider' trying to Include angular-websocket in a MeanJS v0.4.1 app
Tags: javascript;angularjs;node.js;meanjs
Question: I am having a bit of difficulty using angular-websocket in a controller in a MeanJS application I am working on.
My Application is based on MeanJS v0.4.1.
I first installed it with:
``` bower install angular-websocket --save
```
This created the directory /public/lib/angular-websocket
Next I added it to /config/assets/default.js
``` lib: {
css: [
...
],
js: [
...
'public/lib/angular-websocket/angular-websocket.js'
],
tests: ['public/lib/angular-mocks/angular-mocks.js']
},
```
In my /modules/core/client/app/config.js file I have added it as a dependency:
``` var applicationModuleVendorDependencies = [
...
'angular-websocket'
];
```
And finally in my angular module itself,
``` angular.module('somemodule').controller('ModulenameController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'SomeModule', 'ngWebSocket',
function ($scope, $http, $stateParams, $location, Authentication, SomeModule, ngWebSocket) {
```
When I go to view my page I can see in the "Sources" tab of Chrome's Developer tools that it is included as a source,
I am trying to use this file with something like this in my controller:
``` var dataStream = ngWebSocket('wss://www.somesite.com/realtime');
dataStream.onMessage(function(message) {
console.log("dataStream Message: " + message);
$scope.orderBook = message;
});
dataStream.send('{"op":"subscribe", "args":"someargument"}');
```
However, my console shows the following error:
```Error: [$injector:unpr] Unknown provider: ngWebSocketProvider <- ngWebSocket <- ModuleNameController
```
Some of the things I have tried:
Changing The Reference Name
As per the documentation (https://www.npmjs.com/package/angular-websocket)
```angular.module('YOUR_APP', [
'ngWebSocket' // you may also use 'angular-websocket' if you prefer
])
```
I've tried using 'ngWebSocket', 'angular-websocket', but I still get the same issue.
I've tried looking through my code to see if maybe this was being redefined as the angularJS documentation here:
https://docs.angularjs.org/error/$injector/unpr
states that a cause of this error could be 'redefining a module using the angular.module API'.
Any help would be greatly appreciated.
Here is the accepted answer: The factory is actually named ```$websocket```, so you should do as follows:
``` angular.module('somemodule').controller('ModulenameController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'SomeModule', '$websocket',
function ($scope, $http, $stateParams, $location, Authentication, SomeModule, $websocket) {
```
Comment for this answer: No problem! glad to help :)
Comment for this answer: Thanks! This Worked! I'll accept your answer in 8 minutes
|
Title: How do C# lambdas work without a “return”?
Tags: c#;lambda
Question: I have occasionally come across statements like this
```school.Where(s => s.name == "foo")
```
Now I understand this is a lambda and I think I am comfortable with lambdas. I just started C# so I do have this question. In the statement
```s => s.name == "foo"
```
how is the evaluation return being done to determine true or false. I do not see a return statement ? All i see is a comparison operation in the lambda body and nothing being returned. Can anyone please explain this to me.
Here is the accepted answer: In this form the return is implicit. The lambda returns whatever the expression returns. You could also write it like this:
```s => { return s.name == "foo"; }
```
The reason why the return isn’t needed in the short form is because that’s how the language was designed. It makes things short and nice to use instead of forcing the developer to write unnecessary code.
Comment for this answer: Right. Just as reference: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator
Here is another answer: The returned value is always boolean and you can get it like below:
```s=> {retutn s.name=="foo";}
```
Here is another answer: The return statement is implied. If you were to add brackets around ```s.name == "foo"``` then you'd have to have a return. The compiler essentially creates a function to be called there for you. This is just syntax sugar. It's equivalent to creating a function yourself and passing that into the Where
Here is another answer: Lambda can be defined in two ways:
with curly braces: then you will have to write body of a method, just like in a regular method, i.e. with ```return```s, etc. Example
```var lambda = (string param) => { return param.Length; };
```
without curly braces: then the method has to contain one line, which also be the result of a method. Example:
```var lambda = (string param) => param.Length;
```
This is by design, to make one-line methods look nice and clean (especially in LINQ extensoin methods) :)
|
Title: React & clsx: add a class name if the current item in a mapped array is the first of multiple items
Tags: javascript;reactjs;typescript;clsx
Question: I've got the following code, and I need to add some new functionality to it. Basically, the map function is iterating through an array, and if there is only one item in the array, then I don't want to add a new class, but if this is the first item in an array of 2 items, I want to add a class name.
``` {section?.values?.link.map((link, index) => {
return (
<LinkComponent
key={index}
className={clsx({
"jc-left":
link?.values?.linkType !==
"primary-button",
})}
</LinkComponent>
...
```
I know it looks like the one that's already there, in that I put in the class name in quotes followed by a semicolon and then the rule, I just don't know how to write what seems like a complex rule to me. Any help is appreciated.
Here is the accepted answer: If I correctly understand your question is that you want to add className if you ```array.length > 1``` and then add class to the first item of the array.
```{section?.values?.link.map((link, index, self) => {
return (
<LinkComponent
key={index}
className={clsx({
"jc-left": link?.values?.linkType !== "primary-button",
"YOUR_CLASS": self.length > 1 && index === 0,
})}
</LinkComponent>
```
But what if you have more than two items then I assume that you will add class to all items except the last one
```{section?.values?.link.map((link, index, self) => {
return (
<LinkComponent
key={index}
className={clsx({
"jc-left": link?.values?.linkType !== "primary-button",
"YOUR_CLASS": self.length > 1 && (index + 1 !== self.length),
})}
</LinkComponent>
```
Comment for this answer: I didn't know about map's self param. That's pretty cool.
Here is another answer: If you want to render conditionally with clsx you can do this based on the two conditions:
```{section?.values?.link.map((link, index) => {
// Checks if array has more than 2 or 2 items and if the index is 0 which means that is the first item.
const hasConditionalClass = section?.values?.link.length >= 2 && index === 0;
return (
<LinkComponent
key={index}
className={clsx({
"jc-left": link?.values?.linkType !== "primary-button",
"condtional-class": hasConditionalClass
})}
</LinkComponent>
...
```
|
Title: ComboBox bound to ICollectionView is displaying incorrect SelectedItem
Tags: silverlight;mvvm;combobox;icollectionview
Question: I'm having an issue with a pair of combo box's in Silverlight 4.0.
The intention is to have two different comboboxes that read from the same list, but if any item selected in one won't show up in the other (as the underlying properties are not allowed to be the same).
E.g. (this is just example code, but identically represents how it works)
```<ComboBox ItemsSource="{Binding BackgroundColors}"
SelectedItem="{Binding SelectedBackgroundColor, Mode=TwoWay}" />
<ComboBox ItemsSource="{Binding ForegroundColors}"
SelectedItem="{Binding SelectedForegroundColor, Mode=TwoWay}" />
```
To allow for this dynamic filtering, I have 2 different ```ICollectionView```'s in my ViewModel that each combo box ```ItemsSource``` is bound to. Each ```ICollectionView``` has a source of the same ```ObservableCollection<T>``` but in the filter is set to filter out the other's selected item.
```private ObservableCollection<Color> _masterColorList;
public ICollectionView BackgroundColors { get; }
public ICollectionView ForegroundColors { get; }
```
When a SelectedItem is changed in the UI, the ViewModel properties are updated, and as part of that, the opposite ```ICollectionView``` is refreshed via ```.Refresh()```.
Eg.
```public Color SelectedForegroundColor
{
get { return _selectedForegroundColor; }
set
{
if (_selectedForegroundColor == value)
return;
_selectedForegroundColor = value;
BackgroundColors.Refresh();
RaisePropertyChanged(() => SelectedForegroundColor);
}
}
```
This allows the filter to rerun and change what is available to be selected.
This works pretty well, but there is a problem:
Say we have 3 colors in our master list:
Blue
Green
Red
Combo box 1 (CB1) is has selected Blue
Combo box 2 (CB2) has selected Green
Thus the combo boxes have these lists (bold is selected)
CB1
Blue
Red
CB2
Green
Red
If I then select Red in CB1, I would expect that Red would be removed from CB2 and Blue replace it. This happens correctly, BUT the displayed value changes from Green to Blue.
The underlying bound value doesn't get changed and the ICollectionView.CurrentItem is correct, but the display is clearly showing the wrong value.
What I think is happening is that because Green is earlier in the list, that it is getting confused with what is being shown. It also occurs if you are sorting the ICollectionView.
I've tried re-raising the property changed event notification for the changing combobox & selected item but this doesn't seem to work.
Has anyone seen this issue before or any ideas how I could fix it?
Here is another answer: There are at least 5 serious issues with binding of comboboxes.
Here I think you ran into
http://connect.microsoft.com/VisualStudio/feedback/details/523394/silverlight-forum-combobox-selecteditem-binding
this one.
Once you update itemssource binding stops working.
I used one of solutions available there, this code solved this issue for me:
```public class ComboBoxEx : ComboBox
{
#region Fields
private bool _suppressSelectionChangedUpdatesRebind = false;
#endregion
#region Properties
public static readonly DependencyProperty SelectedValueProperProperty =
DependencyProperty.Register(
"SelectedValueProper",
typeof(object),
typeof(ComboBoxEx),
new PropertyMetadata((o, dp) => {
var comboBoxEx = o as ComboBoxEx;
if (comboBoxEx == null)
return;
comboBoxEx.SetSelectedValueSuppressingChangeEventProcessing(dp.NewValue);
}));
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public object SelectedValueProper
{
get { return GetValue(SelectedValueProperProperty); }
set { SetValue(SelectedValueProperProperty, value); }
}
#endregion
#region Constructor and Overrides
public ComboBoxEx()
{
SelectionChanged += ComboBoxEx_SelectionChanged;
}
/// <summary>
/// Updates the current selected item when the <see cref="P:System.Windows.Controls.ItemsControl.Items"/> collection has changed.
/// </summary>
/// <param name="e">Contains data about changes in the items collection.</param>
protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Must re-apply value here because the combobox has a bug that
// despite the fact that the binding still exists, it doesn't
// re-evaluate and subsequently drops the binding on the change event
SetSelectedValueSuppressingChangeEventProcessing(SelectedValueProper);
}
#endregion
#region Events
private void ComboBoxEx_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Avoid recursive stack overflow
if (_suppressSelectionChangedUpdatesRebind)
return;
if (e.AddedItems != null && e.AddedItems.Count > 0) {
//SelectedValueProper = GetMemberValue( e.AddedItems[0] );
SelectedValueProper = SelectedValue; // This is faster than GetMemberValue
}
// Do not apply the value if no items are selected (ie. the else)
// because that just passes on the null-value bug from the combobox
}
#endregion
#region Helpers
/// <summary>
/// Gets the member value based on the Selected Value Path
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
private object GetMemberValue(object item)
{
return item.GetType().GetProperty(SelectedValuePath).GetValue(item, null);
}
/// <summary>
/// Sets the selected value suppressing change event processing.
/// </summary>
/// <param name="newSelectedValue">The new selected value.</param>
private void SetSelectedValueSuppressingChangeEventProcessing(object newSelectedValue)
{
try {
_suppressSelectionChangedUpdatesRebind = true;
SelectedValue = newSelectedValue;
}
finally {
_suppressSelectionChangedUpdatesRebind = false;
}
}
#endregion
}
```
Its not mine code, but one from articles related to this bug.
Comment for this answer: doh. Well I can recommend not to bind to ICollectionView maybe and try something easier like IEnumerable instead (for starters), I ran into big bug with CollectionViewSource here http://stackoverflow.com/questions/6305608/how-to-preserve-twoway-binding-of-currentitem-when-databinding-to-collectionview There are plenty problems with combobox bindings sadly. Ill think of other possible causes.
Comment for this answer: binding to combobox in silverlight is like the worst thing I encountered in my programming life. too many issues.. and not fixed yet. Its also annoying because you totally don't expect it to be so buggy.
Comment for this answer: Unfortunately this, or any of the other workarounds at that connect site, didn't seem to work. I believe the SelectedItem/SelectedValue binding is still working, but the visual display on the Combobox is incorrect.
Comment for this answer: Yeah, in a newer revision of our code, we have made the change back to ObservableCollection. Just a super annoying bug :/
|
Title: Join and Include in Entity Framework
Tags: c#;.net;sql;linq;entity-framework
Question: I have the following query of linq to entities. The problem is that it doesn't seem to load the "Tags" relation even though i have included a thing for it. It works fine if i do not join on tags but i need to do that.
``` var items = from i in db.Items.Include("Tags")
from t in i.Tags
where t.Text == text
orderby i.CreatedDate descending
select i;
```
Is there any other way to ask this query? Maybe split it up or something?
Here is the accepted answer: Well, the Include contradicts the where. Include says, "Load all tags." The where says, "Load some tags." When there is a contradiction between the query and Include, the query will always win.
To return all tags from any item with at least one tag == text:
``` var items = from i in db.Items.Include("Tags")
where i.Tags.Any(t => t.Text == text)
orderby i.CreatedDate descending
select i;
```
(Untested, as I don't have your DB/model)
Here's a really good, free book on LINQ.
Comment for this answer: Any suggestions on how to write it in some other way so i can get the tags and do a condition on them. It would be kind of simple in regular SQL.
Comment for this answer: Do you want to include ALL tags from ANY item with AT LEAST one tag == text?
|
Title: Communicate with Pi via Instant Messaging
Tags: raspbian;pi-2
Question: I'm currently working on a kitchen inventory system using a Raspberry Pi. I thought it would be fun to use an instant messaging service to access the inventory from remote and send the Pi commands, however I wasn't able to find anything useful.
I stumbled upon a WhatsApp library called ```yowsup2```, but apparently it will stop working at the end of June because WhatsApp is changing their protocol.
I know about DynDNS and Port Forwarding to access a website with the inventory running on the Pi, but I consider it a last resort if nothing else works.
Comment: How do you plan to secure such a system? As a rule of thumb when you can't find any existing work or examples it generally means one of two things - the idea is novel or there are better means to the same end.
Comment: You could use Facebook's [bot feature](https://developers.facebook.com/docs/workplace/integrations/custom-integrations/bots).
Here is another answer: You could use the Twitter API and create an account for the PI, have it use that as it's output which will obviously need to be truncated or paged. The upside is that if you sent that account to private and have it only listen to followed users for commands you could have the wife and your accounts on there.
|
Title: css every n-th img in new row
Tags: css;reactjs;css-selectors
Question: I have a react component and I would like to display inline-block 3 photos in a row with it's names under each photo, and every next 3 elements under (in new row) and so on...
I think I need to use something with```:nth-child(3n+1)``` but something goes wrong...
```const Photos=(props)=>{
return(
<div className="photos-list">
<img className="photo-img"
src={props.memoriesPath}
alt={props.memoriesName}
/>
<div className="photo-name">{props.memoriesName}</div>
</div>
)
}
export default Photos
```
Could you please tell me how should css look like?
Here is another answer: wrap all photos components in a div then style div with grid box like this:
```<div classname="parent">
<Photos />
<Photos />
<Photos />
</div>
```
and css:
```.parent {
display:grid;
grid-template-columns:auto auto auto;
}
```
Comment for this answer: thx...that works!
|
Title: is there any way to send a message using the Odoo mailing list?
Tags: python;xml;odoo
Question: I work on an Odoo module where I import the mailing class mailing list, this mailing list sends me emails and I want it to send me the phone numbers I added to the contact class. Have an idea of how I can proceed please
Comment: Maybe can this [Odoo forum's question](https://www.odoo.com/forum/help-1/question/how-can-i-add-more-information-to-internal-note-emails-sent-from-project-tasks-customer-project-deadline-145138) help you?
|
Title: How to get the playing file total time duration Media player
Tags: asp.net;javascript;media-player
Question: I use media player control to play mp3 files in asp.net application. I want to find When the playing process gets end and the total time require to finish the file using javascript.
Code:
``` <object id="mediaPlayer" classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
height="1" standby="Loading Microsoft Windows Media Player components..."
type="application/x-oleobject" width="1">
<param name="fileName" value="" />
<param name="animationatStart" value="true" />
<param name="transparentatStart" value="true" />
<param name="autoStart" value="true" />
<param name="showControls" value="true" />
<param name="volume" value="100" />
<param name="loop" value="true" />
</object>
```
Geetha.
Comment: Maybe you could show how you are *using* this media player control in your code.
Here is the accepted answer: Try to use: get_duration or get_durationString (in javascript may be "duration" or "durationString"). To see properties and methods exposed by WMP object you can download Windows Media Player SDK from Microsoft's site.
|
Title: running esdoc's got error
Tags: ecmascript-6;esdoc
Question: to generate document i want to use esdoc
```
esdoc -c esdoc.json
```
esdoc.json
```{
"source": "./src/",
"destination": "./doc"
}
```
./src/index.js
```/**
* @type {Object}
* @property {boolean} Foo.info
*/
var Foo = {
info: true
};
export default Foo;
```
but it shows
```\node_modules\esdoc\out\src\ESDoc.js:121
results.push(...temp.results);
^^^
SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
```
what did i wrong?
Here is the accepted answer: ESDoc supports Node.js v6.0.0 or later
```sudo npm cache clean -f
sudo npm install -g n
sudo n stable
```
Here is another answer: As one of the answers indicated, upgrade your node version - Had a similar problem and I did following (note I am on Mac OS X)
brew upgrade node
brew upgrade npm
sudo npm cache clean -f
sudo npm install -g n
nvm install 7.8.0
npm install -g esdoc
finally If you run
esdoc
It should give you doc directory as expected; Hope it clarifies and helps others ...
|
Title: Computer restarts while downloading Ubuntu
Tags: 12.10;13.04;windows-8;downloads;iso
Question: I have a question.
While downloading the Ubuntu ISO file, my computer restarts randomly. Why does this happen? What should I do? The browsers I have tried are Firefox and Chrome. I use Windows 8. I have tried both the versions 13.04 and 12.10. Please help me.
And is there a way to legally torrent Ubuntu?
Thanks in Advance.
Comment: Windows restarts while downloading a file? This probably isn't a problem with Ubuntu. Can you download other big files?
Comment: Do you have a torrent client you can download with?
Comment: Of course torrenting Ubuntu is legal, as it's free.
Comment: Yes. I regularly download files as big as 6GB. But not through browsers.
Here is the accepted answer: This is probably a problem with your web browser and big file downloads.
I suggest trying the torrent downloads:
13.04 64-bit: http://releases.ubuntu.com/raring/ubuntu-13.04-desktop-amd64.iso.torrent
12.04 64-bit: http://releases.ubuntu.com/quantal/ubuntu-12.10-desktop-amd64.iso.torrent
You can look at all the downloads for 13.04 here: http://releases.ubuntu.com/raring/
And for 12.04 here: http://releases.ubuntu.com/quantal/
I do not know the cause of windows randomly restarting during downloads of big files, but the torrents should work if the regular downloads do not.
|
Title: URLS in PhoneGap
Tags: cordova
Question: We are creating an PhoneGap App. In the Terms and conditions are dynamically updadted from the database. We have URLS as well in there. Would some one please tell how to open this URL in browser or APP when the user clicks on it.
Many Thanks
Kiran
Here is the accepted answer: To open a URL in the default browser, the following code will do the trick:
```window.open('http://example.com', '_system');
```
|
Title: Adding flutter page to another framework
Tags: flutter
Question: I want to add one of the pages from my flutter app to another app written in different framework (React, Ionic etc.) However, I don't want other developers to see my source code.
I was thinking about creating Flutter web app and hosting it. Then they can use their framework's webview libraries to access it. As far as I know Dart will be converted to low level js and other people won't be able to get my source code.
I also heard that I can create packages/modules and supply those to them (never done this before) I am not sure if they would be able to see my source code in that case.
Do I have any other options other than flutter web app?
Thank you
|
Title: Google static maps with directions
Tags: google-maps;google-maps-api-3;google-static-maps
Question: I have in my project list of generated places with mini maps. There should be 2 points on the map and colored road direction between this two points.
it should looks somehow like this:
This should be static image, because there will be many such pictures with different directions on the page. But as I see, Google Static map didn't allow to draw such image. There can be only direct line between two points, like this:
But I need direction on it...
I decided to use static map, because in my web application I receive coordinates of those 2 points, and it's easy to put it as variables in my PHP template if I use static maps.
But is it possible to receive direction as static image in same way?
I have found few solution with JavaScript API, but didn't find how to draw static image as I need...
Comment: You would need to use the [Directions API](https://developers.google.com/maps/documentation/directions/start) to get all the coordinates for that path, then pass all those coordinates to the static maps API in the `path` parameter. See https://developers.google.com/maps/documentation/static-maps/intro#Paths
Comment: Example URL here http://www.freakyjolly.com/convert-google-map-into-image-with-markers-and-paths/
Comment: @geocodezip I'm not sure about correct code for my case. Those question was related to what language?
Comment: related question: [google maps static map polyline passing through lakes, river, mountains](http://stackoverflow.com/questions/32255380/google-maps-static-map-polyline-passing-through-lakes-river-mountains)
Here is the accepted answer: You can do it in two steps.
Execute directions request from the PHP code to get the encoded polyline
Use encoded polyline from step 1 with static maps
E.g.
https://maps.googleapis.com/maps/api/directions/json?origin=Grodno&destination=Minsk&mode=driving&key=YOUR_API_KEY
This will return encoded polyline in routes[0]->overview_polyline->points
Now use the polyline in static map:
```https://maps.googleapis.com/maps/api/staticmap?size=600x400&path=enc%3AohqfIc_jpCkE%7DCx%40mJdDa%5BbD%7BM%7D%40e%40_MgKiQuVOoFlF%7DVnCnBn%40aDlDkN%7DDwEt%40%7DM%7DB_TjBy%7C%40lEgr%40lMa%60BhSi%7C%40%7COmuAxb%40k%7BGh%5E_%7BFjRor%40%7CaAq%7DC~iAomDle%40i%7BA~d%40ktBbp%40%7DqCvoA%7DjHpm%40uuDzH%7Dm%40sAg%7DB%60Bgy%40%7CHkv%40tTsxAtCgl%40aBoeAwKwaAqG%7B%5CeBc_%40p%40aZx%60%40gcGpNg%7CBGmWa%5CgpFyZolF%7BFgcDyPy%7CEoK_%7BAwm%40%7BqFqZaiBoNsqCuNq%7BHk%60%40crG%7B%5DqkBul%40guC%7BJ%7D%5DaNo%7B%40waA%7DmFsLc_%40_V%7Dh%40icAopBcd%40i_A_w%40mlBwbAiiBmv%40ajDozBibKsZ%7DvAkLm%5DysAk%7DCyr%40i%60BqUkp%40mj%40uoBex%40koAk_E_hG%7B%60Ac%7DAwp%40soAyk%40ogAml%40%7Bg%40qKsNeJw%5DeuA%7D%60Fkm%40czBmK%7Bg%40wCed%40b%40_e%40dT%7BgCzx%40csJrc%40ejFtGi%60CnB_pFhCa%60Gw%40%7Du%40wFwaAmP%7BoA%7Dj%40etBsRm_AiGos%40aCyy%40Lic%40tFohA~NeoCvC_%7CAWm~%40gb%40w~DuLex%40mUk_Ae_%40o_Aol%40qmAgv%40_%7DAaf%40qhAkMcl%40mHwn%40iCuq%40Nqi%40pF%7D%7CE~CyiDmFkgAoUedAcb%40ku%40ma%40cl%40mUko%40sLwr%40mg%40awIoA_aApDe~%40dKytAfw%40kyFtCib%40%7DA%7Bj%40kd%40usBcRgx%40uFwb%40%7BCulAjJmbC~CumAuGwlA_%5Du_C_PqyB%7BI%7DiAwKik%40%7DUcr%40ya%40up%40%7DkB%7DoCoQ%7Da%40aMyf%40an%40wjEimBuwKiYybC%7DLuyBoJ%7DhBuMieAwd%40i%7BB%7B~%40g%60D_Si%5Dsi%40%7Bk%40cPeSuH_T%7DNct%40kNcmC_Gyr%40mq%40_~AkmA%7DkCksByrE_N%7Bc%40oAcs%40%60J%7Bi%40t%7DByaHxNqt%40tGgxA%7CJ%7BkGeJ_aDsQi_HmFwuAmI%7BdA_XijByFgv%40%7DAiwBxDocAdM%7BlAtSmcAfUmaAptAmbGh~AcvGbwBc%7DHff%40shB~Isp%40nQu%7DB%60UsuCbBok%40l%40%7DzAhIwbA~OuaAnYwp%40rYwe%40%7CNke%40zc%40%7BhBrOwRdo%40sf%40xNaTb_%40uy%40ta%40k~%40xTap%40hl%40uiCre%40unHlIi~AlFsc%40rEkk%40aAce%40mL%7DlAwPcyB_GohBzDsqAtMqtA~h%40weDtFkd%40Bi%60%40_XwfEdAag%40dEkM%60%40zAqApJef%40%7BP_o%40sYys%40ai%40yf%40_j%40y_%40oi%40mVi%5EmFqSwAiPtDuQbc%40_nAtZyaAlEkc%40r%40eq%40%7CAo%5BrTwcAtVuz%40vQ%7Dd%40%7CPmb%40xT%7B%5CzZyd%40jG%7BRzL%7Dh%40jr%40ov%40rFiImFqPiD%7BJ&key=YOUR_API_KEY```
Comment for this answer: See also for potential snafus with API key restrictions: https://stackoverflow.com/a/52596973/721073
Comment for this answer: This answer helped me a lot. This tool can help you build a polyline as well: https://developers.google.com/maps/documentation/utilities/polylineutility. It takes a bit to get used to it. You can also use it to decode an existing polyline. This was helpful for debugging purposes.
Comment for this answer: And you need to add "enc%3A" before path. http://../staticmap?...&path=enc%3A(YOUR_PATH_WITHOUT_BRACKETS)
Comment for this answer: See also http://stackoverflow.com/questions/9015791/show-a-route-on-a-map/9024450#9024450
Here is another answer: I took Bedu33 logic in PHP and write it in javascript to generate the Google Maps Static Image in case someone needs it like I did. This code uses the response from the Directions API
```var request = directionsDisplay.directions.request;
var start = request.origin.lat() + ',' + request.origin.lng();
var end = request.destination.lat() + ',' + request.destination.lng();
var path = directionsDisplay.directions.routes[0].overview_polyline;
var markers = [];
var waypoints_labels = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
var waypoints_label_iter = 0;
markers.push("markers=color:green|label:" + waypoints_labels[waypoints_label_iter] + '|' + start);
for(var i=0;i<request.waypoints.length;i++){
//I have waypoints that are not stopovers I dont want to display them
if(request.waypoints[i].stopover==true){
markers.push("markers=color:blue|label:" + waypoints_labels[++waypoints_label_iter] + '|' + request.waypoints[i].location.lat() + "," +request.waypoints[i].location.lng());
}
}
markers.push("markers=color:red|label:" + waypoints_labels[++waypoints_label_iter] + '|' + end);
markers = markers.join('&');
alert("https://maps.googleapis.com/maps/api/staticmap?size=1000x1000&maptype=roadmap&path=enc:" + path + "&" + markers);
```
Comment for this answer: Thanks. This is exactly what i was looking for.
Here is another answer: I have created a small utility function for my website that does exactly what you need : https://github.com/bdupiol/php-google-static-map-directions
Given an origin, a destination and a array of waypoints (if needed), it gives you a clean Google Static Maps URL with driving path rendered between those points, and sets proper markers.
index.php
```<?php
include "static-map-direction.php";
$origin = "45.291002,-0.868131";
$destination = "44.683159,-0.405704";
$waypoints = array(
"44.8765065,-0.4444849",
"44.8843778,-0.1368667"
);
$map_url = getStaticGmapURLForDirection($origin, $destination, $waypoints);
echo '<img src="'.$map_url.'"/>';
```
static-map-direction.php
```<?php
function getStaticGmapURLForDirection($origin, $destination, $waypoints, $size = "500x500") {
$markers = array();
$waypoints_labels = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K");
$waypoints_label_iter = 0;
$markers[] = "markers=color:green" . urlencode("|") . "label:" . urlencode($waypoints_labels[$waypoints_label_iter++] . '|' . $origin);
foreach ($waypoints as $waypoint) {
$markers[] = "markers=color:blue" . urlencode("|") . "label:" . urlencode($waypoints_labels[$waypoints_label_iter++] . '|' . $waypoint);
}
$markers[] = "markers=color:red" . urlencode("|") . "label:" . urlencode($waypoints_labels[$waypoints_label_iter] . '|' . $destination);
$url = "https://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$destination&waypoints=" . implode($waypoints, '|');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
$result = curl_exec($ch);
curl_close($ch);
$googleDirection = json_decode($result, true);
$polyline = urlencode($googleDirection['routes'][0]['overview_polyline']['points']);
$markers = implode($markers, '&');
return "https://maps.googleapis.com/maps/api/staticmap?size=$size&maptype=roadmap&path=enc:$polyline&$markers";
}
```
result
Comment for this answer: When I tried this with two different locations, I see a map, with no line meeting the places. My markers say A and C, which is confusing because I don't know who has B but I've only put in two locations. Could it be because I'm using the address not longditude and Lat?
Comment for this answer: No wait it's still not drawing the line. It just shows two markers
Comment for this answer: Any Javascript version of this?
Here is another answer: I've been doing this today, using the overview_polyline which is returned from the distance matrix, however in some cases the polyline isn't plotted on the static map when adding it to the map URL but the same one works on a dynamic map. with googles new pricing coming in we've had to make changes as our current yearly payment is to increase by other 1500%.
the bonus of the static map is that you can pass postcode/zip and full addresses. you can also pass in variables which makes things easier.
|
Title: How do I set a currency string value to a UITextField, preserving encoding?
Tags: ios;uitextfield;nsnumberformatter
Question: I am developing an application in which I wish to handle different currency formats, depending on the current locale. Using a ```NSNumberFormatter``` I can correctly translate a number into string and back without problems.
But, if I put the string value into a ```UITextField``` and later get it back, I won't be able to convert the string back into a number and I will get a ```nil``` value instead.
Here is a sample code to explain the problem:
```NSNumberFormatter *nf = [Utils currencyFormatter];
NSNumber *n = [NSNumber numberWithInt:10000];
NSString *s = [nf stringFromNumber:n];
NSLog(@"String value = %@", s);
UITextField *t = [[UITextField alloc] init];
// I put the string into the text field ...
t.text = s;
// ... and later I get the value back
s = t.text;
NSLog(@"Text field text = %@", s);
n = [nf numberFromString:s];
NSLog(@"Number value = %d", [n intValue]);
```
where the ```currencyFormatter``` method is defined this way:
```+ (NSNumberFormatter *)currencyFormatter
{
static NSNumberFormatter *currencyFormatter;
if (!currencyFormatter) {
currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setLocale:[NSLocale currentLocale]];
if ([currencyFormatter generatesDecimalNumbers] || [[currencyFormatter roundingIncrement] floatValue] < 1) {
[currencyFormatter setGeneratesDecimalNumbers:YES];
[currencyFormatter setRoundingIncrement:[NSNumber numberWithFloat:0.01]];
}
}
return currencyFormatter;
}
```
(The inner ```if``` is used to force the formatter to always round to the smallest decimal digit, eg. even for CHF values).
What I get in the Console is this:
```2012-03-29 00:35:38.490 myMutuo2[45396:fb03] String value = € 10.000,00
2012-03-29 00:35:38.494 myMutuo2[45396:fb03] Text field text = € 10.000,00
2012-03-29 00:35:38.497 myMutuo2[45396:fb03] Number value = 0
```
The strange part is that the spacing character between ```€``` and ```1``` in the first line is represented in the console through a mid-air dot, while in the second line this dot disappears. I believe this is an encoding-related problem.
Can anyone help me solve this problem?
Thank you!
Edit
I changed my test code to this:
```NSNumberFormatter *nf = [Utils currencyFormatter];
NSNumber *n = [NSNumber numberWithInt:10000];
NSString *s = [nf stringFromNumber:n];
NSLog(@"String value = %@ (space code is %d)", s, [s characterAtIndex:1]);
UITextField *t = [[UITextField alloc] init];
t.text = s;
s = t.text;
NSLog(@"Text field text = %@ (space code is %d)", s, [s characterAtIndex:1]);
n = [nf numberFromString:s];
NSLog(@"Number value = %d", [n intValue]);
```
to discover this:
```2012-03-29 02:29:43.402 myMutuo2[45993:fb03] String value = € 10.000,00 (space code is 160)
2012-03-29 02:29:43.405 myMutuo2[45993:fb03] Text field text = € 10.000,00 (space code is 32)
2012-03-29 02:29:43.409 myMutuo2[45993:fb03] Number value = 0
```
The ```NSNumberFormatter``` writes down the space as a non-breaking space (ASCII char 160), and then the ```UITextField``` re-encodes that space as a simple space (ASCII char 32). Any known workaround for this behaviour? Perhaps I could just make a replacement of the space with a non-breaking space but ... will it work for all the locales?
Comment: its not working for your currency locale only. i checked it and getting same null value as you said.
Comment: See my Edited answer second time. This may help you somewhat.
Here is the accepted answer: I was able to solve this problem only extending the ```UITextField``` through a custom class. In this new class I put a new ```@property``` of type ```NSString``` in which I store the "computed" string value for the text field. This string will never be modified and will preserve the original encoding of the content of the text field.
When you need to work again on the original untouched content of the text field you have to refer to this new property instead of referring to the ```text``` property.
Using a separate string container is the only way to avoid these strange encoding changes.
Here is another answer: A possible workaround: You could try to parse only the number values (and punctiation) via a regex pattern and create you currency value based on that number. If you do it in that way it is perhaps even more forgivable for the user, if he typed another currency symbol or other symbols that shouldnt be there...
Comment for this answer: I already do this in a previous version of the code. But I get strange errors, exceptions and crashes, probably with some strange locale. I really would like to use the magic of the `NSNumberFormatter` just to get rid of all that custom handling of the strings and to work in a "controlled" environment in which I encode and decode the strings/numbers using the same formatter object.
Comment for this answer: By the way ... what the user puts into the `UITextField` is actually generated through a call to the `stringFromNumber:` method of `NSNumberFormatter`, so I always know that what the text field contains has been correctly formatted. No need to add more logic to interpret that value.
Comment for this answer: Because the "user-entered" value is written into the UITextField through the `textField:shouldChangeCharactersInRange:replacementString:` method in the delegate class. This method will automatically convert user-inserted characters into currency formatted strings. The string is saved into the `text` property of the text field for displaying purposes and I get it back from here later ...
Comment for this answer: Than you could just save the user-entered value for later usage? why do you need than to reconvert the textfield contents?
|
Title: Extract word timings from MP3 audio file
Tags: c#;text-to-speech
Question: I want to capture audio timings for each word in the audio.
For example, "Introduction Hi Bangalore" consider this is one mp3file(page1.mp3), from that how can extract each word starting time.
i.e., The starting time of "Introduction", "Hi", "Bangalore".
If it is possible?, Possible means, how can i do?
If any software available?.
I have tried to extract timing using system.speech API using bookmark-reach event but it not as accurate as I want.
Comment: I'm not entirely sure I understand your question. Are you going from audio to text, or text to audio?
Comment: Have you tried the [PhonemeReached](http://msdn.microsoft.com/en-us/library/system.speech.synthesis.speechsynthesizer.phonemereached.aspx) event instead?
Comment: System.Speech doesn't generate MP3 files by default, which is why I was confused. Showing your code would help immensely.
Comment: i want to convert text to audio and then play that audio and highlight words in sync with audio.
Comment: This problem is now solved. I have used "SpeeckProgress" event to capture word timing. It is working fine on Windows server 2012.
Comment: @PratikPatel I am looking for the same solution, can you share your code or guide how did you achieve it? I am using [Pageflip5](http://pageflip-books.com/) Flipbook and [Read Along](https://github.com/westonruter/html5-audio-read-along)
|
Title: Can I upload CSV file to MySQL database without deleting "\" backslash which is placed in CSV file using php
Tags: php;mysql;backslash;fgetcsv
Question: Csv file has been uploaded to database but backslash() is automatically getting deleted when I upload CSV file to database.
I need that \ to be also uploaded in the database.
For eg : I need to add the folder location into database like C:\Users\Others\Desktop\Gips report but it shows like C:UsersOthersDesktopGips report
``` $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",", '"' , '"' )) !== FALSE)
{
$sql = "INSERT INTO csvfile(id,Projectnumber,Projectfolder,e0id) VALUES ('".$emapData[0]."','".$emapData[1]."','".$emapData[2]."','".$emapData[3]."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo 'Invalid File:Please Upload CSV File';
}
```
Comment: Use prepared statements. Then there is no need to escape anything.
Comment: Welcome to Stack Overflow. It's almost impossible for us to help you unless you show us a bit of code, or at least explain how you read your .csv file and INSERT its rows to your table. And, please show us a few lines of your file, including some with the `\\` characters you want preserved in your table. Please [edit] your question or ask another.
Comment: Of course you can. Prepared statements and parameters don't prevent you from doing that
Comment: hi Jones i have edited and added a bit of code
Comment: Hi markus but iam using array to import all the datas in file to database so if i use prepared statement then i cannot fetch all datas from csv file to database right?
|
Title: why doesn't this code for passing data between controllers work?
Tags: ios;swift;xcode;delegates
Question: I'm trying to understand delegates so I created this simple app to test it out, I just want to pass a string from the secondViewController to the MainViewController... I tried to follow all the steps but it seems there's something missing and I don't have a clue about what it might possibly be... here's my code..
main view controller
```class mainController: UIViewController, sendDataDelegate {
let label: UILabel = {
let lab = UILabel()
lab.text = "No data"
lab.textAlignment = .center
lab.translatesAutoresizingMaskIntoConstraints = false
return lab
}()
let tapRecognizer = UITapGestureRecognizer()
let secondVC = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
// assign delegate to self, not working...
secondVC.delegate = self
tapRecognizer.addTarget(self, action: #selector(goToSecondVC))
view.addGestureRecognizer(tapRecognizer)
view.addSubview(label)
// label constraints..
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-200-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":label]))
}
@objc func goToSecondVC(){
show(SecondViewController(), sender: nil)
}
func passData(str: String) {
print(str)
label.text = str
}
}
```
and the second view controller plus protocol to send the data...
```import UIKit
//protocol to pass the data..
protocol sendDataDelegate {
func passData(str: String)
}
class SecondViewController: UIViewController {
let tapRecog = UITapGestureRecognizer()
let dataStr = "data passed"
var delegate: sendDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
tapRecog.addTarget(self, action: #selector(goBack))
view.addGestureRecognizer(tapRecog)
}
@objc func goBack(){
// trying to pass data here..
delegate?.passData(str: dataStr)
// dismiss view...
dismiss(animated: true, completion: nil)
}
}
```
I'd like to point out I'm trying to learn everything by code, so no storyboards being used here.. how can I do this just by code?
thank you all in advance for the answers! have a great day)
Comment: Just a note: delegate in SecondViewController should be weak – `weak var delegate: sendDataDelegate?`, otherwise you will get retain cycle
Comment: Make sure to accept the answer that helped you.
Comment: When you are trying to show SecondVC set the delegate of your protocol.
Here is the accepted answer: In your function ```goToSecondVC``` you are creating a brand new view controller and ignoring the property that you created.
Change it to use ```secondVC``` instead of ```SecondViewController()```.
Here is another answer: This correction will solve your problem:
```@objc func goToSecondVC(){
show(secondVC, sender: nil)
}
```
Protocols are better to be named with a capital letter:
``` protocol SendDataDelegate: AnyObject {
func passData(str: String)
}
```
And don't forget about weak delegate:
```weak var delegate: SendDataDelegate?
```
Comment for this answer: thank you so much for the hints, I'll remember that next time.
|
Title: Javascript countdown timer with dom storage
Tags: javascript
Question: Can someone help me understand where im going wrong with this code ive spend days upon days trying to get this to work as i need a javascript/dom timer rather than jquery
HTML
```<input name="button" type="button" onClick="displaytimer()" value="Play!">
<form name="counter">
You have
<input type="text" size="8" name="d2">
seconds left to escape!
</form>
```
Javascript
```if (localStorage) {
var milisec = 0;
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
function displaytimer() {
if (milisec <= 0) {
milisec = 9;
seconds -= 1;
}
if (seconds <= -1) {
milisec = 0;
seconds += 1;
}
else milisec -= 1;
localStorage.seconds = seconds;
document.counter.d2.value = seconds + "." + milisec;
if (seconds > 0 || (seconds = 0 && milisec > 0)) {
setTimeout(displaytimer(), 100);
}
if (seconds <=0) {
window.location="./pages/fail.html";
cleartimer();
}
function cleartimer() {
localStorage.seconds = seconds;
document.counter.d2.value =0;
}
window.location="./pages/2.html";
}
}
else {
document.write("dom storage not supported");
}
```
Comment: Well what is it not doing that it should, or doing that it shouldnt? What is document.counter and d2? Are you getting errors on your javascript console?
Comment: @Ejay - If only there were some way to help him out with that . . .
Comment: @user3905055 - I did help . . . I fixed your formatting for you, rather than just commenting on it . . .
Comment: From first look, your formatting looks wrong
Comment: @user3905055 your `input` would not show until you put it in code format
Comment: Since you've ignored patrick's comment, do you get any errors **in console**? also what is `document.counter.d2`? Is there a portion of code that you've left out?
Comment: what do you think is preventing `window.location="./pages/2.html";` from executing on first call of `displaytimer()`? Also, you intend to use function name instead of function call inside `setTimeout` (in this context), so that'll be `setTimeout(displaytimer, 100);` instead of `setTimeout(displaytimer(), 100);`. Also you can't rely on `setTimeout` to execute after real 100ms.
Comment: so you do `setTimeout(displaytimer, 100)` and figure out a condition/event you want to redirect the user on, put `window.location="./pages/2.html";` inside that condition (`if`, because redirection to `pages/2.html` occurs instantaneously), and report back ;)
Comment: @Ejay, The formatting is weird, but I think it's valid.
Comment: basically i need a javascript only timer that doesnt refresh or reload on page F5 or close, and then when timers up redirect .. p.s i know in this ive used dom to store rather than javascript
Comment: @PatrickEvans the page doesnt work atm but i carnt find out why
Comment: @talemyn please dont comment if your not trying to help!
Comment: ah i see now, great thanks still not working though =p
Comment: apart from the format can anyone help me on this problem im having?
Comment: @PatrickEvans mybad ive updated the code to show you what you requested
Comment: @ejay thanks for continuing to help ive updated the missing code
Here is another answer: Try this code. It was modified to avoid some function declaration inside another function. Also, ```setInterval()``` was used for simplicity. Note that ```onClick()``` triggers now ```starttimer()```.
HTML:
```<input name="button" type="button" onClick="starttimer()" value="Play!">
<form name="counter">
You have
<input type="text" size="8" name="d2">
seconds left to escape!
</form>
```
JS:
```if (localStorage) {
var milisec = 0;
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
var timer;
function starttimer() {
clearInterval(timer);
timer = setInterval(displaytimer, 100);
}
function cleartimer() {
localStorage.seconds = seconds;
document.counter.d2.value = 0;
clearInterval(timer);
}
function displaytimer() {
if (milisec <= 0) {
milisec = 9;
seconds -= 1;
}
if (seconds <= -1) {
milisec = 0;
} else {
milisec -= 1;
}
localStorage.seconds = seconds;
document.counter.d2.value = seconds + "." + milisec;
if (seconds < 0) { //countdown ended here
//window.location="./pages/fail.html"; //put this forward in its appropriate place according to what you want to do
cleartimer();
}
//window.location="./pages/2.html"; //put this forward in its appropriate place according to what you want to do
}
}
else {
document.write("dom storage not supported");
}
```
I've tested in this plunkr and it worked ok.
http://plnkr.co/edit/acAxRZAHsFVtJoQZ1Ov6
|
Title: pyramid/cornice validators and colander schema
Tags: validation;pyramid;colander;cornice
Question: I have a cornice API with a view that has validators and a colander schema. I can't get access to colander validated data (```request.validated```) in my validator.
I pass my data through colander. My colander schema looks something like this:
```from colander import (
MappingSchema,
SchemaNode,
String
)
class UserSchemaRecord(MappingSchema):
username = SchemaNode(String())
password = SchemaNode(String())
class UserSchema(MappingSchema):
user = UserSchemaRecord()
```
It adds a sanitized version of the request data into ```request.validated['user']``` that I can then access in my view like this.
```@view(renderer='json', validators=(valid_token, valid_new_username), schema=UserSchema)
def collection_post(self):
"""Adds a new user"""
user_data = self.request.validated['user']
user = UserModel(**user_data)
DBSession.add(user)
DBSession.flush()
return {'user': user}
```
However, I also need to check that the request provides a unique username and return an error if the username is already taken. I'd like to do this with a validator (```valid_new_username```) but when I try to access ```request.validated['user']``` in my validator the data aren't there.
```def valid_new_username(request):
user = request.validated['user'] # this line fails with a KeyError
username = user['username']
if UserModel.get_by_username(username):
request.errors.add('body', 'username', "User '%s' already exists!" % username)
request.errors.status = 409 # conflict
```
It looks like the validator is called before the data have been extracted. I don't really want to access the request json_body data directly before passing them through colander. Is there a way I can change the ordering of the schema/validator?
The alternative is to do the checking directly in my view callable. Is that a good option? Are validators not supposed to work with colander validated data?
Here is the accepted answer: Not sure if it's your problem, but if the data is not valid in the first place (Colander found errors), then it will not be available as request.validated['key'] in the validators.
You can use a decorator like this if you want to apply the validator only if the data has passed Colander validation.
```def when_valid(validator):
"""Decorator for validation functions.
Only try validation if no errors already.
"""
def inner(request):
if len(request.errors) > 0:
return
validator(request)
return inner
@when_valid
def valid_new_username(request):
pass # your validation here
```
Comment for this answer: The code seems to point in that direction. https://github.com/mozilla-services/cornice/blob/f94dd6cc41c26dc648c97a526ed6071fb56e5c5b/cornice/service.py#L547-L560
Comment for this answer: Yes, it is. Thanks, I will use this a lot.
Comment for this answer: So schema validation always happens first?
|
Title: HeadlessException when trying to launch/run jProfiler 9 on Fedora 24 Workstation?
Tags: fedora;jprofiler
Question: I just installed a fresh copy of Fedora 24 Workstation and did a full ```dnf update``` on the entire system.
Then I installed the jProfiler rpm from the jProfiler site.
However, when I try to launch jProfiler (either from the /opt/jprofiler9/jProfiler.desktop icon or from /opt/jprofiler9/bin/jprofiler shell script), I get the following error message:
```java.awt.HeadlessException
at java.awt.SplashScreen.getSplashScreen(SplashScreen.java:117)
at com.exe4j.runtime.splash.AwtSplashScreen.<init>(AwtSplashScreen.java:17)
at com.exe4j.runtime.splash.SplashEngine.setJavaSplashScreenConfig(SplashEngine.java:17)
at com.install4j.runtime.launcher.UnixLauncher.main(UnixLauncher.java:50)
```
I've tried setting my display using ```DISPLAY=0.0``` or even ```DISPLAY=:0```, but neither seem to make any difference/impact.
Any suggestions how to get this to work? I suspect it is something obvious that I am overlooking.
Here is another answer: After a bunch of trial and error, I finally tried to install the Oracle Hotspot JRE instead of the OpenJDK JRE. I downloaded Oracle's JDK, installed it, and then configured it as the system default using:
```sudo alternatives --config java
```
Now everything works properly with Oracle JRE.
Comment for this answer: I suspect you may have only have had the headless JRE package installed. That package is not able to run GUI applications.
|
Title: Integrate Android Studio with Unity
Tags: unity;android-studio;hud;globalmenu
Question: is there a way to properly integrate Android Studio with Unity Desktop Environment?
I'm not looking for help about how to install android studio on Ubuntu, neither to add a desktop entry in order to have it on the launcher. I've already installed it following the Android instructions and I have it up and working.
What I'm missing though, it's an actual integration with the features of the Unity DE: menu bar shown inside the Window's title bar (global menu), commands easily accessible through Alt key (HUD support) and, hopefully, Progress status & Badges in the unity launcher.
I haven't myself tried to use Ubuntu Make to install android studio and see if it results in better results, maybe someone who has can confirm it?
|
Title: How to use HTTPPost without a new runnable thread
Tags: android;json;http-post
Question: I have the following code inside my ```MainAcitivity``` for logging to the application using username and password taken by a method ```jsnrqstr.sendRequest(username, password, URL);```
```loginButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
username = userNameBox.getText().toString();
password = passwordBox.getText().toString();
login_state = jsnrqstr.sendRequest(username, password, URL);
if(login_state.equals("ok")){
details.setUserName(username);
details.setPassword(password);
Toast.makeText(MainActivity.this, "User Verified", Toast.LENGTH_LONG).show();
passwordBox.setText("");
Intent myIntent = new Intent(MainActivity.this, DashBoardActivity.class);
MainActivity.this.startActivity(myIntent);
}else
Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
passwordBox.setText("");
}
});
```
This method uses the following code for receiving the response from an erlang server which responses with a JSON object and I could receive the login_state from it. Code for ```jsnrqstr.sendRequest(username, password, URL);```
```public class JSONRequester {
String state;
public String sendRequest(final String userName, final String password, final String URL){
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(URL);
post.setHeader("Content-type", "application/json");
json.put("username", userName);
json.put("password", password);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
String temp = EntityUtils.toString(response.getEntity()); //Get the data in the entity
//Log.v("response", temp);
JsonObject o = new JsonParser().parse(temp).getAsJsonObject();
Log.v("response", o.get("state").toString());
state = o.get("state").toString();
}}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
}
}).start();
return state;
}
```
But I get the following Null-pointer Exception @
```if(login_state.equals("ok")){
```
line which means that I have not returned the ```login_state``` value from the above method correctly. As I think This is because by the time the new runnable thread returns the value it is too late. What could I do for fixing this issue?
Here is the accepted answer: The problem is between the lines :) - these two:
}).start();
<== HERE!!!
``` return state;
```
The second one gets executed prematurely, while your thread is still running. Concurrency is the solution.
One common Android-specific pattern is AsyncTask - http://developer.android.com/reference/android/os/AsyncTask.html - or its analogs (Thread/Handler etc.)
On click, initiate the process in onPreExecute (code before sendRequest): say, bring up a progress dialog and do the initializations. Your thread's code goes into the doInBackground method and sets the state variable. When done, in onPostExecute, dismiss the progress dialog, and proceed with your login logic: ```if(/*response*/ state!=null)``` ...
Here is another answer: You should use a callback of some sorts that will begin executing your code when the thread has completed if you rely on the return value. Or you can start up the new thread and just wait for it to return before doing anything else.
|
Title: How to enable port 8080 for apache to serve APIs
Tags: apache2
Question: I'm using ec2 instance to server my Go apis. When I'm building my APIs then it will simply access by ```http://Ip:8080/api```. After that I'm working on frontend part to integrate my APIs I used react for it. In local everything is fine and running. But when I deploy my frontend on the server then it will show me error of fetching result from APIs ```http://Ip:8080/api``` need to use ```https://ip:8080/api``` then I created a sub domain and apply SSL on it and I successfully bind my IP with that subdomain and I'm able to access images which are on server folder path ```/var/www/html/images/a.png``` for that I'm using Apache server. But now when I run my Go services and run it with the subdomain name like ```https://subdomain:8080/api``` then it will not accessible. I'm pasting my ```ports.conf```
```# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf
Listen 80
Listen 8080
<IfModule ssl_module>
Listen 443
Listen 8080
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
```
Please let me know if any this is needed and also if I'm skipping something.
Comment: But I want to run my apis with `https` not with the `http` @LunaLovegood
Comment: Can add log and see if the port number is set.
AFAIK, while deploying in ec2, public instance and setting a domain or sub-domain, we usually don't set any port, it takes the http default port which is 80, while requesting we need not explicitly mention the default port, since it is default.
|
Title: what is an getErrorCode()==1767 in sybase?
Tags: sql;exception;sybase
Question: I tried searching the Exception thown for ```getErrorCode()``` in sybase,but couldnot get the required information.I tried searching the minor codes also.Can someone please tell what this exception means?This is a ```SQLException``` and the ```errorcode=1767```.what does this indicate? And how to overcome this issue?
Here is the accepted answer: Number of variable length columns exceeds limit of %d for allpage locked tables. %s for '%.*s' failed.
Explanation:
Adaptive Server could not perform the requested action. Modify your command to meet the Adaptive Server requirement for the objects or variables shown in the error message.
http://manuals.sybase.com/onlinebooks/group-as/asg1250e/svrtsg/@Generic__BookTextView/76240;pt=77267
Comment for this answer: can you please show the the cmd line that you use so i can figure it out. and please don't forget to click the upvote and select my answer if i answered your question successfully :)
Comment for this answer: thank you so much but can you please explain when we get this error and how to overcome this? i mean iam using an alter table cmd what might have resulted in this error?
|
Title: How to dump the Windows SAM file while the system is running?
Tags: windows;security;passwords
Question: I've exploited test machines using metasploit and was able to get the hashes from the SAM file; I've tried running commands as ```SYSTEM``` to get them but am unable to do so. What is a more portable method to extract the hashes from the SAM file?
Here is the accepted answer: Edit: I decided to edit after many years of abandonment.
The Windows SAM file is locked from copying/reading unlike ```/etc/shadow``` on Linux systems. Instead, to get around this tools will extract hashes from memory.
There are ways to get around this that I'll cover below:
Mimikatz
Run mimikatz with ```sekurls181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16logonpasswords```.
fgdump
Similar functionality as mimikatz. Run it, and hashes will be dumped to local files.
hashdump
Built into meterpreter; extracts hashes from memory.
Registry
It's also possible to extract from the registry (if you have ```SYSTEM``` access):
```reg save hklm\sam %tmp%/sam.reg``` and ```reg save hklm\system %tmp%/system.reg```
Copy the files, and then run: ```samdump2 system sam```
Backups
SAM file can also be stored in a backup location: ```C:\Windows\Repair\SAM```
I should also mention that the tools will at a minimum require ```Administrator``` privileges; and most will not get all hashes unless ```SYSTEM``` access is attained.
Comment for this answer: Maybe I've misunderstood, but in what way are tools like `Mimikatz` or `fgdump` any more portable than C&A or different to it? As far as I can tell they're all third party tools that don't come packaged with Windows and need to be loaded separately. Also, for my own curiosity, what's the use case for hash-dumping tools when tools like Ophcrack exist?
Comment for this answer: Can mimikatz be used to crack local hashes on a powered-off system via a bootable disk, or is it only designed to run on a powered-on system?
Here is another answer: There is a simpler solution which doesn't need to manage shadow volumes or use external tools. You can simply copy SAM and SYSTEM with the ```reg``` command provided by microsoft (tested on Windows 7 and Windows Server 2008):
```reg save hklm\sam c:\sam
reg save hklm\system c:\system
```
(the last parameter is the location where you want to copy the file)
You can then extract the hashes on a Linux system with package samdump2 (available on Debian: ```apt-get install samdump2```):
```$ samdump2 system sam
Administrator:500:aad3b435b51404eeaad3b435b51404ee:c0e2874fb130015aec4070975e2c181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16:
*disabled* Guest:501:aad3b435b51404eeaad3b435b51404ee:d0c0896b73e0d1316aeccf93159d181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16:
```
Comment for this answer: which windows flavors does this work on (or rather which does it not)? tried to tell from MSDN website but it doesnt list it (at least i didnt see it)
Comment for this answer: this just dumps local accounts. to get cached domain creds you need to get SECURITY from the registry too. then you can run: **python /usr/share/doc/python-impacket/examples/secretsdump.py -sam SAM -security SECURITY -system SYSTEM LOCAL** to dump all cached creds.
Here is another answer: It's not a permission issue – Windows keeps an exclusive lock on the SAM file (which, as far as I know, is standard behavior for loaded registry hives), so it is impossible for any other process to open it.
However, recent Windows versions have a feature called "Volume Shadow Copy", which is designed to create read-only snapshots of the entire volume, mostly for backups. The file locks are there to ensure data consistency, so they are unnecessary if a snapshot of the entire filesystem is made. This means that it is possible to create a snapshot of ```C:```, mount it, copy your ```SAM``` file, then discard the snapshot.
How exactly to do this depends on your Windows version: XP needs an external program, Vista and 7 have ```vssadmin create shadow```, and Server 2008 has the ```diskshadow``` command. The page Safely Dumping Hashes from Live Domain Controllers has more details on this process, as well as instructions and scripts.
Alternatively, there are tools such as ```samdump``` which abuse the LSASS process from various directions in order to extract all password hashes directly from memory. They might be much faster than VSS snapshots, but have a higher risk of crashing the system.
Finally, Google brings out this snippet, whose usefulness I cannot rate having never used metasploit myself:
```meterpreter> use priv
meterpreter> hashdump
```
Comment for this answer: What's the difference between the SAM\SYSTEM files and the SAM\SYSTEM registry subkeys (I'm referring to vmarquet's [answer](https://superuser.com/a/1088644/452686))? Are the contents the same?
Comment for this answer: Yes, those files are actually where the registry database is stored – the file "SYSTEM" holds the data of HKLM\SYSTEM. (I mean, it has to be stored in some file _somewhere,_ does it not?) You can look at `HKLM\SYSTEM\CurrentControlSet\Control\HiveList` to see which subkeys correspond to which files.
Here is another answer: Obscuresec method overcomes your dificulties locally on any windows powershell 1.0 enabled machine. Leaves out some targets i know, but hey, nice job ! (thank you Chris).
Note: Admin privileges are always needed to perform such an operation
You could use
```
http://gallery.technet.microsoft.com/scriptcenter/Get-PasswordFile-4bee091d
```
or from another source (more recent i might add)
```
https://github.com/obscuresec/PowerShell/blob/master/Get-PasswordFile
```
Advised reading:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/12/using-the-windows-api-and-copy-rawitem-to-access-sensitive-password-files.aspx
http://github.com/obscuresec/PowerShell/blob/master/Get-PasswordFile
http://gallery.technet.microsoft.com/scriptcenter/Copy-RawItem-Reflection-38fae6d4
http://gallery.technet.microsoft.com/scriptcenter/Get-PasswordFile-4bee091d
http://blog.cyberis.co.uk/2011/09/remote-windows-sam-retrieval-with.html
For grabbing remote systems SAM and SYSTEM hives use the above mentioned in conjunction with
http://gallery.technet.microsoft.com/scriptcenter/GetRemoteSAM-b9eee22f
Comment for this answer: Links are broken.
Here is another answer: Would like to specify additional method that is not described here, as lots of time in Red Teaming / Penetration Testing the most obvious ways are not accessible (denied, are monitored by Blue Team, etc.) and it's nice to know all available techniques.
One of workaround of accessing files, which system has handles on (cannot copy/remove as usual), is ```vssshadow.exe``` told above.
Second - ```esentutil.exe```.
Exact command to take a copy of file with handle:
```esentutl.exe /y /vss c:\windows\ntds\ntds.dit /d c:\folder\ntds.dit```
This applies to SAM, SYSTEM, SECURITY, NTDS.DIT etc.
P.S.
There's ```esentutl.py``` in impacket's package:
https://github.com/SecureAuthCorp/impacket/blob/master/examples/esentutl.py
P.S.S.
esentutl PoC image
|
Title: SQL: JOIN two tables with distinct rows from one table
Tags: sql;sql-server-2008;tsql;join
Question: This might be a very simple problem but I can't seem to get my head around this since last night.
I have 3 tables
```VirtualLicense
VirtualLicenseId ProductName
-----------------------------------
1 Transaction
2 Query
3 Transaction
Product
ProductId Name
---------------------------
1 Transaction
2 Query
License
LicenseId ExpiryDate ProductId
-----------------------------------------
1 14/07/2013 1
2 13/07/2013 1
3 13/07/2013 2
4 14/07/2013 2
```
The VirtualLicense and License are joined using ProductName and ProductId mapping using the Product table.
I want to get combination of VirtualLicenseId and LicenseId, where I can basically assign the VirtualLicenseId to a LicenseId. Once a licenseid is assigned to a VirtualLicenseId, it should not be available for the following VirtualLicenseIds. Also, I want that the licenseid for which the expirydate is nearer(smaller) should be assigned first.
So, the result for my example data set should be
```VirtualLicenseId LicenseId
---------------------------------
1 2
2 3
3 1
```
I do not want to loop over any of the tables for this.
I hope my problem is clear from my description and data.
Here is the accepted answer: You can do something like this:
In first CTE - assign rankings for VirtualLicenses within the Product groups.
In second CTE - assign rankings for Licensce within the Product groups (order by exp. date)
And at the end just join the two subqueries on productID and ranking.
```WITH CTE_VL AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY vl.VirtualLicenseId ASC) RN
FROM dbo.VirtualLicense vl
LEFT JOIN dbo.Product p ON vl.ProductName = p.Name
)
,CTE_License AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY ExpiryDate ASC) RN
FROM dbo.License
)
SELECT VirtualLicenseId, LicenseId
FROM CTE_VL vl
LEFT JOIN CTE_License l ON vl.ProductId = l.ProductID AND vl.RN = l.RN
```
SQLFiddle DEMO
|
Title: What technologies came to the PC world from High Performance Computing?
Tags: history;hpc
Question: Recently I came to think about the technologies that supercomputers gave to the modern PCs. I found out that the instruction pipelining appeared in one of the first CDC machines and parallelism was certainly a super-computer hallmark of all the times. But it seems that such "features" like co-processors and cache-memory were initially invented for the "mainstream" computers.
Can you help me to sort this out and name the technologies that came to our desktops and laptops from the supercomputing (and maybe name the ones that surprisingly didn't)?
Comment: I am going to say this is wiki material.
Here is another answer: I would say, home computers!
If it wasn't for the early super computers, we probably wouldn't have any of the technologies we have now.
Anyway,
From Wikipedia -
Technologies developed for supercomputers include:
```* Vector processing
* Liquid cooling
* Non-Uniform Memory Access (NUMA)
* Striped disks (the first instance of what was later called RAID)
* Parallel filesystems
```
|
Title: App is crashing with EXC_BAD_ACCESS on background
Tags: iphone;objective-c;xcode;exc-bad-access
Question: i setted ```NSString *oldChat``` in the header file like this:
```@interface CTFChatViewController : UIViewController {
NSString *oldChat;
}
- (void)updateChat;
@property (nonatomic, retain) NSString *oldChat;
@end
```
and then i used it:
```- (void)updateChat
{
NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
if (![chat isEqual:oldChat])
{
[webView loadHTMLString:chat baseURL:nil];
oldChat = chat;
}
[self performSelectorInBackground:@selector(updateChat) withObject:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
oldChat = chat;
[webView loadHTMLString:chat baseURL:nil];
[self performSelectorInBackground:@selector(updateChat) withObject:nil];
}
```
App crashed on ```if (![chat isEqual:oldChat])``` with ```EXC_BAD_ACCESS``` error.
why it crashed ?
(XCode 4.5.2, iPhone Simulator 6.0, Base SDK 6.0)
Comment: why are you making property of oldChat, if you are not going to use it?
Here is the accepted answer: oldChat is ```autorelease``` object. Retain it and use isEqualToString for string comparison.
``` NSString *chat = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://theshay.byethost7.com/chat.php"] encoding:NSUTF8StringEncoding error:nil];
oldChat = chat;
[oldChat retain];
```
Comment for this answer: do not forget to release oldChat in dealloc.
Here is another answer: You have to check your NSString is equal or not using isEqualToString: method. Your code should be like this
```if (![chat isEqualToString:oldChat]){
//Do something
}
```
|
Title: TilesConfigurer throws NoClassDefFoundError on initialization
Tags: spring;spring-mvc;tiles2;apache-tiles
Question: Problem: TilesConfigurer throws NoClassDefFoundError on initialization
Took steps to resolve:
Import tiles jars.
Added jstl.jar
Added older vesions of tiles:
tiles-api-2.0.6.jar
tiles-core-2.0.6.jar
tiles-jsp-2.0.6.jar
tiles-servlet-2.1.2.jar
Several restructuring of web deployments and ordering of imported jars.
webmvc-context.xml
```<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:view-controller path="/jsp/index.jsp" />
<mvc:view-controller path="/jsp/info/about.jsp" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="factoryClass"
value="org.apache.struts.tiles.xmlDefinition.I18nFactorySet" />
<property name="definitions">
<list>
<value>/WEB-INF/tiles-def.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" >
<!--
<property name="requestContextAttribute" value="requestContext"/>
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles.TilesView"/>
-->
</bean>
</beans>
```
web.xml
```<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>simple-tiles2</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/web-application-context.xml
</param-value>
</context-param>
<servlet>
<servlet-name>tiles</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>tiles</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>encoding-filter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
```
Error Log Brief:
```13:26:51,622 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] (MSC service thread 1-1) Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@136d1b4: defining beans [org.springframework.web.servlet.config.viewControllerHandlerMapping,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,tilesConfigurer,viewResolver]; root of factory hierarchy
13:26:51,627 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-1) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tilesConfigurer' defined in ServletContext resource [/WEB-INF/spring/webmvc-context.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/servlet/view/tiles2/TilesConfigurer$SpringTilesInitializer
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1011) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:957) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) [spring-context-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) [spring-context-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383) [spring-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283) [spring-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) [spring-web-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3392) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3850) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [rt.jar:1.6.0_43]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [rt.jar:1.6.0_43]
at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_43]
Caused by: java.lang.NoClassDefFoundError: org/springframework/web/servlet/view/tiles2/TilesConfigurer$SpringTilesInitializer
at java.lang.Class.getDeclaredConstructors0(Native Method) [rt.jar:1.6.0_43]
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2398) [rt.jar:1.6.0_43]
at java.lang.Class.getConstructor0(Class.java:2708) [rt.jar:1.6.0_43]
at java.lang.Class.getDeclaredConstructor(Class.java:1987) [rt.jar:1.6.0_43]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1004) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
... 21 more
Caused by: java.lang.ClassNotFoundException: org.springframework.web.servlet.view.tiles2.TilesConfigurer$SpringTilesInitializer from [Module "deployment.simple-tiles2-webapp.war:main" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
... 27 more
```
I have used other versions of spring, but right now I am using 3.2.0.RELEASE. Really appreciate the help.
Comment: Which version of Spring are you using?
Comment: Can you post your pom.xml if you use maven or the list of jar you are using if you don't
Comment: I should have also said that this comes from the springbyexample tutorial. http://www.springbyexample.org/examples/simple-tiles-spring-mvc-webapp.html
Comment: I have made some edits to my question to give the clarifications you need. I am using the 3.2.0.RELEASE version of spring and the libraries posted above. Really appreciate the help.
Here is the accepted answer: Changed two things in webmvc-context.xml.
```<mvc:view-controller path="/index.html" view-name="index" />
<mvc:view-controller path="/about.html" view-name="info/index" />
```
and the tilesConfigurer and viewResolver beans
``` <bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles-defs/templates.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
```
There were also libraries that were changed. I don't think that is relevant, but here they are.
|
Title: How do you mark a property as transient in a Javabean in order to avoid serialization by XMLEncoder?
Tags: java;javabeans
Question: Using the "transient" keyword on a variable declaration or "@Transient" on the getter does not stop the XMLEncoder from serializing properties. The only way I've found to tell the XMLEncoder not to serialize specific properties is with code like:
```BeanInfo info = Introspector.getBeanInfo(MyClass2.class);
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("props")) {
pd.setValue("transient", Boolean.TRUE);
}
}
```
Really??? Is there an easier way that doesn't require runtime code to loop through all the properties? Something like the transient modifier would rock!
Here's a JavaBean that will have all it's properties serialized by XMLEncoder, despite the use of "transient":
```import java.io.Serializable;
import java.beans.XMLEncoder;
public class TestJavaBeanSerialization implements Serializable {
public TestJavaBeanSerialization() {}
private transient String myProp1 = null;
private String myProp2 = null;
@Transient public String getMyProp1() { return myProp1; }
public void setMyProp1(String a) { myProp1 = a; }
public String getMyProp2() { return myProp2; }
public void setMyProp2(String a) { myProp2 = a; }
public static void main( String[] args ) {
TestJavaBeanSerialization myObj = new TestJavaBeanSerialization();
myObj.setMyProp1("prop 1");
myObj.setMyProp2("prop 2");
XMLEncoder encoder = new XMLEncoder(System.out);
encoder.writeObject(myObj);
encoder.close();
}
}
```
Here's the output of running this program:
```<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_29" class="java.beans.XMLDecoder">
<object class="TestJavaBeanSerialization">
<void property="myProp1">
<string>prop 1</string>
</void>
<void property="myProp2">
<string>prop 2</string>
</void>
</object>
</java>
```
UPDATE
I still have not received a definitive answer to the original question. There's this article that people keep referencing, but it's not clear and no one's given a reference to an API or spec that clearly states the only way to mark a property as transient is to loop through all the properties and call "setValue".
Comment: You've posted your workaround...could you post the code that doesn't work?
Comment: Because the official JavaBeans tutorial says the transient property should work: http://docs.oracle.com/javase/tutorial/javabeans/advanced/persistence.html
Comment: BTW, I did not get my example from any official document... so what official document are you referring to?
Comment: Hmmm... I haven't read anywhere that the two are different. But I guess that's the case. I've read this article you give and I've read the java tutorial I posted a couple comments up. I'd very much like to see an official document from Oracle explaining the differences between XMLEncoder and Java Object Serialization API. It's unfortunate that such a document is not easily found, as it makes a lot of sense to use the "transient" modifier for XMLEncoder as well as ObjectOutputStream/ObjectInputStream.
Comment: The standard Java object serialization API is a language-level construct, and as such the transient keyword is only available to the compiler, [email protected]. As far as I can tell the XML serialization system is what they implemented upon realizing that the original API was terrible. Alas, like much of Java it is robust but very heavy on boilerplate code.
Comment: But like many annoying boilerplate-y things in Java, using Groovy can lend it a lot of brevity:
`def agentPD = Introspector.getBeanInfo(this).propertyDescriptors.find { it.name == "agent" }
agentPD.setValue("transient", Boolean.TRUE)`
;)
Comment: A @Transient annotation would be available at runtime just fine. There's no explanation along the lines of "it can't be done"
Comment: I agree with @BogdanCalmac, the Transient annotation (from java.beans) has the same effect than FeatureDescriptor.setValue("transient", Boolean.TRUE).
Comment: Given that you seem to have obtained this code from the official documentation site, why would you expect there to be another method for excluding properties from serialization?
Comment: You are mixing up standard serialization with XMLEncoder serialization - http://java.sun.com/products/jfc/tsc/articles/persistence4/#transient
Here is another answer: I was accustomed to use this known solution for several years in my own code but there is a much more simple one since Java 1.7: the java.beans.Transient annotation. Note that you can use it on the getters and the setters but not on the fields unlike javax.persistence.Transient (JPA).
```import java.beans.Transient;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static final void main(String[] args) throws Throwable {
final Capsule caps = new Capsule();
caps.setIdentifier("6545346");
caps.setMe("Julien");
caps.setSentences(new ArrayList<>(Arrays.asList(new String[]{"I don't like my job","I prefer sleeping"})));
try (FileOutputStream fOut = new FileOutputStream(new File(System.getProperty("user.home"), "test.xml"));
BufferedOutputStream out = new BufferedOutputStream(fOut);
XMLEncoder encoder = new XMLEncoder(out)) {
encoder.writeObject(caps);
encoder.flush();
}
}
public static final class Capsule {
private String identifier;
private transient String me;
private transient ArrayList<String> sentences;
public Capsule() {
super();
}
@Transient
public ArrayList<String> getSentences() {
return sentences;
}
@Transient
public void setSentences(ArrayList<String> sentences) {
this.sentences = sentences;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
@Transient
public String getMe() {
return me;
}
@Transient
public void setMe(String me) {
this.me = me;
}
}}
```
The result is:
```<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_76" class="java.beans.XMLDecoder">
<object class="Test$Capsule">
<void property="identifier">
<string>6545346</string>
</void>
</object>
</java>
```
Note the absence of the transient values. I couldn't skip the collections in 2009 but it seems to work now.
Here is another answer: You use the wrong @Transient
Should use java.beans.Transient for the annotation. javax.persistence.Transient is only respected in the context of database persistence, not BeanInfo serialization.
Here is another answer: I had a similar problem and I was looking for an easier solution. The way I managed it is by breaking Java Beans conventions.
If you don't want to serialize a field, don't set getters setters for it. Instead of "get" and "set", use other prefixes like "retrieve" and "save". For example -
```int x=0;
public int retrieveX() {
return x;
}
public void saveX(int x) {
this.x = x;
}
```
This did the trick for me and I'm sure will help others who don't specifically need Java Beans conventions in the code. Using this way makes the variable available throughout your application but at the same time hiding it from XMLEncoder serializer.
Hope it helps someone in future.
Comment for this answer: I like this idea and +1'd it, but it is difficult to bring myself to use this method as it will require that I remember the method is called `retrieveX()` years after I wrote it. I don't think that's likely.
Here is another answer: this is the only way that declare properties is transient.you can see the article. Url is http://www.oracle.com/technetwork/java/persistence4-140124.html?ssSourceSiteId=otncn#transient
Comment for this answer: where is the '@Transient' from?why i compile error and display 'Transient cannot be resolved to a type'
Comment for this answer: your class may implements Externalizable interface,then you provide implementations for both readExternal and writeExternal method.In writeExternal method you can serialize specific properties.
Comment for this answer: This is an article, it does not say that the only way to mark a property as transient is with setValue("transient", Boolean.TRUE);. Furthermore, the tutorial explicitly says: "Selectively exclude fields you do not want serialized by marking with the transient (or static) modifier." The tutorial can be found at: http://docs.oracle.com/javase/tutorial/javabeans/advanced/persistence.html
Comment for this answer: Sorry, the @Transient is provided by import javax.persistence.Transient;
Comment for this answer: What is the difference?
Comment for this answer: @Jason You make a confusion between the bean persistence and the long term persistence. Jax jiang, this annotation is available since Java 1.7.
Here is another answer: A workaround might be to use JAXB as your XML serializer which is bundled with Java 1.6. It supports an @XmlTransient annotation.
|
Title: Struts2: How do I tell my index.jsp to forward to a struts2 action?
Tags: java;web-applications;frameworks;struts2
Question: Oftentimes when I see an index.jsp on a web application it just forwards to another url like login.jsp such as
```<jsp:forward page="login.jsp" />
```
When using struts2, I want a similar index.jsp but I want it to forward to an action. How do I do this?
Here is the accepted answer: You can use plain HTML if you want
Between your head tags use:
``` <META HTTP-EQUIV="Refresh" CONTENT="1;URL=Login.action">
```
This will redirect to myCOntext/Login.action
If Login is behind a name space you wil need to include that in the URL
Comment for this answer: Probably irrelevant for this case, but this is redirect, NOT forward.
Comment for this answer: Thank you alzoid. Never thought it would be that simple :)
Here is another answer: Scriplet:
```<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
response.sendRedirect("/Project/namespace/Login.action");
%>
```
I use it with Struts2 and it works.
Comment for this answer: True. I do this now, but three years ago I was still using them :)
Comment for this answer: @Trick in struts2 scriplets should be avoid.
Comment for this answer: Thank you. This works, but I'm trying to avoid using scriptlets ;)
Here is another answer: Try this:
```<META HTTP-EQUIV="Refresh" CONTENT="0;URL=welcomeLink.action">
```
This is also a working one,
```<%
response.sendRedirect("welcomeLink.action");
%>
```
But in my experience it will work only when it is in index page, or any other page which is loaded as first page.
If I put response.sendRedirect in any successor page it will not work Reffer this question
Comment for this answer: In index.jsp you need to add only this line. It will goes to your Struts.xml and find mappings for this action.
It will work
|
Title: How to use Longitude and Latitude values from locationManager function elsewhere in my app in Swift
Tags: ios;swift;core-location;openweathermap
Question: I am using the ```CoreLocation``` framework to get the user's location when they open up my app. I use this function:
```func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
```
to get the user's longitude and latitude position, and I can see them by printing them to the logs. This works fine.
elsewhere in my app (but in the same ```viewController.swift``` file) I have code that uses the OpenWeatherMap API, and I have a string that contains the url for this, which return JSON.
In my ```viewDidLoad```, I use:
```getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=XXXXXX&lon=XXXXXX&appid=(MY-APP-ID)")
```
I need to place the Long and Lat values that I've acquired in the ```locationManager``` function, into this string, which I know I can do by ```"\()"``` within the url string.
My problem is, I can currently only use these values inside the ```locationManager``` function. How can I store them in a value outside of this function, so I can add them into my URL string?
Thanks
Here is the accepted answer: Hope this answers your question.
```import UIKit
import MapKit
class myClass {
var userLocation: CLLocationCoordinate2D? // The user location as an Optional stored as a var in class "myClass".
// !!! This can be accessed everywhere within the class "myClass" (and deeper)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate // Change it from var to let since it's only read not writen
// !!! This can be accessed everywhere within the func "locationManager" (and deeper)
userLocation = locValue // !!! Store it if necessary
// Why would you call this in viewDidLoad? I doubt the user location will be available at this point (but it might). You can move this anywhere if you want
// note the "\(name)" this will turn the var name into a string
// if != nil not necessary here since it cannot be nil but still added it regardless
// Maybe you want to add a check so this only gets called on the first location update. It depends on what you need it for.
if userLocation != nil {
getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=\(userLocation!.latitude)&lon=\(userLocation!.latitude)&appid=(MY-APP-ID)") // Why would you call this in viewDidLoad? I doubt user doubt the user location will be available at this point (but it might)
}
else {
print("Error: User not Located (yet)")
}
}
}
```
Comment for this answer: That's what I was gonna suggest: Don't call `getWeatherData` in `viewDidLoad`, call it once you have that data (in `locationManager...`). If you need the data elsewhere after that, why not save them in a var of your class?
|
Title: Php call static method of class which is in variable
Tags: php;variables;namespaces
Question: I have a namespace ```App\Term``` which is saved as a property: ```$this->name = 'App\Term'```. How can I call a static method of this class like ```$this->nam181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16methodName()``` ? Or is there another solution for this problem?
Comment: Does `$nam181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16methodName()` not work?
Comment: I updated the question. It should be not a simple variable like `$name`. It is a property: `$this->name`
Here is the accepted answer: You can use ```call_user_func``` for this.
```call_user_func($name.'181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16methodName');
```
Or:
```call_user_func(array($name, 'methodName'));
```
Comment for this answer: Perfect. I works even with property: `call_user_func($this->name.'181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16methodName');`
|
Title: Regex taking a lot of time when tested with large data
Tags: java;regex
Question: I have created a java regex
```(?=\b((?<![^\p{Alnum}\p{Punct}])(?:\p{Alnum}+\p{Punct}\p{Alnum}+){2})\b)
```
I tested this regex against a sample string: https://www.google.com.google.com
It is giving me all the expected tokens:
```www.google.com google.com.google com.google.com
```
But, the issue with the above regex is that it is taking a lot of time when tested with a large string.
My expected tokens are in the form of "alphanumeric punctuation alphanumeric".
How can I optimize this regex?
Comment: To check, do you want matches which are "alphanumeric punctuation alphanumeric" or strings which are made up of alphanumeric strings delimited by single punctuation characters (i.e. so you can have multiple `www.google.com` is valid as well as `www.google` being valid? E.g. https://regex101.com/r/LVLTFg/1
Here is the accepted answer: You need to simplify the regex like this:
```(?=\b((?:\p{Alnum}+\p{Punct}){2}\p{Alnum}+)\b)
```
See the regex demo.
Details:
```\b``` - a word boundary
```((?:\p{Alnum}+\p{Punct}){2}\p{Alnum}+)``` - Group 1:
```(?:\p{Alnum}+\p{Punct}){2}``` - two occurrences of one or more letters/digits and a punctuation char and then
```\p{Alnum}+``` - one or more letters/digits
```\b``` - a word boundary
Note that each subsequent pattern does not match at the same location inside the string, which makes it as efficient as it can be (still, the overlapping patterns performance is not that great since they must evaluate each position inside the string, from left to right).
Comment for this answer: Thank you so much, Wiktor. Earlier, it was taking 2 mins 20 sec but, now it gave the result in 4 secs.
Comment for this answer: @DareToDead Patterns like `(a+ba+)+` are catastrophic backtracking prone. You can learn more about this in [this YT video of mine](https://www.youtube.com/watch?v=4-nrlRF5xX0). Although the regex described is an email validation pattern, you will see the similar approach.
|
Title: Configure Maven settings for deployment
Tags: maven;jenkins;nexus
Question: I want to deploy artifacts to Nexus from Jenkins to different repositories (like ```builds-all```, ```builds-verified```, ```releases```). The thing is that I want to keep minimal configuration in the project POM file. My settings file now looks like:
```<servers>
<server>
<id>orion-nexus</id>
<username>admin</username>
<password>password</password>
</server>
</servers>
<localRepository>~/.m2/repository</localRepository>
<profiles>
<!-- Deployment configuration for CI builds for mainline -->
<profile>
<id>build</id>
<repositories>
<repository>
<id>builds-all</id>
<url>http://orion-nexus:8081/</url>
<snapshots>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
</profile>
</profiles>
```
Project POM:
```<distributionManagement>
<repository>
<id>orion-nexus</id>
<layout>default</layout>
<url><!-- how to avoid explicit URL? --></url>
</repository>
</distributionManagement>
```
I wan to run deploy like ```mvn -B -P build clean install deploy```. However, I don't understand how to avoid setting explicit URL in distribution management section. Can I set a variable in settings file and propagate it to my POM?
Is there any step-by-step guide for such workflow?
Comment: Why do you not want a URL here? It's the perfect place for it: each project declares where it should be pushed. There was a long mail about this on the [Maven mailing list](http://maven.40175.n5.nabble.com/Can-t-specify-distributionManagement-in-settings-xml-td3181781.html) that will interest you. At the end of it, you'll agree :)
Comment: If you need it for more than one project simply start creating a corporate pom which defines this.
Here is the accepted answer: You can declare a property inside a profile on your ```settings.xml``` and use its name within ```<distributionManagement/>``` configuration.
settings.xml
```<profiles>
<profile>
<id>distmgt</id>
<properties>
<distUrl>scp://...</distUrl>
<properties/>
</profile>
</profiles>
```
pom.xml
```<distributionManagement>
<repository>
<id>orion-nexus</id>
<layout>default</layout>
<url>${distUrl}</url>
</repository>
</distributionManagement>
```
And finally
```mvn -P distmgt clean deploy
```
You can avoid the ```-P build``` params using activation.
|
Title: Object causing an undefined error in console
Tags: javascript;ajax;object;undefined;console.log
Question: There wasn't something close enough to this already... at least that my newbie mind could grasp.
I'm just trying to play around creating a global containing object that has methods, and contained within are the instructions to create and use AJAX requests. I then proceed to create an event listener for a button. I then get the following console output.
```Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Uncaught ReferenceError: globOject is not defined script.js:21
Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Exception in onResRdy: TypeError: Cannot read property 'htmlRes' of undefined ContentScript.js:84
```
I'm sure I'm doing a lot wrong here. Let me know what additional info I would need to include to get assistance on this.
```var globObject = {
sendToServer: function () {
alert('you got to me at least!');
var xhr;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhr=new XMLHttpRequest();
}
else {// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'counterDoc.php', true);
xhr.send();
},
counterClick: function (counter) {
alert('you got here!');
counter += 1;
this.sendToServer();
}};
var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0), true);
```
Comment: typo: `globOject.counterClick(0), true);` should be `globObject.counterClick(0), true);`
Comment: This question appears to be off-topic because it is just a typo.
Comment: Sorry I missed that guys, I'm sad now. :(
Here is the accepted answer:
Fix the typo I said in comment and also @Bonakid mentioned. ```globOject.counterClick(0), true);``` should be ```globObject.counterClick(0), true);```
Do not use ```globObject.counterClick(0)``` for callback function, use ```globObject.counterClick``` instead. The first one will get called immediately when ```globObject``` is defined.
Do not use ```this.sendToServer();```, use ```globObject.sendToServer();``` instead. ```this``` in the ```counterClick``` method will be ```document.getElementById('submbut')``` which is a HTML element. Add ```console.log(this)``` to ```counterClick``` and you will see that.
A working demo here
Comment for this answer: WoW! the simplest things. Thank you.
Here is another answer: change this
```var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0)
```
to
```var button = document.getElementById('submbut').addEventListener('click',globObject.counterClick(0)
```
theres a typographical error in this part
```globOject.counterClick(0)
```
|
Title: Lua table read and match efficient
Tags: function;lua;while-loop;lua-table;codea
Question: My problem is simple, i used to do this in order to check if any of my lines (see photo) bump into any other line (or trail of any other line). But the way i do this now is by doing a lot of if statements, which is not good. So here is the code i used:
```function Bumper:draw()
for id,posx1 in pairs(tableposx1) do
posy1 = tableposy1[id]
posx2 = tableposx2[id]
posy2 = tableposy2[id]
posx3 = tableposx3[id]
posy3 = tableposy3[id]
posx4 = tableposx4[id]
posy4 = tableposy4[id]
if (posx1 ~= nil) and (posy1 ~= nil) and
((math.abs(xposplayer1 - posx1) < 5) and (math.abs(yposplayer1 - posy1) < 5))
and (id < (count - 5) and killp1 == "false") then
killp1 = "true"
tint(255, 0, 0, 162)
sprite("Dropbox:kill",xposplayer1,yposplayer1)
noTint()
end
if (posx2 ~= nil) and (posy2 ~= nil) and
((math.abs(xposplayer1 - posx2) < 5) and (math.abs(yposplayer1 - posy2) < 5))
and killp1 == "false" then
killp1 = "true"
tint(255, 0, 0, 162)
sprite("Dropbox:kill",xposplayer1,yposplayer1)
noTint()
end
if (posx3 ~= nil) and (posy3 ~= nil) and
((math.abs(xposplayer1 - posx3) < 5) and (math.abs(yposplayer1 - posy3) < 5))
and killp1 == "false" then
killp1 = "true"
tint(255, 0, 0, 162)
sprite("Dropbox:kill",xposplayer1,yposplayer1)
noTint()
end
if (posx4 ~= nil) and (posy4 ~= nil) and
((math.abs(xposplayer1 - posx4) < 5) and (math.abs(yposplayer1 - posy4) < 5))
and killp1 == "false" then
killp1 = "true"
tint(255, 0, 0, 162)
sprite("Dropbox:kill",xposplayer1,yposplayer1)
noTint()
end
if (posx1 ~= nil) and (posy1 ~= nil) and
((math.abs(xposplayer2 - posx1) < 5) and (math.abs(yposplayer2 - posy1) < 5))
and killp2 == "false" then
killp2 = "true"
tint(0, 29, 255, 162)
sprite("Dropbox:kill",xposplayer2,yposplayer2)
noTint()
end
if (posx2 ~= nil) and (posy2 ~= nil) and
((math.abs(xposplayer2 - posx2) < 5) and (math.abs(yposplayer2 - posy2) < 5))
and (id < (count - 5) and killp2 == "false")then
killp2 = "true"
tint(0, 29, 255, 162)
sprite("Dropbox:kill",xposplayer2,yposplayer2)
noTint()
end
if (posx3 ~= nil) and (posy3 ~= nil) and
((math.abs(xposplayer2 - posx3) < 5) and (math.abs(yposplayer2 - posy3) < 5))
and killp2 == "false" then
killp2 = "true"
tint(0, 29, 255, 162)
sprite("Dropbox:kill",xposplayer2,yposplayer2)
noTint()
end
if (posx4 ~= nil) and (posy4 ~= nil) and
((math.abs(xposplayer2 - posx4) < 5) and (math.abs(yposplayer2 - posy4) < 5))
and killp2 == "false" then
killp2 = "true"
tint(0, 29, 255, 162)
sprite("Dropbox:kill",xposplayer2,yposplayer2)
noTint()
end
if (posx1 ~= nil) and (posy1 ~= nil) and
((math.abs(xposplayer3 - posx1) < 5) and (math.abs(yposplayer3 - posy1) < 5))
and killp3 == "false" then
killp3 = "true"
tint(1, 255, 0, 162)
sprite("Dropbox:kill",xposplayer3,yposplayer3)
noTint()
end
if (posx2 ~= nil) and (posy2 ~= nil) and
((math.abs(xposplayer3 - posx2) < 5) and (math.abs(yposplayer3 - posy2) < 5))
and killp3 == "false" then
killp3 = "true"
tint(1, 255, 0, 162)
sprite("Dropbox:kill",xposplayer3,yposplayer3)
noTint()
end
if (posx3 ~= nil) and (posy3 ~= nil) and
((math.abs(xposplayer3 - posx3) < 5) and (math.abs(yposplayer3 - posy3) < 5))
and (id < (count - 5) and killp3 == "false") then
killp3 = "true"
tint(1, 255, 0, 162)
sprite("Dropbox:kill",xposplayer3,yposplayer3)
noTint()
end
if (posx4 ~= nil) and (posy4 ~= nil) and
((math.abs(xposplayer3 - posx4) < 5) and (math.abs(yposplayer3 - posy4) < 5))
and killp3 == "false" then
killp3 = "true"
tint(1, 255, 0, 162)
sprite("Dropbox:kill",xposplayer3,yposplayer3)
noTint()
end
if (posx1 ~= nil) and (posy1 ~= nil) and
((math.abs(xposplayer4 - posx1) < 5) and (math.abs(yposplayer4 - posy1) < 5))
and killp4 == "false" then
killp4 = "true"
tint(255, 0, 229, 162)
sprite("Dropbox:kill",xposplayer4,yposplayer4)
noTint()
end
if (posx2 ~= nil) and (posy2 ~= nil) and
((math.abs(xposplayer4 - posx2) < 5) and (math.abs(yposplayer4 - posy2) < 5))
and killp4 == "false" then
killp4 = "true"
tint(255, 0, 229, 162)
sprite("Dropbox:kill",xposplayer4,yposplayer4)
noTint()
end
if (posx3 ~= nil) and (posy3 ~= nil) and
((math.abs(xposplayer4 - posx3) < 5) and (math.abs(yposplayer4 - posy3) < 5))
and killp4 == "false" then
killp4 = "true"
tint(255, 0, 229, 162)
sprite("Dropbox:kill",xposplayer4,yposplayer4)
noTint()
end
if (posx4 ~= nil) and (posy4 ~= nil) and
((math.abs(xposplayer4 - posx4) < 5) and (math.abs(yposplayer4 - posy4) < 5))
and id < (count - 5) and killp4 == "false" then
killp4 = "true"
tint(255, 0, 229, 162)
sprite("Dropbox:kill",xposplayer4,yposplayer4)
noTint()
end
end
end
```
Here is my init:
``` -- Main
a = 1
gameover = 0
tx = 0
paused = 1
count = 0
stagecount = 0
player1count = 0
player2count = 0
player3count = 0
player4count = 0
-- Random hole times
thistime1 = 0
thistime2 = 0
thistime3 = 0
thistime4 = 0
-- Dead players
killp1 = "false"
killp2 = "false"
killp3 = "false"
killp4 = "false"
kills = 0
-- Touch control
touches = {}
-- Player direction
pi = math.pi
o5pi = 50 * pi
mo5pi = - (50 * pi)
minpi = - (100*pi)
-- Random start direction
r1t = math.random(0,o5pi)
r2t = math.random(mo5pi,0)
r3t = math.random(minpi,mo5pi)
r4t = math.random(o5pi,100*pi)
r1 = r1t / 100
r2 = r2t / 100
r3 = r3t / 100
r4 = r4t / 100
deltar1 = pi / 55
deltar2 = pi / 55
deltar3 = pi / 55
deltar4 = pi / 55
-- Player speed
speed1 = 2.5
speed2 = 2.5
speed3 = 2.5
speed4 = 2.5
-- Player random start position
xposplayer1 = math.random(123,300)
yposplayer1 = math.random(123,300)
xposplayer2 = math.random(123,300)
yposplayer2 = math.random(468,645)
xposplayer3 = math.random(724,901)
yposplayer3 = math.random(468,645)
xposplayer4 = math.random(724,901)
yposplayer4 = math.random(123,300)
-- Player coordinate tables
tableposx1 = {}
tableposy1 = {}
tableposx2 = {}
tableposy2 = {}
tableposx3 = {}
tableposy3 = {}
tableposx4 = {}
tableposy4 = {}
```
Now i tried doing the following, but failed because i dont now how to use variable variable names:
```for id,posx[a] in pairs(tableposx[a]) do
posy[a] = tableposy[a][id]
if ((posx[a] ~= nil) and (posy[a] ~= nil))
and (math.abs(xposplayer[a] - posx[a]) < 5)
and (math.abs(yposplayer[a] - posy[a]) < 5)
and (id < (count - 5))
and (killp[a] == "false")
then
killp[a] = "true"
tintp[a]
sprite("Dropbox:kill",xposplayer[a],yposplayer[a])
noTint()
end
end
a = a + 1
if a = 4 then
a = 1
end
```
-- EDIT: i use is 4 times, for 4 players!
```function Player:draw1()
fill(255, 0, 11, 255)
xposplayer1 = xposplayer1 + speed1 * math.cos(r1)
yposplayer1 = yposplayer1 + speed1 * math.sin(r1)
if player1count == 0 then
thistime1 = math.random(200,500)
end
player1count = player1count + 1
if player1count < thistime1 then
table.insert(tableposx1,count,xposplayer1)
table.insert(tableposy1,count,yposplayer1)
tint(255, 0, 0, 162)
ellipse(xposplayer1,yposplayer1,10,10)
noTint()
elseif player1count > thistime1 then
tint(255, 0, 0, 162)
ellipse(xposplayer1,yposplayer1,5,5)
noTint()
if player1count > thistime1 + 20 then
player1count = 0
end
end
```
end
-- EDIT
How should i do this correctly? Thanks in advance!
Image:
Here is the accepted answer: You probably don't really want variable variable names like you said, but you can do it...
All globals are accessible by table named ```_G```, and you can access your global variables by doing this:
```_G['killp1']
_G['killp2']
-- etc
```
You can then use string manipulation as usual.
```local i = 1
_G['killp' .. tostring(i)] -- same as _G['killp1']
i = i + 1
_G['killp' .. tostring(i)] -- same as _G['killp2']
```
But this is going to get really messy, fast. What you probably want to do instead is start using objects. You object might look something like this:
```Linething = { x = 0, y = 0, dead = false, speed = 2.5 }
function Linething:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Linething:checkCollision(other)
if self.x - other.x < 5 and self.y - other.y < 5 then
self.dead = true
-- other stuff
end
end
function Linething:update(delta_t)
-- update the game logic
self.x = self.x + self.speed * cos(self.angle) * delta_t
self.y = self.y + self.speed * sin(self.angle) * delta_t
end
function Linething:draw()
-- do line drawing here
tint(255, 0, 0, 162)
ellipse(self.x, self.y, 10, 10)
noTint()
-- etc
end
-- in main:
linething1 = Linething:new()
linething2 = Linething:new()
linething1.checkCollision(linething2)
```
EDIT: Typically you want to seperate the game logic from the rendering. Most games have a loop that looks like this:
```function main_loop()
while true do
delta_t = get_change_in_time()
update_all(delta_t)
draw_all()
end
end
-- where update_all is something like this:
function update_all(delta_t)
player1:update(delta_t)
player2:update(delta_t)
-- things in a table:
for _, x in pairs(table_of_x) do
x:update(delta_t)
end
end
-- and draw all is basically the same
function draw_all()
player1:draw()
player2:draw()
-- things in a table:
for _, x in pairs(table_of_x) do
x:draw()
end
end
```
It looks like your ```Player``` object has-a ```Linething``` object. So you might want to add a ```Linething``` object to the ```Player``` object and change ```Player:draw()``` to call ```players_linething:draw()```. Then you can have 4 ```Player``` objects, which each have a ```Linething``` object. Does that make sense?
Comment for this answer: Ok, so should i get the first part in my 'init' file and the last bit in the main, or is something else needed?
Comment for this answer: I edited my post, so you can see how i draw the lines, how an i integrate your 'object functions' with the way i draw my lines? Thanks
Here is another answer: I have not read everything but in your last snippet:
You cannot do ```for id,posx[a]```, because the variables assigned by a ```for``` loop are local. To fix it replace instances of ```posx[a]``` by a local variable name such as ```posx_a```.
There is a typo here: ```if a = 4 then``` (you mean ```==```).
This line means nothing: ```tintp[a]```.
Here is another answer: The problem is that you're using variables with subscripts (player1, player2, etc.) rather than arrays (player[1], player[2], etc.) which makes it impossible to iterate over them in a loop.
You should also be grouping related items together. Rather than player 1 being represented by a bunch of global variables:
```player1count = 0
speed1 = 2.5
```
Those things should be organized into a table:
```player1.count = 0
speed1.speed = 2.5
```
And, as mentioned before, any time you have a bunch of variables that vary by subscript, you should be using an array (or more generally, some kind of iterable list type, which in Lua happens to be a table/array):
```players = {}
-- initialize players
for i=1,NUM_PLAYERS do
players[i] = {
count = 0,
speed = 2.5
}
end
```
If you apply this generally to your program, your huge ```if``` statement is going to naturally disappear, being replaced by a relatively small, nested for loop.
|
Title: How to add additional argument to all templates in play framework
Tags: routing;playframework
Question: We have completed 95% of our application. We want to add additional argument mode=1 to all templates URLS's in the browser. Is it possible by adding in one place like routing file,
The URL should be like be visible in the address bar.
Suppose, the original url is
```http://localhost:9000/design/customersList
```
it needs to be add the mode=1, which will be like
```http://localhost:9000/design/customersList?mode=1
```
Generally
```http://localhost:9000/{module}/{action}?mode=1
```
Comment: I have to pass in all the URL's. This URL will be passed to LoadBalancer( my another play application in another machine). Which will decide where to go. if mode=1 then it will send the URL to my PlayApplication1, if mode=2 then it will send the URL to my another PlayApplication2 on another machine and so on.
Comment: Additional Info: if user changes mode=1, Then Application1 will be trigger, if changes to mode=2 then then Application2 will be trigger. Application1 and Apllication2 are completely different from functionality and UI. Application1 is a PlayApplication. Application2 can be a PlayApplication or Symfony or whatever.
Comment: where are you actually using this parameter? in the html templates?
Here is the accepted answer: I couldn't find any inbuild option in play to do that. So i added the mode in every template.
Here is another answer: Create a controller with a @Before method and in this method add your arg
```@Before
public static void setUpTemplate() {
renderArgs.put("mode", "1");
}
```
In all your controllers, add this Controller as an interceptor with a @With annotation
Comment for this answer: this argument should be viewed in the url like http://localhost:9000/design/reportsList?customer=10&mode=1
Here is another answer: Do you want to access the configuration file from your views? If so, you can do it like this:
```#{if play.Play.configuration.get("yourKey") == '1'}
... Do something ...
#{/if}
```
Otherwise, where do your "Additional arguments" come from?
Comment for this answer: the user will type in the url ( any url) or we will receive a url with mode as one argument
|
Title: SSH2 Connect Issues
Tags: php;laravel;ssh
Question: I am using Laravel framework with homestead. (Latest Version) and i am trying to use ssh2_connect. I have installed the extension
```sudo apt install php-ssh2
```
and i have tested that its working
```php -m |grep ssh2
```
i am seeing
```ssh2
```
i am assuming that this is correct but when i try and make a connection i get the following error.
```Call to undefined function App\Http\Controllers\ssh2_connect()
```
This is the code i am executing
``` $connection = ssh2_connect($request->sever_ip, 2222);
if (!$connection) die('Connection failed');
```
Would someone point me in the right direction?
Comment: $connection = ssh2_connect($request->sever_ip, 2222);
if (!$connection) die('Connection failed');
Comment: just updated.!!
Comment: where is the php code?
Comment: Add it in the question, not as a comment.
Here is the accepted answer: Because you are in the namespace of the ```Controllers``` you might need to use:
```$connection = \ssh2_connect($request->sever_ip, 2222);
if (!$connection) die('Connection failed');
```
Comment for this answer: It should work without backslash. Per the documentation: `For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.` https://secure.php.net/manual/en/language.namespaces.fallback.php It's only for globlal classes that you need the backslash.
Comment for this answer: Yes i think the function is just not loaded properly. Maybe it's setup for the php command line but not Apache.
Comment for this answer: i have fixed it after a `vagrant provision` this seem to get it all working.
Comment for this answer: @this.lau_ I agree with you, however I've seen some weird things related to namespaces. If the above doesn't work it is probably ssh2 isn't loaded by the php (apache restart might be needed here).
|
Title: How to Detect 'Batch' mode from within a Batch File under Windows
Tags: windows;batch-file;cmd
Question: I'm running a batch (.bat) file via the Windows (Task) Scheduler, a third party cron (nncronLite) and via a "START" command. I'm trying to work out a way that I can detect the .bat file has been run via one of the above means compared to me running the batch file from a console (cmd.exe) window.
I can try checking an environment variable.. but which one (here I'm trying HOMEDRIVE)?
```setlocal
set BATCH_MODE=1
if defined HOMEDRIVE set BATCH_MODE=
rem [...]
if defined BATCH_MODE echo IN BATCH MODE
```
Any other suggested mechanims (other than supplying a command line argument to the batch file = kludge, IMO)?
This is for use with Windows XP, Win7, Win8, Win10 (and beyond, I guess)
Thanks.
Comment: @Aacini: That variable shows the actual command line used to invoke the .bat file when in 'batch' mode and just the name (no .bat) of the batch file when run in a console (cmd.exe) window. So, maybe I can do something with comparing COMSPEC with CMDLINE or CMDCMDLINE.
BTW, where did you find out about the existence of CMDCMDLINE? It's not shown by a 'SET' command, nor is it included in the System Environment Variables...?
Comment: Type `set` to list all variables, including `CMDCMDLINE`. Type `set /?` to find the help for the `set` command, which includes the predefined environment variables.
Comment: @Aacini, then it's probably `cmd /?`...
Comment: Ah yes, @Aacini, seems I misunderstood you. You are perfectly right, `CMDCMDLINE` is also a dynamic variable of course; sorry for confusion!
Comment: Look for _the value_ of `%CMDCMDLINE%` variable...
Comment: @aschipfl: `set` command does _not_ list the dynamic variables...
Comment: @aschipfl: what I mean is that `set /?` _describes_ all the dynamic variables, and `set` command list the variables defined in the environment. Because its nature, the _dynamic_ variables are _not_ defined in the environment, so `set` command does _not_ list anyone of they, like CMDCMDLINE, ERRORLEVEL, TIME, RANDOM, etc.
|
Title: Travel from Hahn airport to Bornheim Berger Straße in Frankfurt
Tags: air-travel;hhn
Question: I am flying to Hahn from UK and I would like to go to Bornheim Berger street in Frankfurt. I just checked the taxis and it is very expensive. I can be picked up or get a taxi once I am a bit closer to Frankfurt. Any idea if there are there any shuttles that are fast and I can share the cost with others?
Comment: Just a small side note: Though the airport is called *Frankfurt* Hahn, it is really far away from Frankfurt, that's why taxis would be horribly expensive. The same goes for *Munich West*, as Memmingen Airport is called by some airlines.
Comment: Yep, This airport naming is a pretty nasty marketing plot. Hahn Airport is not even remotely near Frankfurt and it's actually closer to Luxembourg City than it is to Frankfurt. Fastest would be a rental car. Any form of public transportation will require at least two hours plus whatever waiting is created by the schedule
Here is another answer: There is a bus service that goes from Hahn Frankfurt airport it takes two hours.
You can buy tickets here.
Then once in Frankfurt like you said you could use taxi.
Comment for this answer: I think at least for the Bohr shuttle a direct link here would be better: http://www.bohr.de/linienverkehr/fahrscheinbuchung but you can as well buy the ticket when you arrive there (unless it is during some weird hours)
|
Title: Java: Pick out multiple elements in Linked list
Tags: java;list;linked-list;listiterator
Question: I have a linked list of classes which contain 3 strings and a double. I want to collect the total value of each double in the list. For example
``` LinkedList<Person> L = new LinkedList<Person>();
Person p1 = new Person("Fee","Foo","Bar", 1.2);
Person p2 = new Person("Fi","Fi","Fo", 2.5);
L.add(p1);
L.add(p2);
```
I would want to find and add up 1.2, and 2.5. I'm assuming I should use ListIterator, but how do I tell it to add each found double value to the total?
Comment: To clarify: are you asking how to iterate over a list?
Comment: The list only contains one type: Person.
Comment: No, I know about Iteration, I just want to pick specific elements from a list with different data types.
Here is the accepted answer: You have couple of options to iterate over it
A) Using iterators as asked
```Person person = new Person();
ListIterator<Person> listIterator = L.listIterator();
while (listIterator.hasNext()) {
person = listIterator.next();
double value = person.getDoubleAttribute();
}
```
B) Use a ```for-each``` loop as suggested in other answer:
```for(Person person : L){
double value = person.getDoubleAttribute();
}
```
PS: is highly discouraged to start ```Java``` variables or attributes by ```UPPERCASE```
Comment for this answer: I know you will be hating me ;), but speaking of memory usage wouldn't it be better to put the `Person person = ...` outside of the loop? Because now it reserves new memory space in every iteration?
Here is another answer: You can iterate over the list, get the double property of each Person and sum them, or you can use Java 8 Streams :
```double sum = L.stream().mapToDouble(Person181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16getDoubleProperty).sum();
```
Where ```getDoubleProperty``` stands for the name of a method in the ```Person``` class returning the double value.
Here is another answer: Just use a for loop over the persons:
```double sum = 0;
for(Person p : L)
sum += p.getDouble();
System.out.print(sum);
```
Comment for this answer: @KnutKnutsen Use a `for each` loop maybe it's the easiest way but not the optimal. Also OP asked for `Iterator`in `LinkedList`...
Comment for this answer: @KnutKnutsen Internally converted is exactly what means less optimal ;)... Anyway, I'm totally agree with you, i don't like `Iterators`, code is less clear, but they are better in the memory usage...
Comment for this answer: not really, but sure you can easily find it... BTW: i edited my question to cover all possibilities... ;)
Comment for this answer: I think your approach is the better one, than the accepted answer ;) but skipping of brackets should be avoided due to increased error ratio when extending the loop. See http://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java
Comment for this answer: @JordiCastilla why not optimal? Sure he asked for an `Iterator`, but as far as I know the for-each loop will be internally converted to a similar approach. Even Oracle embraces the use of for-each, see http://docs.oracle.com/javase/7/docs/technotes/guides/language/foreach.html
Comment for this answer: @JordiCastilla PS: I didn't mean that your answer is wrong, but not so beautiful ;)
Comment for this answer: @JordiCastilla Do you have a source for the memory usage statement? (I'm really interested) I thought the conversion will be done by Compiler so that it should make any difference on runtime ?!
Comment for this answer: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69282/discussion-between-knutknutsen-and-jordi-castilla).
|
Title: Design pattern - data exporter
Tags: design-patterns;export
Question: I have a problem to solve where I export data from one system, into some intermediary database tables for another system to pick up.
There is a specific format for each object type and the associated fields i.e.:
Orders
Order id (int 10 - padded left with zeros if under - error if over)
Customer Name (varchar 150 - trimmed if over)
Customer address line 1 (varchar 250 - trimmed if over)
Aside from some brute force logic, listing each field, its data type and maximum length, then looping over each field in the object to enforce those rules ready to be exported, is there a more elegant solution or pattern for this type of problem.
Im assuming this is pretty much a standard problem throughout many years of business programs and must have been solved countless times.
Comment: the source data structure is different to the target
Comment: Isn't this just straight forward SQL?
|
Title: Problema para desplegar servidor GLPI
Tags: composer;glpi
Question: Tengo un problema a la hora de instalar el servidor GLPI a traves de xampp, tengo descargado el composer y la version de PHP 8.1.1 cuando ejecuto en el navegador me responde el aviso:
```
Application dependencies are not up to date. Run "php bin/console
dependencies install" in the glpi tree to fix this.
```
y una vez que con la consola ejecuto el comando con la consola colocada en la carpeta de glpip me responde:
```
"composer" no se reconoce como un comando interno o externo, programa
o archivo por lotes ejecutable
```
.
¿Alguna solución para poder finalizar la instalación?
Comment: el composer no lo has instalado globalmente tendrias que ubicarlo para poder ejecutarlo anteponiendo su ubicacion...
Comment: cuando tu pregunta en el sitio dice sugerencia, opciones, ideas etc... suelen cerrarte las preguntas por estar basadas en opiniones o faltar algo de ejemplo... trata de evitarlo
Comment: tambien seria bueno que agregaras los comandos que vas ejecutando... a lo mejor puede estar hay el error de sintaxis.
|
Title: Hibernate doesn't log anything anymore, since I relocated the log4j.xml and hibernate.properties files
Tags: java;hibernate;log4j
Question: I had the following working organization
```src/main/resources/log4j.xml```
```src/main/resources/hibernate.properties```
I wanted to reorganize my webapp as follow:
```src/main/resources/log/log4j.xml```
```src/main/resources/orm/hibernate.properties```
The ```Logger.info("foobar")``` still logs well (after having set the ```log4jConfigLocation``` context parameter), and the app still has a working database connection.
The problem is that Hibernate doesn't log anything anymore, even if ```hibernate.show_sql``` is set to ```true```. Any idea why? Should specify the new path to the ```log4j.xml``` file to Hibernate? If yes, how?
Here is the accepted answer: You could run your server with this VM argument:-
```-Dlog4j.configuration=/path/to/log4j.xml
```
I usually tend to place the log4j.xml at the recommended default location unless there's a need to do otherwise... "convention over configuration" is important especially if other peers may be working on the same project in the future.
Here is another answer: Log4j first looks for its configuration by looking at the system property "log4j.configuration". If that system property is not set, it looks for a log4j.properties or a log4j.xml file on the classpath.
So, if you really want the log4j.xml at src/main/resources/log/log4j.xml, you will have to set the log4j configuration system property. This is basically what limc does by supplying it as a vm argument.
Also like limc says, you should probably just keep the log4j.xml at the default location.
|
Title: ManyToMany forced unique index
Tags: spring;hibernate;jpa;spring-data-jpa;spring-data
Question: I let JPA to create tables. It can create base tables correctly but in the cross table, make one of the join columns unique. In this case, I cannot use as many to many.
Example schema:
Table1: id INT(11);
Table2: id INT(11);
CrossTable: t1id INT(11) nn, t2id INT(11) nn unq;
Here is the code:
```@ManyToMany
@JoinTable(name = "CrossTable",
joinColumns = { @JoinColumn(name = "t1id") },
inverseJoinColumns = { @JoinColumn(name = "t2id") })
@ElementCollection(targetClass=Table2.class)
private List<Table2> datttt;
```
Comment: Annotating a field with ManyToMany and ElementCollection makes no sense. It's one or the other. If Table2 is an entity, then it can't be an ElementCollection. If it's not an entity, then it can't be a ManyToMany. Finally, post the actual table definition being generated, not some pseudo-sql.
Comment: Thanks, deleting @ElementCollection fix it.
|
Title: ng-model not working inside ng-include
Tags: javascript;angularjs;angularjs-ng-include
Question: I am a beginner in angularjs and currently I am facing an issue with ng-include.
I have a test app using partials.
Here is my code.
```<html ng-app ="TextboxExample">
<head>
<title>Settings</title>
<script src="angular.js"></script>
</head>
<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
</html>
```
The partial code view.html is
```<input type="text" ng-model="textboxVal">
```
For some reason, textboxVal set to ng-model doesn't get updated when I enter the value in the text box.
But this works fine if I don't use ng-include and directly add the content of view.html into the main html file.
Please help.
Thanks
Sunil
Comment: ng-include creates a new scope
Comment: Check my answer below
Comment: ok, so I can I make it work?
Here is the accepted answer: Use $parent to access the scope of the controller
Demo
```<input type="text" ng-model="$parent.textboxVal">
```
Here is another answer: The problem is that ```ngInclude``` creates new scope, so the model you define inside partial template with ```ngModel``` works with local scope value, and outer ```ExampleController``` can't see it.
The simple solution is to use prototypical chain of scope objects, then inner scope will inherit and use model value from the outer scope:
```<body ng-controller="ExampleController">
<div ng-include src = "'view.html'"></div>
<script>
angular.module('TextboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.model.textboxVal = 'fddfd';
$scope.ReadGeneralSettings = function() {
alert($scope.model.textboxVal);
}
$scope.ResetGeneralSettings = function() {
$scope.model.textboxVal = 'fddfd';
}
}]);
</script>
<button class="pull-right" ng-click = "ReadGeneralSettings()">Read</button>
<button class="pull-right" ng-click = "ResetGeneralSettings()">Cancel</button>
</body>
```
and then use it in partial as
```<input type="text" ng-model="model.textboxVal">
```
|
Title: Is there a tool for python that can visualize methods and classes?
Tags: python;python-3.x
Question: Is there a tool that can visualize (such as tree view) all python functions and classes in a program and which function calls other functions? Trying to find dependencies of some real messy code.
Here is the accepted answer: Yes, there is. It is called ```pycallgraph```.
Comment for this answer: Does pycallgraph run the entire program to create the tree view?
|
Title: Angular 12 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ng-deep (deprecated)? Only option that's working?
Tags: angular;angular12
Question: I am trying the change the text in ngx-charts and this works:
```181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ng-deep .ngx-charts {
text{
fill: #ff0000;
}
}
```
The only issue is that ```181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16ng-deep``` is deprecated?
```:host``` will not work
So what do I use instead that works?
Here is the accepted answer: You'll likely have to apply this style at a global level in styles.[s]css or a file that gets imported in styles.[s]css/bundled when bundling your other global css.
(I usually path it directly from my component, ex:)
```app-my-component-that-uses-this-chart {
.ngx-charts {
text {
fill: #ff0000;
}
}
}
```
But you can also apply a class instead of a component name to make it more reusable
|
Title: How to suppress "DWARF2 CFI reader: unhandled CFI instruction" error in valgrind output?
Tags: valgrind
Question: I'm quite new in using valgrind. I'm running tests for my C library. I've tryed to run it under valgrind and got some very valuable info about possible errors in my code. One thing that bothers me is beginning of every valgrind session is full of messages like this:
```DWARF2 CFI reader: unhandled CFI instruction 0:22
```
IIUC it's unrelated to problems in my code and I'd like to disable them to simplify analysis of other errors. I've read valgrind help but can't find the proper command-line option.
Can you provide me some hints?
Here is the accepted answer: Support for these DWARF3 operations have been added. Just update to the current version of valgrind, available at http://valgrind.org.
|
Title: Get derived date dimension year or month
Tags: einstein-analytics;saql
Question: I'm creating a derived date dimension in SAQL and wanted to find out if there was any way to get the year or month (or day or quarter) parts from it? Normally, adding an "_year" to the end of a standard date dimension achieves this:
```q = group q by Date_1_year as 'Date1Year', count(q) as 'Count';
```
But this doesn't seem to work the same way on derived measures (even though the full derived date measure works):
```q = foreach q generate toDate(case when 'Date_1_sec_epoch' is not null then 'Date_1_sec_epoch' else 'Date_2_sec_epoch' end) as 'DateToUse';
-- This line doesn't work:
q = foreach q generate DateToUse_year as 'DateToUseYear', count(q) as 'Count';
-- This line works:
-- q = foreach q generate DateToUse as 'DateToUse', count(q) as 'Count';
```
Is augmenting the calculated date from a custom formula field in the underlying dataflow the only way to get this right?
Here is another answer: EA only generates these values for Dates loaded into a dataset:
Einstein Analytics Dates
To achieve someting similar, you can use the toString()-function:
q = foreach q generate toString(newDate, "yyyy") as newDate_Year;
|
Title: Webpack - React ES6 transpile every template (src to dist)
Tags: reactjs;webpack;html-webpack-plugin
Question: I am using webpack for react(es6) project.
My problem
I have built react app with ES6, so everywhere i have used import keyword for dependency. Now for server side rendering i am using NodeJS so its not support import yet. For this i have to use require instead of import.
Now i have used webpack for bundling my app, but it always generate final bundle file (single.bundle.js), That's why i am not able to import chunk of transpiled code for server side rendering.
Solution
If it is possible to transpile every file (src to dist), then i can import this es5 file into nodejs server code.
Question
Is this possible with webpack to transpile whole folder with same out put rather than bundle file ?
Otherwise i have to use grunt or gulp. :(
Comment: @Ursus package.json or webpack.config.js
Comment: @Ursus https://gist.github.com/Nishchit14/ba6edd1b36bb5161206847acf49072b3
Comment: @Ursus https://gist.github.com/Nishchit14/82916291809827e2b6113e934adcffed
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116790/discussion-between-nishchit-dhanani-and-u-r-s-u-s).
Comment: It'd be helpful if you showed your `package.json`
Comment: Let's see both please
Comment: Sorry can't see anything wrong with them.
Here is another answer: You can use webpack for server too. It will transpile to webpack server bundle only your specific code containing react and excluding node_modules by externals option. Here is example of ```webpack.config.js``` for server side
```var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/server.js',
output: {
path: __dirname,
filename: 'server.js'
},
target: 'node',
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
},
externals: nodeModules,
}
```
|
Title: 360 degree video in MPMoviePlayerController
Tags: objective-c;ios;mpmovieplayercontroller
Question: I am trying to develop an iphone application which needs to show a 360 degree video like the one and rotate the video as per the phone movement. How can i do this? Is it possible to do this with normal MPMovieplayer controller?
Comment: did you get any answer for the same?
Here is another answer: I don't think you can do this with a normal ```MPMoviePlayerController```, but there are several libraries out there to achieve this. Have a look here:
PanoramaGL
Panorama 360
They work with OpenGL and you can embed them in your Objective-C code.
EDIT:
As @Mangesh Vyas kindly pointed out those are intended to use with fixed images only. However they might be a suitable starting point for embedding video as well, if you modify the code accordingly. They already do the handling of direction, accelerometer etc. so you don't have to implement all that yourself.
Comment for this answer: @Mangesh would like to know how you did this? have similar requirement. help please
Comment for this answer: I see both the code but it is useful for panorama images. I needed for video like Gopano app does.
Comment for this answer: Stefan i Have done this with the Help of Flex. Same thing i also tried with js file. Thanks For your effort. I am giving you bounty points.
Comment for this answer: Sorry, yes they are intended for the use with images. My browser didn't load the video the OP linked, so it was just my assumption that you were looking for this. I will edit my answer.
Comment for this answer: Glad to hear you were successful! Thanks for the update and the points! :)
|
Title: Using a Drupal variable in SQL query
Tags: php;drupal
Question: I'm trying to stuff a variable into a SQL query to return a value to a page.
```$sql = 'SELECT account FROM users WHERE uid = arg(1)';
```
Where arg(1) = the user currently being viewed. I am outputting arg(1) at the top of the page, so I know it's there, but Drupal doesn't seem to want to take it. I've tried escaping several different ways. Below is the full code
``` function accountselect_getclientaccount() {
global $user;
$sql = 'SELECT account FROM users WHERE uid = arg(1)';
$result = db_result(db_query($sql));
return $result;
}
```
Here is the accepted answer: You could try:
```$uid = arg(1);
$result = db_result(db_query("SELECT account FROM {users} WHERE uid = %d", $uid));
```
Here is another answer: To avoid sql-injection, you should use placeholders (see db_query for more info):
```$result = db_query("SELECT * FROM {users} WHERE uid = %d", arg(1));
```
Also note that db_result is meant for single-column, single-result queries. You probably want to use db_fetch_object. Additionally, there isn't a column in the users table called account.
Comment for this answer: Thanks, jhedstrom - isn't the solution provided by anonymouse the same in terms of SQL injection attacks...?
By the way, I am only trying to grab one value, and I have created a column named `account`. I know that's like pissing on the Drupal bible, but for the specific situation I wanted to use it for, it needed to go that way. Besides, I'm betting that the User table doesn't change that much...
Comment for this answer: It is the same as anonymouse's...I think we cross-posted those answers.
Here is another answer: ```function accountselect_getclientaccount() {
return (arg(0) == 'user') ? db_result(db_query('SELECT account FROM {users} WHERE uid = %d', arg(1))) : FALSE;
}
```
I don't know why you're using the global $user. Maybe you should be using $user->uid instead of arg(1)? This would save you checking arg(1) is actually a user ID.
This might be better:
```function accountselect_getclientaccount($account) {
return db_result(db_query('SELECT account FROM {users} WHERE uid = %d', $account->uid));
}
```
Also: see the user hook. It might be best practice to return the 'account' col on the load operation (if you're not doing that already)
http://api.drupal.org/api/function/hook_user/6
Comment for this answer: You're right, I didn't need global $user in the code. I removed it shortly after. As far as the $user->uid, that returns the uid of the currently logged in user. arg(1) returns the uid of the user whose account you are viewing.
The purpose of the function is to load the users current account as default value in the select list. It was sort of a pain. What is 'load' operation? A user-edit state?
Comment for this answer: Edit is another state but you're kinda right. You would have loaded that account from that URL so you could write something like:
function mymodule_user($op, &$edit, &$account, $category) {
if($op == 'load') {
//do something to $account
}
}
It shouldn't be too hard if you hook into the API the right way :)
|
Title: st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16cin error for large file
Tags: c++;c++11
Question: I was benchmarking some I/O code with large input( 1Mb text file of integer, separated by tab, spaces or endline) then the normal cin method
```int temp;
cin >> temp;
while(temp!=0){ cin >> temp;}
```
Got into an infinite loop with temp value at 15
, there is no such long sequences in the input file however
The cooked up integer parsing method, with fread however did just fine
with a clock time of around 0.02ms
```void readAhead(size_t amount){
size_t remaining = stdinDataEnd - stdinPos;
if (remaining < amount){
memmove(stdinBuffer, stdinPos, remaining);
size_t sz = fread(stdinBuffer + remaining, 1, sizeof(stdinBuffer) - remaining, stdin);
stdinPos = stdinBuffer;
stdinDataEnd = stdinBuffer + remaining + sz;
if (stdinDataEnd != stdinBuffer + sizeof(stdinBuffer)){
*stdinDataEnd = 0;
}
}
}
int readInt(){
readAhead(16);
int x = 0;
bool neg = false;
// Skipp whitespace manually
while(*stdinPos == ' ' || *stdinPos == '\n' || *stdinPos == '\t'){
++stdinPos;
}
if (*stdinPos == '-') {
++stdinPos;
neg = true;
}
while (*stdinPos >= '0' && *stdinPos <= '9') {
x *= 10;
x += *stdinPos - '0';
++stdinPos;
}
return neg ? -x : x;
}
```
Any direction on how might cin get stuck ?
Comment: Thanks ive just realised that.
Comment: It's very simple. If the input does not contain an integer value, the formatted input extraction fails, and the input stream enters error state, which results in all subsequent input operation failing, until the error state gets cleared.
Comment: Fatal logic error: You never check the result of the input operation.
|
Title: Starting Ruby on Rails from an Objective-C background
Tags: ruby-on-rails;objective-c;ruby
Question: Right now I program exclusively with Objective-C using the Cocoa frameworks to write applications for the Mac OS X and iPhone/iPad platforms. I'm fairly fluent using the Objective-C language as well as the Cocoa and Cocoa Touch frameworks. I also know just enough C to be able to understand ObjC.
One of my projects requires that I write a corresponding web application for use with my iPhone app. I've decided that the best path to go with is Ruby on Rails. What is the easiest transition path to go from Objective-C to Ruby on Rails? Any starter guides/docs/tutorials are appreciated!
Thanks
Here is the accepted answer: I'm nearing the end of this tutorial myself, and I think it's a perfect resource for those who are already familiar with software development, particularly web application development in general. I come from a Java background, but have dabbled in PHP and Python (specifically, Django). This tutorial has given me tremendous exposure to Rails in a very friendly way.
I still have some unanswered questions, but less than I had when I tried learning from other books.
As a side note, the tutorial briefly discusses learning Ruby first then Rails vs learning Rails first then Ruby (it ultimately suggests Rails first).
Here is another answer: I'm not sure if it was available back when this question was first asked, but I think http://railsforzombies.org/ is an excellent first tutorial. It introduces the framework in a way that's accessible, interactive and engaging, and it makes a great foundation for further study. I got a lot out of it.
Here is another answer: How to make a rails application app as a versioned api in less than 10 minutes.
http://railscasts.com/episodes/350-rest-api-versioning
If you'd like to easily follow along executing code along with the video check out the ascii cast so you may copy and paste as you watch.
http://railscasts.com/episodes/350-rest-api-versioning?view=asciicast
You may want to have rvm installed and use the gem bundler. create new gemset for each project. This will save you hassle with different versions of ruby and gems required for different projects.
Here is another answer: I think that learning Ruby without Rails first is a good idea. _why's Poignant Guide to Ruby is good for people coming from Objective-C because it doesn't go through how objects send "messages" to each other and all that stuff. After that, you should be able to use the Rails Guides to learn Rails. There are tutorials there. I don't know of any learning material that you have to pay for (like books), though. If that is what you want, I would try searching on Amazon.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.