text
stringlengths 175
47.7k
| meta
dict |
---|---|
Q:
How to avoid anti-clockwise rotation animation when reseting rotation from 360deg to 0 deg?
I am creating an animation that looks like a fancy wheel, When resetting rotation from 360deg to 0 deg, It animating the wheel in anti-clockwise direction, How to Avoid this???
HTML
<ul class="cm">
<li><span>01</span></li>
<li><span>02</span></li>
<li><span>03</span></li>
<li><span>04</span></li>
<li><span>05</span></li>
<li><span>06</span></li>
<li><span>07</span></li>
<li><span>08</span></li>
</ul>
SCSS
$Brdr: #7d868c;
*{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
&:before,&:after{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
}
%notaList{
margin: 0;
padding: 0;
list-style: none;
}
$node: 8;
$s: 80px;
$rotation: 0;
.cm{
top: 50%;
left: 0;
right: 0;
width: $s;
height: $s;
margin: auto;
display: block;
position: absolute;
transition: transform 0.8s ease-out;
transform:rotate(#{$rotation}deg);
@extend %notaList;
background: rgba(#000, 0.5);
border-radius: 50%;
li{
left: 0;
top:-($s*2 - ($s/2));
color:#333;
width:90%;
height: 90%;
display: block;
position: absolute;
margin-bottom: ($s*2 - ($s/2));
& > span{
display: block;
padding: 36%;
text-align: center;
overflow: hidden;
background: #CCC;
border-radius: 5px 5px 50% 50%;
transition: transform 0.8s ease-out;
}
@for $i from 1 through $node{
&:nth-child(#{$i}n) {
transform-origin: 50% ($s*2);
transform: rotate(($i - 1) * 360deg/$node);
& > span {
transform:rotate(($rotation * -1) - (($i - 1) * 360deg/$node));
}
}
}
}
}
JQuery
var i = 1,
nodes = 8;
setInterval(function(){
var rotation = i * 360 / nodes;
i = i + 1;
$('.cm').css({
'transform': 'rotate(' + rotation + 'deg)'
}).attr('data-rotation', rotation);
$('.cm li').each(function (node){
r = (node) * 360/nodes;
$($('.cm li')[node]).find('span').css({
'transform': 'rotate(' + ((rotation*-1) - r) + 'deg)'
});
});
if(i >= nodes){
i = 0;
}
}, 1000);
JsFiddle link:
https://jsfiddle.net/aspjsplayground/hqczLby7/
A:
I've edited your jsfiddle so that it does not animate the rotation when reseting to 0.
When doing this it's helpful to use window.requestAnimationFrame since modifying transition isn't instant.
https://jsfiddle.net/hqczLby7/8/
| {
"pile_set_name": "StackExchange"
} |
Q:
ReCAPTCHA v3 is not working in a Shopify Contact form, how can I solve it?
Yesterday I added Google ReCAPTCHA v3 in one of my client's Shopify website, but I don't think that it is working because he is still reporting to receive several spam e-mails.
I've followed Google's guide, but I don't know what to do for "Verifying user response" part of the guide. I'm not an expert in coding.
Basically I've added this code to the theme.liquid file
<script src="https://www.google.com/recaptcha/api.js?render=*site key provided by google*"></script>
And then I've added this part in the page.contact.liquid file:
<script> grecaptcha.ready(function() {
grecaptcha.execute('*site key provided by google*', {action: 'contact'}).then(function(token) {
...
}); }); </script>
Have I missed out something? Can someone help me to fix this issue please?
A:
Unfortunately, any attempt to implement reCaptcha on a native Shopify contact form will not work. It may appear to work, as in the form submits and you see the stats in the reCaptcha admin, but it won't actually be blocking any spam. The reason is that you can only implement the client-side piece in your theme, and in order to work, you must have both the client and server-side pieces in place and working. The server-side piece is what detects a failed captcha (i.e., a spam bot) and prevents the form from being submitted.
Implementing just the client-side piece might block some of the most unsophisticated spam bots that just see the captcha and stop, but it's trivial to design a bot to bypass the client-side piece: that's why the server-side piece is essential.
Also posted this answer on the Shopify forum thread linked by Chami, as people there are going in circles thinking it's possible or thinking it's working when it's not.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get URL segment in Laravel 5
For accessing previous URL in laravel. I am using this code in my controller.
$current_url = Request::url();
$back_url = redirect()->back()->getTargetUrl();
if ($current_url != $back_url) {
Session::put('previous_url', redirect()->back()->getTargetUrl());
}
This method helps maintainging previous url even when server side validation fails.
In my blade I access previous url like this {{ Session::get('previous_url') }}.
I need to find the second segment of my previous url.
Thanks
A:
You can do it this way:
request()->segment(2);
request() is a helper function that returns Illuminate\Http\Request, but you can also use the facade Request or inject the class as a dependency in your method.
EDIT
with the redirect back: redirect()->back()->getRequest()->segment(2);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change jump time in totem media player?
How to change jump time in totem media player? It's by default 60 sec jump forward and 15 sec jump back.
A:
shift, Right Arrow: forward 15 seconds
shift, left arrow: back for 5 seconds
| {
"pile_set_name": "StackExchange"
} |
Q:
store wget link into a database (php)
I'm trying to find a solution to download automatically .flv link everyday from a website using wget and to store all the links into a database to stream them in my website. (all in php)
How to do that? I don't need to store the files only links into the database.
Best regards,
A:
I don't know why you would need wget.
You could use curl to go to the website and get the new link. After you have the link, just store the information in the database and your done.
You are basically scrapping other sites for content.
This article looks like it is promising:
http://www.merchantos.com/makebeta/php/scraping-links-with-php/
You could also try to search google. I used the term:
scrapping site php curl
Have fun.
Regards.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algorithm for creating fisheye effect from a normal image
I am trying to create an OpenGL fragment shader that converts a normal image to an image that contains fish eye effect. This is what i mean by fish eye affect (http://www.marcofolio.net/photoshop/create_a_fish_eye_lens_effect_in_photoshop.html).
By normal image i mean a rendered image taken from a virtual camera in a 3d interactive environment, not an image taken from a real camera, but i guess that doesnt really make much difference in terms of this problem.
Does anyone have any idea how Photoshop does it, or where i can find material that explains the algorithm?
Thanks
A:
You don't really even need a shader in this case. From the sound of things, you have your original image as a bitmap of some sort. If that's so, just use it as a texture, and attach it to a sphere.
Of course, you can use a shader (or pair of shaders, really), but unless you're going to do more than you've described, doing so won't gain you much (if anything).
| {
"pile_set_name": "StackExchange"
} |
Q:
Ruby instance variable
class Polygon
attr_accessor :sides
@sides = 10
end
When I try to access
puts Polygon.new.sides # => nil
I get nil. How to access sides?
What is wrong here?
A:
Since ruby class definitions are just executable code, when you say @sides = 10 in the context of a class definition, you're defining that on Polygon (not instances of Polygon):
class Polygon
attr_accessor :sides
@sides = 10
end
Polygon.instance_variables
# => [:@sides]
You probably want to set the number of sides on the instances of Polygon, from the initializer:
class Polygon
attr_accessor :sides
def initialize(sides)
@sides = sides
end
end
Polygon.new(10).sides
# => 10
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make an anonymous types property name dynamic?
I have a following LinqToXml query:
var linqDoc = XDocument.Parse(xml);
var result = linqDoc.Descendants()
.GroupBy(elem => elem.Name)
.Select(group => new
{
TagName = group.Key.ToString(),
Values = group.Attributes("Id")
.Select(attr => attr.Value).ToList()
});
Is it possible somehow to make the field of my anonymous type it to be the variable value, so that it could be as (not working):
var linqDoc = XDocument.Parse(xml);
var result = linqDoc.Descendants()
.GroupBy(elem => elem.Name)
.Select(group => new
{
group.Key.ToString() = group.Attributes("Id")
.Select(attr => attr.Value).ToList()
});
A:
No, even anonymous types must have compile-time field names. It seems like to want a collection of different types, each with different field names. Maybe you could use a Dictionary instead?
var result = linqDoc.Descendants()
.GroupBy(elem => elem.Name)
.ToDictionary(
g => g.Key.ToString(),
g => g.Attributes("Id").Select(attr => attr.Value).ToList()
);
Note that Dictionaries can be serialized to JSON easily:
{
"key1": "type1":
{
"prop1a":"value1a",
"prop1b":"value1b"
},
"key2": "type2":
{
"prop2a":"value2a",
"prop2b":"value2b"
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Associative Array Looping in Twig
How can i loop this array in Twig ?
what im doing wrong ?
here is what i have
<?php foreach (array('price','weight','length','width','height','points') as $mod) { ?>
<label class="col-sm-2 control-label" for="input-<?php echo $mod . $option_row; ?>"><?php echo ${'text_option_'.$mod}; ?></label>
<select name="product_option[<?php echo $option_row; ?>][value][<?php echo $mod; ?>_prefix]" class="form-control">
<option value=""<?php if (isset($product_option['value'][$mod.'_prefix']) && $product_option['value'][$mod.'_prefix'] == '') echo ' selected'; ?>>NONE</option>
<option value="+"<?php if (isset($product_option['value'][$mod.'_prefix']) && $product_option['value'][$mod.'_prefix'] == '+') echo ' selected'; ?>>+</option>
</select>
here is what i done but isnt work
{% for price, weight, length, width, height, points in mod %}
<label class="col-sm-2 control-label" for="input-{{ mod . option_row}}">{{ text_option_ . mod}}</label>
<select name="product_option[{{ option_row }}][value][{{ mod }}_prefix]" class="form-control">
<option value=""{% if product_option['value'][mod.'_prefix'] is defined and product_option['value'][mod.'_prefix'] == '' %} {% endif %} {{'selected'}}; >NONE</option>
<option value=""{% if product_option['value'][mod.'_prefix'] is defined and product_option['value'][mod.'_prefix'] == '+' %} {% endif %} {{'selected'}}; >+</option>
</select>
{% endfor %}
A:
You are building your array wrong. Also it's {% for needle in haystack %} in twig... So your first line should become:
{% for mod in [ 'price','weight','length','width','height','points' ] %}
| {
"pile_set_name": "StackExchange"
} |
Q:
What will be the interval of convergence $\sum_{n=1}^{\infty} \frac{n! x^n}{2^{n^{2}}}$
$\displaystyle \sum_{n=1}^{\infty} \frac{n! x^n}{2^{n^{2}}}$ My main problem is how can I handle the denominator ${2^{n^{2}}}$? I used until know the ratio test, as I saw a factorial, but it the denominator makes it a little bit difficult.
A:
With Hadamard's formula: the radius of convergence $R$ of $\sum a_n z^n$ is given by
$$\frac1R=\limsup\Bigl(\lvert a_n\rvert^{\tfrac1n}\Bigr).$$
$$\text{Now}\hspace{10em}0\le\biggl(\frac{n!}{2^{n^2}}\biggr)^{\tfrac1n}\le\biggl(\frac{n^n}{2^{n^2}}\biggr)^{\tfrac1n}=\frac n{2^n}\to 0\hspace{11em},$$
so $R=\infty$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bitmap from byte[] array
I want to create a bitmap from a byte[]. My problem is that I can't use a BitmapSource in Unity and if I use a MemoryStream Unity gets an error.
I tried it with this:
Bitmap bitmap = new Bitmap(512, 424);
var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size),
ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Marshal.Copy(arrayData, 0, data.Scan0, arrayData.Length);
bitmap.UnlockBits(data);
It works but the Bitmap I get is the wrong way up. Can someone explain me why and got a solution for me?
A:
This can be two things, perhaps combined: The choice of coordinate system, and Endianness
There's a convention (I believe universal) to list pixels from left to right, but there's none regarding vertical orientation. While some programs and APIs have the Y-coordinate be zero at the bottom and increases upwards, others do the exact opposite. I don't know where you get the byte[] from, but some APIs allow you to configure the pixel orientation when writing, reading or using textures. Otherwise, you'll have to manually re-arrange the rows.
The same applies to endianness; ARGB sometimes means Blue is the last byte, sometimes the first.Some classes, like BitConverter have buit-in solutions too.
Unity uses big-endian, bottom-up textures. In fact, Unity handles lots of this stuff under the hood, and has to re-order rows and flip bytes when importing bitmap files. Unity also provides methods like LoadImage and EncodeToPNG that take care of both problems.
To illustrate what happens to the byte[], this sample code saves the same image in three different ways (but you need to import them as Truecolor to see them properly in Unity):
using UnityEngine;
using UnityEditor;
using System.Drawing;
using System.Drawing.Imaging;
public class CreateTexture2D : MonoBehaviour {
public void Start () {
int texWidth = 4, texHeight = 4;
// Raw 4x4 bitmap data, in bottom-up big-endian ARGB byte order. It's transparent black for the most part.
byte[] rawBitmap = new byte[] {
// Red corner (bottom-left) is written first
255,255,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
255,0,0,255, 255,0,0,255, 255,0,0,255, 255,0,0,255
//Blue border (top) is the last "row" of the array
};
// We create a Texture2D from the rawBitmap
Texture2D texture = new Texture2D(texWidth, texHeight, TextureFormat.ARGB32, false);
texture.LoadRawTextureData(rawBitmap);
texture.Apply();
// 1.- We save it directly as a Unity asset (btw, this is useful if you only use it inside Unity)
UnityEditor.AssetDatabase.CreateAsset(texture, "Assets/TextureAsset.asset");
// 2.- We save the texture to a file, but letting Unity handle formatting
byte[] textureAsPNG = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/EncodedByUnity.png", textureAsPNG);
// 3.- Rearrange the rawBitmap manually into a top-down small-endian ARGB byte order. Then write to a Bitmap, and save to disk.
// Bonus: This permutation is it's own inverse, so it works both ways.
byte[] rearrangedBM = new byte[rawBitmap.Length];
for (int row = 0; row < texHeight; row++)
for (int col = 0; col < texWidth; col++)
for (int i = 0; i < 4; i++)
rearrangedBM[row * 4 * texWidth + 4 * col + i] = rawBitmap[(texHeight - 1 - row) * 4 * texWidth + 4 * col + (3 - i)];
Bitmap bitmap = new Bitmap(texWidth, texHeight, PixelFormat.Format32bppArgb);
var data = bitmap.LockBits(new Rectangle(0, 0, texWidth, texHeight), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
System.Runtime.InteropServices.Marshal.Copy(rearrangedBM, 0, data.Scan0, rearrangedBM.Length);
bitmap.UnlockBits(data);
bitmap.Save(Application.dataPath + "/SavedBitmap.png", ImageFormat.Png);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Meaning and Usage of 'Раз уж'
I translated a sentence of mine into Russian, which originally read: "I want to hear all about your news and what took place today! Once I have my coffee, of course."
Here is my translation: "Я хочу услышать все о твоих новостях и сегодняшних происшествиях! Раз уж у меня есть кофе."
At first, I translated the last sentence quite directly as 'Раз у меня есть кофе,' but was changed to 'раз уж...' Could you provide a brief explanation of 'раз уж' (though I can intuit from context, I want to be sure) and an example or two of how it is used?
A:
"Раз уж у меня есть кофе" translates into something like "...since I already have my coffee", or, to put it another way, "Now that I have got my coffee [I'm ready to listen to you]" -- it implies that you have a cup of coffee in your hand and are ready to listen.
There is not much difference here between "раз" and "раз уж" -- the particle "уж" (reduced "уже") simply reinforces completeness of what follows ("у меня есть чашка кофе").
Your English phrase sounds more like you haven't had your coffee yet and are not ready to listen until you have, so it would be better translated as "Расскажи мне, что у тебя нового и что происходило сегодня, но только после того, как я выпью кофе, конечно".
| {
"pile_set_name": "StackExchange"
} |
Q:
Select the field that ever fulfil condition
Employee Table
NameId Name
1 Andy
2 Peter
3 Jason
4 Thomas
5 Clark
Employee - Supervisor Relations
NameId SupervisorId (Refer to employee Id)
1 4
1 2
2 3
5 4
How can i select query to return search with all name that supervisor 'once' to be Thomas. So the result i want is like this.
Name Supervisor
Andy Thomas
Andy Peter (Is valid because Andy supervisor contains 'Thomas')
Clark Thomas
A:
It looks the table relation doesn't need another optional table, so the query would be more simple:
select emp.name as Name, spv.name as Supervisor
from employee emp
inner join employee spv
on emp.spv_id = spv.id
where spv.name like 'Thomas'
order by emp.name
| {
"pile_set_name": "StackExchange"
} |
Q:
SSH Permission denied for Mininet
I am new to SDN and was trying to learn Mininet. I have installed debian(64-bit) and Mininet on Virtual Box. When I try to connect Mininet Vm from Debian I have to run the following comamnd :
ssh -X mininet@10.0.2.15
It asks for mininet password, but after entering the default mininet password it shows an error
Permission denied please try again
Both my debian and Mininet VM have same IP address. Kindly guide how to eliminate the SSHerror. Also is it fine having same ip address for two different VM, is the SSH error a result of this ?
Thanks
A:
In the VirtualBox settings under the tab Network click on Advanced then Port Forwarding and add a rule with name: ssh, protocol: tcp, host port: 3022 and guest port: 22. Then execute:
sudo ssh -p 3022 mininet@10.0.2.15
| {
"pile_set_name": "StackExchange"
} |
Q:
Summing up digits of a very long binary number?
I was asked by a friend :
If 2^10 = 1024 , we can take 1024 and break and summarize its digits :
1+0+2+4 = 7.
This is easy.
However When the input is 2^30000 ( the input actually is a long string "1000...") --there is no .net type which can hold this value .
So there must be a trick to sum its digits (digits of the decimal value)....
Edited :
Related trick ( for finding 10^20 - 16)
100 = 10^2 (one and two zeros)
10^20 = (one and 20 zeros)
hence:
10^20 - 16 = 18 nines, an eight and four.
18*9+8+4 = 174
But I haven't succeeded converting this solution to my problem.( I tried quite a lot).
*Im tagging this question as .net because I can use string functions , math functions from .net library.*
Question
Is there any trick here which can allow me to sum many many numbers which is the result of x^n ?
What is the trick here ?
Edited #2 : Added the .net2 tag (where biginteger is unavailable) - I'm wondering how I could do it without biginteger.(i'm looking for the hidden trick)
A:
You can leverage the BigInteger structure to do this. As it's written in MSDN
The BigInteger type is an immutable type that represents an
arbitrarily large integer whose value in theory has no upper or lower
bounds.
Basically after creating BigInteger instance and evaluating exponent you can translate it to a string. After that you will iterate over each character of that string and convert each char to int number. Add all those int numbers up and you'll get your answer.
BigInteger bi = new BigInteger(2);
var bi2 = BigInteger.Pow(bi, 30000);
BigInteger sum = new BigInteger();
foreach(var ch in bi2.ToString())
sum = BigInteger.Add(sum, new BigInteger(int.Parse(ch.ToString())));
MessageBox.Show(bi2.ToString() + " - " + sum.ToString());
A:
There is no general trick I'm aware of for finding the base 10 digit sum of a number.
However, there is an easy trick for finding the base 10 digit root of a number.
The digit sum is, as you say, simply the sum of all the digits. The base 10 digit sum of 1024 is 1 + 2 + 4 = 7. The base 10 digit sum of 65536 is 6 + 5 + 5 + 3 + 6 = 25.
The digit root is what you get when you repeat the digit sum until there's only one digit. The digit sum of 65536 is 25, so the digit root is 2 + 5 = 7.
The trick is: If you have Z = X * Y then DigitRoot(Z) = DigitRoot(DigitRoot(X) * DigitRoot(Y)). (Exercise to the reader: prove it! Hint: start by proving the same identity for addition.)
If you have an easily-factored number - and the easiest number to factor is 2n -- then it is easy to figure out the digit root recursively: 216 = 28 * 28, so DigitRoot(216) = DigitRoot(DigitRoot(28) * DigitRoot(28)) -- We just made the problem much smaller. Now we don't have to calculate 216, we only have to calculate 28. You can of course use this trick with 230000 -- break it down to DigitRoot(DigitRoot(215000 * DigitRoot(215000)). If 215000 is too big, break it down further; keep breaking it down until you have a problem small enough to solve.
Make sense?
A:
From http://blog.singhanuvrat.com/problems/sum-of-digits-in-ab:
public class Problem_16 {
public long sumOfDigits(int base, int exp) {
int numberOfDigits = (int) Math.ceil(exp * Math.log10(base));
int[] digits = new int[numberOfDigits];
digits[0] = base;
int currentExp = 1;
while (currentExp < exp) {
currentExp++;
int carry = 0;
for (int i = 0; i < digits.length; i++) {
int num = base * digits[i] + carry;
digits[i] = num % 10;
carry = num / 10;
}
}
long sum = 0;
for (int digit : digits)
sum += digit;
return sum;
}
public static void main(String[] args) {
int base = 2;
int exp = 3000;
System.out.println(new Problem_16().sumOfDigits(base, exp));
}
}
c#
public class Problem_16 {
public long sumOfDigits(int base1, int exp) {
int numberOfDigits = (int) Math.Ceiling(exp * Math.Log10(base1));
int[] digits = new int[numberOfDigits];
digits[0] = base1;
int currentExp = 1;
while (currentExp < exp) {
currentExp++;
int carry = 0;
for (int i = 0; i < digits.Length; i++) {
int num = base1 * digits[i] + carry;
digits[i] = num % 10;
carry = num / 10;
}
}
long sum = 0;
foreach (int digit in digits)
sum += digit;
return sum;
}
}
void Main()
{
int base1 = 2;
int exp = 3000000;
Console.WriteLine (new Problem_16().sumOfDigits(base1, exp));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to manage data sharing in a little Intranet on Windows
I should set up a network for a little enterprise. The requirements can be summarized as follows:
All the "business" softwares have to be stored in a single computer (let's call it "the server"). The other computers (in this case there should be at most 2 or 3 computers) can execute these softwares through the server. So there are no local copies of those softwares on clients, only on the server.
The main computer (the server) shares also a printer.
All the computers in the network, are interconnected through a single wi-fi modem/router. Some of them are connected through the wi-fi interface and others through an ethernet cable.
Here is the most tedious problem with which I'm dealing: the server, in order to perform some special procedures, has to connect to a special modem which connects it to a remote private network. In order to do so, the server disconnects from the local enterprise network. In the meantime, clients are not able to execute softwares anymore and cannot print anything.
PAY ATTENTION: when the server is connected to the private network, it still needs to execute the "business" softwares.
So, my questions are:
Is it possible to keep the server connected to both the networks without denying the access to softwares, data and printers to anyone? If yes, how?
If not, how can I design the topology of the network in order to share softwares and other data among all the computers (server and clients)? It's important that when the server connects to the private network every computer (including the server itself) can still access softwares, data and printers.
I hope I was clear.
Thanks.
A:
You say that: in order to connect to the remote private special network, it has to disconnect from the local network. Then you say that you also need to keep it connected at all times so that all the clients can run software that lives only on the server.
By the terms you've defined, this is impossible. You need to split up these functions into two separate servers, or talk to the special private network people and find out what in their software requires the server to disconnect from the local network.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Laravel handle high traffic apps?
I am working on a PHP/MySQL social network project that will consist of many module/sections including:
user system (permissions, profiles, settings, etc...)
stackoverflow style badge and reputation point system
Wall/stream of friends posts
forums
message system
portfolio
blog
code snippets
bookmarks
and several other sections...
Originally I had planned to build everything using Laravel framework since it's simply awesome and also does a lot of the work already.
I am now questioning that though. I have not began any code yet so that is not a factor in the decision.
Also my time that it takes to build any part of the site/app does not out-weigh performance.
So if Laravel leads to less performance vs building from scratch but saves a ton of time. I would then prefer to spend a ton of extra time building from scratch if it means better performance and better long term.
Back around 2006 I built a social network hybrid of MySpace and Facebook and did not use a framework. It gave me 100% control of every aspect of everything and greater performance as I was able to really tweak and optimize everything as my network grew in size and traffic. I think you lose some of that low level optimizing capability when using a big framework?
My question could easily be mistaken as an opinion based question. To some extent it is however the core of it should be legit as far as which in theory would be the better route if performance is the priority over time to build.
I have only built low traffic app with a framework like Laravel so I have no experience building a high traffic app with a framework like Laravel so I do not know how well they perform compared to without a framework.
All my high traffic apps have been without a framework.
Based on the type of modules/sections I listed above. Can Laravel handle these type of apps on a high traffic and large scale level?
A:
This question is a little vague - for a start, what's your definition of high traffic?
Where I work we run a combination of hand built from the ground up code, and areas that are served by a laravel application (this is embedded in the main site and serves as much traffic as the rest of the old application code).
There's been no slowdown in the areas built with laravel at all (same database sources are used and it runs on the same web servers - so useful to benchmark on).
Caveats:
The original hand built code is older, and doesn't always take advantage of newer PHP methods / design types. This means that it's not as efficient as it could be. Then you have overhead with laravel doing things you might not always need/want to have going on.
Summing Up
What it comes down to is to mockup what you think would be the heaviest part of your application within laravel, and then again with custom ground up code. Then benchmark the crap out of it.
You'll more than likely find that (good) hand built work is going to be quicker. Is it worth those milliseconds? Well thats down to personal choice. Laravel is more than capable of handling large volumes of traffic, but sure, you might shave a small amount of time by not using it.
Just how important is that to what you're doing? If something is slowing it down and causing you problems within Laravel - change it. It's open source after all.
For reference (up to you if you count this as high traffic or not - I would):
This is a UK based SASS that generally serves UK based visitors. At 9pm tonight (Friday evening - actually one of our quietest times) we currently had around 250,000 active PHP sessions going on.
The system is served via 6 web servers [for redundancy, traffic loads etc] (load balanced) for the PHP application.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using while loop for nested if statements
Although I know I'm missing something, can't seem to get my head around a simple loop.
while (true){
if (n < 0)
System.out.print("less than 0")
else if (n > 35)
System.out.print("greater than 35")
else
calc(n)
}
I'm trying to use a while loop to loop the code and asks for input until the user inputs a value greater than 0 and less than 35, I have tried using continue but too no avail, thanks in advanceenter image description here
I have added sc of full code, the while loop will go after requesting input at the bottom of the code
A:
// if using jdk 1.7 or above else close scanner in finally block.
try (Scanner s = new Scanner(System.in)) {
int n;
while (true) {
n = s.nextInt();
if (n < 0) {
// ask for value greater then 0
System.out.print("Please enter a value greater then 0 ");
// extra print statement so input will be printed on next line after message
System.out.println();
} else if (n > 35) {
// ask for value less then 35
System.out.print("Please enter a value less then 35");
System.out.println();
} else {
// process input and break if correct input has received
calc(n);
break;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Making bootstrap navbar sticky only when navbar-collapse show
I want to make my navbar into a fixed position only if the collapsed menu is shown. It seems I can only make it permanently fixed regardless of the collapse function trigger, which is not what I want.
This is what I have
<nav class="navbar navbar-expand-lg navbar-light bg-white align-items-stretch">
<a href="{{ url('/') }}" class="navbar-brand">
<img class="navbar-logo img-fluid" src="{{ asset('img/generic.png') }}">
</a>
<button class="navbar-toggler collapsed" data-toggle="collapse" data-target="#navbar_collapse" aria-expanded="false">
<span class="navbar-toggler-icon "></span>
</button>
<div class="navbar-collapse collapse align-items-stretch bg-white" id="navbar_collapse">
<!--collapse menu code-->
</div>
</nav>
and in my css file to specify the navbar only on device version
@media (max-width: 992px) {
.navbar-fix {
position: fixed;
top: 0;
right: 0;
left: 0;
z-index: 10;
}
}
and my script
$( document ).ready(function() {
$('.navbar').click(function(){
$('.navbar.navbar-fixed').removeClass('navbar-fixed');
$(this).addClass('navbar-fixed');
console.log( "nav fix" );
});
});
Which doesn't load it back to relative position when the collapse is hidden. And how can I specify so it's only fixed when I click on the toggler?
A:
It's a little difficult to discern exactly what you are asking, but I'll give it a shot.
So, when you say...
I want to make my navbar into a fixed position only if the collapsed menu is shown. It seems I can only make it permanently fixed regardless of the collapse function trigger.
It seems as though you are having difficulty changing the navbar position attribute at the lg(992px) breakpoint. Without more content on the page, it's difficult to determine what's actually happening upon hitting the breakpoint. So, I inserted your snippet into my IDE, added some filler text and played around with Chrome's dev tools to see what was happening.
Let's breakdown the components at work here...
For navbar, the class "navbar-expand-lg" is saying to expand/show the navbar when the screen is 992px or more. So the collapsed version will display only when the size is less that 992px.
Now, your css snippet has a media query for the lg breakpoint(992px). Therefore, the styles inside @media codeblock will apply when the screen is 992px or less. Since the position attribute is being set to "fixed" inside this @media query, the navbar is being set to fixed when the screen is 992px or less.
Putting it all together, you
want to make my navbar into a fixed position only if the collapsed menu is shown.
Your collapsed menu is shown when screen size is less than 992px. Your @media query is setting the navbar to fixed when the screen size is less than 992px. What may fix your issue is setting the navbar position attribute specifically for when the screen is bigger than 992px.
If I didn't answer the right question, or if you were trying to remove the navbar completely except when collapsed is showing, look into the display setting to remove it at the lg breakpoint.
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing groovy closure or some pattern to take care of transactions
I want to write some type of closure or method template pattern in groovy that takes care of DB transactions in one place
What i want is some thing like this...
Pseudo code
def txMethod(codeOrSetStatementsToExecute){
//begin transaction
execute given - codeOrSetStatementsToExecute
//end transaction by commit or rollback
}
def createSomething(args){
txMethod({
-create1statement(args)
-create2statement
});
}
def deleteSomething(){
txMethod({
-delete1statement()
-doSomethingElse
});
}
A:
I've written something akin to that using JPA, sometime ago. IIRC, it turned into something like this:
class DB<T> {
void save(T t) {
transactional {
em.persist(t)
em.flush()
}
}
void delete(T t) {
transactional {
em.remove(t)
}
}
void update(T t) {
transactional {
em.merge(t)
em.flush()
}
}
protected UserTransaction getTransaction() {
// get transaction from JPA/Context/Younameit
}
protected void transactional(Closure<?> closure) {
def utx = getTransaction();
try {
utx.begin();
closure.call();
em.flush();
} catch (Throwable t) {
utx.setRollbackOnly()
throw t;
} finally {
utx.commit();
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract array from JSON using sed and regex
I'm trying to write a script for comissioning embedded devices, they retrieve a JSON object from an API that contains an array of scripts that must be run to comission the device.
{
"status":"wait",
"settings":{
"serialNo": "123456",
"macAddress":"ff:ff:ff:ff:ff:ff",
"ipMode": "static|dhcp",
"ipAddress": "192.168.0.1",
"ipSubnet": "255.255.255.0",
"ipGateway": "192.168.0.10",
"ipDns": "192.168.0.10"
},
"scripts":[
"https://www.google.co.uk/1",
"https://www.google.co.uk/2",
"https://www.google.co.uk/3"
]
}
As the devices run minimal linux installs with busybox I am using sed to "parse" the JSON and retrieve the values from the object. This works fine for single parameters such as
mac=$(echo $reply | sed -ne 's/^.*"macAddress":"\([^"]*\)".*$/\1/p')
echo $mac
ff:ff:ff:ff:ff:ff
I try to use a similar regex to match the contents of the array between [ and ] but when I run it through sed it returns with nothing.
scripts=$(echo $reply | sed -ne 's/"scripts":\(\[[^\[\]]*\]\)/\1/p')
echo $scripts
What I would like it to result in is this:
echo $scripts
["https://www.google.co.uk/1","https://www.google.co.uk/2","https://www.google.co.uk/3"]
A:
With jq you can issue the following command:
jq -r '.scripts[]' the.json
If you want to put this into an array, use command substitution:
arr=( $(jq -r '.scripts[]' a.json ) )
Now you can access the individual urls using:
echo "${arr[0]}"
echo "${arr[1]}"
echo "${arr[2]}"
| {
"pile_set_name": "StackExchange"
} |
Q:
convert SAS date format to R
I read in a sas7bdat file using the haven package.
One column has dates in the YYQ6. format.
I R this is converted to numbers like -5844, 0, 7121, ..
How can I convert this to a year format? I have no access to SAS but these values should be birth dates.
A:
Bit of Research first. SAS uses as Zero 1st of January 1960 (see http://support.sas.com/publishing/pubcat/chaps/59411.pdf) so if you want the year of the data (represented by your number) it should be
format(as.Date(-5844, origin="1960-01-01"),"%Y")
and you get in this case
1944
is that correct? is what you are expecting?
To learn more on the data type YYQ6. check this Support article from SAS
http://support.sas.com/documentation/cdl/en/leforinforref/64790/HTML/default/viewer.htm#n02xxe6d9bgflsn18ee7qaachzaw.htm
Let me know if is working.
Umberto
| {
"pile_set_name": "StackExchange"
} |
Q:
Image generator missing positional argument for unet keras
I keep getting the following error for below code when I try to train the model: TypeError: fit_generator() missing 1 required positional argument: 'generator'. For the life of me I can not figure out what is causing this error. x_train is an rgb image of shape (400, 256, 256, 3) and for y_train i have 10 output classes making it shape (400, 256, 256, 10). What is going wrong here?
If necessary the data can be downloaded with the following link:
https://www49.zippyshare.com/v/5pR3GPv3/file.html
import skimage
from skimage.io import imread, imshow, imread_collection, concatenate_images
from skimage.transform import resize
from skimage.morphology import label
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as K
from sklearn.metrics import jaccard_similarity_score
from shapely.geometry import MultiPolygon, Polygon
import shapely.wkt
import shapely.affinity
from collections import defaultdict
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras import utils as np_utils
import os
from keras.preprocessing.image import ImageDataGenerator
gen = ImageDataGenerator()
#Importing image and labels
labels = skimage.io.imread("ede_subset_293_wegen.tif")
images = skimage.io.imread("ede_subset_293_20180502_planetscope.tif")[...,:-1]
#scaling image
img_scaled = images / images.max()
#Make non-roads 0
labels[labels == 15] = 0
#Resizing image and mask and labels
img_scaled_resized = img_scaled[:6400, :6400 ]
print(img_scaled_resized.shape)
labels_resized = labels[:6400, :6400]
print(labels_resized.shape)
#splitting images
split_img = [
np.split(array, 25, axis=0)
for array in np.split(img_scaled_resized, 25, axis=1)
]
split_img[-1][-1].shape
#splitting labels
split_labels = [
np.split(array, 25, axis=0)
for array in np.split(labels_resized, 25, axis=1)
]
#Convert to np.array
split_labels = np.array(split_labels)
split_img = np.array(split_img)
train_images = np.reshape(split_img, (625, 256, 256, 3))
train_labels = np.reshape(split_labels, (625, 256, 256, 10))
train_labels = np_utils.to_categorical(train_labels, 10)
#Create train test and val
x_train = train_images[:400,:,:,:]
x_val = train_images[400:500,:,:,:]
x_test = train_images[500:625,:,:,:]
y_train = train_labels[:400,:,:]
y_val = train_labels[400:500,:,:]
y_test = train_labels[500:625,:,:]
# Create image generator (credit to Ioannis Nasios)
data_gen_args = dict(rotation_range=5,
width_shift_range=0.1,
height_shift_range=0.1,
validation_split=0.2)
image_datagen = ImageDataGenerator(**data_gen_args)
seed = 1
batch_size = 100
def XYaugmentGenerator(X1, y, seed, batch_size):
genX1 = gen.flow(X1, y, batch_size=batch_size, seed=seed)
genX2 = gen.flow(y, X1, batch_size=batch_size, seed=seed)
while True:
X1i = genX1.next()
X2i = genX2.next()
yield X1i[0], X2i[0]
# Train model
Model.fit_generator(XYaugmentGenerator(x_train, y_train, seed, batch_size), steps_per_epoch=np.ceil(float(len(x_train)) / float(batch_size)),
validation_data = XYaugmentGenerator(x_val, y_val,seed, batch_size),
validation_steps = np.ceil(float(len(x_val)) / float(batch_size))
, shuffle=True, epochs=20)
A:
You have a few mistakes in your code, but considering your error:
TypeError: fit_generator() missing 1 required positional argument:
'generator'
this is caused because fit_generator call XYaugmentGenerator but no augmentation generator is called inside.
gen.flow(...
won't work because gen is not declared. You should either rename image_datagen to gen as:
gen = ImageDataGenerator(**data_gen_args)
or, replace gen with image_datagen
genX1 = image_datagen.flow(X1, y, batch_size=batch_size, seed=seed)
genX2 = image_datagen.flow(y, X1, batch_size=batch_size, seed=seed)
| {
"pile_set_name": "StackExchange"
} |
Q:
Read multiple lists from python into an SQL query
I have 3 lists of user id's and time ranges (different for each user id) for which I would like to extract data. I am querying an AWS redshift database through Python. Normally, with one list, I'd do something like this:
sql_query = "select userid from some_table where userid in {}".format(list_of_users)
where list of users is the list of user id's I want - say (1,2,3...)
This works fine, but now I need to somehow pass it along a triplet of (userid, lower time bound, upper time bound). So for example ((1,'2018-01-01','2018-01-14'),(2,'2018-12-23','2018-12-25'),...
I tried various versions of this basic query
sql_query = "select userid from some_table where userid in {} and date between {} and {}".format(list_of_users, list_of_dates_lower_bound, list_of_dates_upper_bound)
but no matter how I structure the lists in format(), it doesn't work. I am not sure this is even possible this way or if I should just loop over my lists and call the query repeatedly for each triplet?
A:
suppose the list of values are something like following:
list_of_users = [1,2],
list_of_dates_lower_bound = ['2018-01-01', '2018-12-23']
list_of_dates_lower_bound = ['2018-01-14', '2018-12-25']
the formatted sql would be:
select userid from some_table where userid in [1,2] and date between ['2018-01-01', '2018-12-23'] and ['2018-01-14', '2018-12-25']
This result should not be what you thought as is, it's just an invalid sql, the operand of between should be scalar value.
I suggest loop over the lists, and pass a single value to the placeholder.
| {
"pile_set_name": "StackExchange"
} |
Q:
In an ItemControl binding to property doesent work but binding to DataContext does
when I run this code the Item-object in my CustomControl becomes a System.Windows.Data.Binding containing nothing but null values but the DataContext becomes an MyClass object (which Items is populated with)
<UserControl x:Name="thisControl">
<Grid x:Name="LayoutRoot">
<ItemsControl ItemsSource="{Binding ElementName=thisControl,Path=Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<local:UniformGrid Columns="1"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:CustomControl Item="{Binding}" DataContext="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
My CustomControl class
public partial class CustomControl : UserControl
{
public CustomControl()
{
InitializeComponent();
}
public object Item { get; set; }
}
is there something i don't know about ItemsControl?
this is written in Silverlight 4.0
Thanks in advance!
A:
There is no need for you to be attempting to assign the custom control DataContext. The ItemsControl will take care of that for you.
Also your CustomControl code needs to specify the Item property as a DependencyProperty for the binding to work. Binding doesn't work on plain ordinary properties.
Example:
public object Item
{
get { return GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(
"Item",
typeof(object),
typeof(CustomControl),
new PropertyMetadata(null))
(I assume that RSListBoxStopItem is a typo and you meant to generalise to CustomControl)
| {
"pile_set_name": "StackExchange"
} |
Q:
Create file and directories at the same time
I am trying to create a blank file and its directories.
I have tried to use cd. > foo\bar.txt but it wont also make the directory.
Thank you.
A:
The only thing I can suggest is to mkdir first and then crate file, in fact it's 2 instructions but you can execute it in one line
mkdir test& cd. > test\test.txt
| {
"pile_set_name": "StackExchange"
} |
Q:
What am I missing here: $U(144) \neq U(140)$
I'm confused about the following exercise:
Prove that $U(144)$ is isomorphic to $U(140)$.
Here are my thoughts:
$$U(144) = U(12^2) = U(3^2)\oplus U(2^4) = \mathbb Z_{6} \oplus \mathbb Z_{8}$$
and
$$ U(140) = U(2^2 *7*5) = U(2^2) \oplus U(5) \oplus U(7) = \mathbb Z_{2} \oplus \mathbb Z_{4} \oplus \mathbb Z_{6}$$
And I have the following result:
$\mathbb Z_{n_1 \dots n_k}\cong \mathbb Z_{n_1}\oplus \dots \oplus \mathbb Z_{n_k}$ if and only if $n_i$ are pairwise coprime.
But $2$ and $4$ are not coprime therefore $\mathbb Z_{2} \oplus \mathbb Z_{4} \oplus \mathbb Z_{6}$ is not isomorphic to $\mathbb Z_{6} \oplus \mathbb Z_{8}$.
What am I doing wrong?
A:
Hint: $U(2^4)$ is not isomorphic to $\mathbb{Z}_8$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to assume the Probability function that will be used in Likelihood
We define Likelihood as follows:
$$ \mathcal{L}(\theta | X) = \prod P(x_{i}|\theta) $$
Question: How to assume the probability function $P$, specially in case of complex dataset?
I understand that if we are doing a Coin Toss, I can assume $P$ to be Bernoulli. But what if my dataset is complex (ex: financial data, flu cases) or I am working on some complex use case where I am using a Neural Network to classify images for example and then applying Bayesian inference for identifying the network weights $W$.
$$ P(W | D) \propto P(D | W) P(W)$$
where,
$$ P(W) = N(0, 1) $$
but how do we define / assume,
$$ P(D | W) = ?? $$
A:
I found a wonderful resource online that describes this question in much detail.
Bayesian Methods for Neural Networks: https://www.cs.cmu.edu/afs/cs/academic/class/15782-f06/slides/bayesian.pdf
Also, see chapter 10 of 'Neural Networks for Pattern Recognition' book by Bishop: http://cs.du.edu/~mitchell/mario_books/Neural_Networks_for_Pattern_Recognition_-_Christopher_Bishop.pdf#page=400
| {
"pile_set_name": "StackExchange"
} |
Q:
Data binding to a nested property with possibly null parent
I want to perform data-binding to Room.ToNorth.ImageName while ToNorth may be null.
I'm trying to write my own text adventure and have images next to each of the directions a player can go (ie. open/closed door, pathway). When there isn't a room in a given direction I have the controls bound to show a 'no exit' image, this works great so long the player starting location has an exit in all 4 directions, however when one is null I get the following exception
System.ArgumentNullException: 'Value cannot be null. Parameter name:
component'
This is isn't an issue on a new game but I'm making randomly generated dungeons so it can't be guaranteed on a load game. I realise I could probably fudge it by creating a safe space while the bindings are set then moving the player to where they need to be but is there a proper way to handle this?
The closest answer I've found is this question, but I'm not sure I can apply it here due to how it's bound.
private GameSession _CurrentGame;
private BindingSource _BindToPlayer = new BindingSource();
private void BtnNewGame_Click(object sender, EventArgs e)
{
_CurrentGame = new GameSession();
_BindToPlayer.DataSource = _CurrentGame.CurrentPlayer;
PicBoxNorth.DataBindings.Add("ImageLocation", _BindToPlayer,
"CurrentRoom.ToNorth.ImageName", true, DataSourceUpdateMode.OnPropertyChanged,
"Images\\Wall.png");
}
The ToNorth property just gets the object from an an array of exits, but telling it to return an empty exit if it's null (like suggested in the above link) would be problematic in that the exit wouldn't have any rooms to connect to and thus fail to initialise likely throwing an exception itself along the way. To explain better, I have my rooms set up as follows
public Class Room
{
public int ID { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public String FarDescription { get; set; }
public CoOrds Co_Ords { get; set; }
public Boolean UniqueRoom { get; set; }
public Exit[] ExitArr { get; set; }
public Exit ToNorth => ExitArr[0];
public Exit ToSouth => ExitArr[1];
public Exit ToWest => ExitArr[2];
public Exit ToEast => ExitArr[3];
public Exit ToUp => ExitArr[4];
public Exit ToDown => ExitArr[5];
public Exit ToIn => ExitArr[6];
public Exit ToOut => ExitArr[7];
public Room(int id, String name, String desc, String fardesc,bool unique = false)
{
ID = id;
Name = name;
Description = desc;
FarDescription = fardesc;
Co_Ords = new CoOrds();
ExitArr = new Exit[8];
UniqueRoom = unique;
}
And my exits are set up like so
public class Exit
{
public String Description {get;}
public Room RoomA { get; set; }
public Room RoomB { get; set; }
public Boolean CanExitA { get; set; } = true;
public Boolean CanExitB { get; set; } = true;
public Room NextRoom
{
get
{
if (RoomA.PlayerHere && CanExitA)
{ return RoomB; }
else if (RoomB.PlayerHere && CanExitB)
{ return RoomA; }
else
return null;
}
}
public String ImageName
{
get
{
string imagePath = "Images\\";
if (DoorHere != null)
{
return imagePath + DoorHere.ImageName;
}
else
return imagePath + "Pathway.png";
}
}
public Door DoorHere { get; set; }
public Exit(Room roomA, int Adir, Room roomB, int Bdir, Door door = null)
{
RoomA = roomA;
RoomA.ExitArr[Adir] = this;
RoomB = roomB;
RoomB.ExitArr[Bdir] = this;
DoorHere = door;
}
Door is just an unnamed object with a few bools for IsOpen, IsLocked etc. and shouldn't be needed if you want to test this but exits are created anonymously and add themselves to the Exit array in both connecting rooms, hence creating empty ones would fail.
Any suggestions would be greatly appreciated.
A:
As an option, you can create a property to do null-checking and get/set second level property using that property.
For example in your code, you can create ToNorthImageName property to get/set the value of ToNorth.ImageNamein Room class:
public string ToNorthImageName
{
get { return ToNorth?.ImageName }
//set { if (ToNorth != null) ToNorth.ImageName = value; }
}
The property setter is optional, you can remove it if you just want to read the image name.
Then setup data-binding to that property:
PicBoxNorth.DataBindings.Add("ImageLocation", _BindToPlayer, "ToNorthImageName",
true, DataSourceUpdateMode.OnPropertyChanged);
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically updated charts with Achartengine
I will like to have a chart in my application that the user can update when inserting data in an edit text. That is to say I want that when a user inserts data in the edit text and sent them with the send button the chart updates and shows the new data.
I tried inserting the new data into the arraylist in which data are saved and calling the repaint function but it doesn't work and I can't figure why.
This is my code.
Can someone help me, please?
public class ChartActivity extends Activity {
private GraphicalView mChartView;
XYMultipleSeriesRenderer renderer;
List<double[]> x= new ArrayList<double[]>();
List<double[]> values = new ArrayList<double[]>();
String[] titles = new String[] { "spens1" };
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.llayout);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout2);
x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
// }
values.add(new double[] { 9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13,
10 });
int[] colors = new int[] { Color.BLUE };
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE };
renderer = buildRenderer(colors, styles);
int length = renderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
((XYSeriesRenderer) renderer.getSeriesRendererAt(i))
.setFillPoints(true);
}
setChartSettings(renderer, "Ranges", "time",
"distance", 0.5, 12.5, -10, 40, Color.LTGRAY, Color.LTGRAY);
renderer.setXLabels(12);
renderer.setYLabels(10);
renderer.setShowGrid(true);
renderer.setXLabelsAlign(Align.RIGHT);
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setZoomButtonsVisible(true);
renderer.setPanLimits(new double[] { -10, 20, -10, 40 });
renderer.setZoomLimits(new double[] { -10, 20, -10, 40 });
if (mChartView == null) {
Log.d("Oncreate ", "if (mChartView == null)");
mChartView = ChartFactory.getLineChartView(this, mDataset(titles,
x, values), renderer);
layout.addView(mChartView, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
Log.d("Oncreate ", "if (mChartView != null)");
}
}
private final Handler mHandler = new Handler();
public void sendMessageChart(View view) {
mHandler.post(mUpdateUITimerTask);
}
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
EditText editText = (EditText) findViewById(R.id.edit_message_chart);
String message = editText.getText().toString();
double new_y = Double.parseDouble(message);
double[] x_val = new double[]{x.size()+1};
x.add(x.size()+1,x_val);
double[] y_val = new double[]{new_y};
values.add(values.size()+1,y_val);
mChartView = .repaint();
}
};
private void setChartSettings(XYMultipleSeriesRenderer renderer3,
String title, String xTitle, String yTitle, double xMin,
double xMax, double yMin, double yMax, int axesColor,
int labelsColor) {
// TODO Auto-generated method stub
renderer3.setChartTitle(title);
renderer3.setXTitle(xTitle);
renderer3.setYTitle(yTitle);
renderer3.setXAxisMin(xMin);
renderer3.setXAxisMax(xMax);
renderer3.setYAxisMin(yMin);
renderer3.setYAxisMax(yMax);
renderer3.setAxesColor(axesColor);
renderer3.setLabelsColor(labelsColor);
}
private XYMultipleSeriesRenderer buildRenderer(int[] colors,
PointStyle[] styles) {
// TODO Auto-generated method stub
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
setRenderer(renderer, colors, styles);
return renderer;
}
private void setRenderer(XYMultipleSeriesRenderer renderer2, int[] colors,
PointStyle[] styles) {
// TODO Auto-generated method stub
renderer2.setAxisTitleTextSize(16);
renderer2.setChartTitleTextSize(20);
renderer2.setLabelsTextSize(15);
renderer2.setLegendTextSize(15);
renderer2.setPointSize(5f);
renderer2.setMargins(new int[] { 20, 30, 15, 20 });
int length = colors.length;
for (int i = 0; i < length; i++) {
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(colors[i]);
r.setPointStyle(styles[i]);
renderer2.addSeriesRenderer(r);
}
}
private XYMultipleSeriesDataset mDataset(String[] titles,
List<double[]> xValues, List<double[]> yValues) {
// TODO Auto-generated method stub
XYMultipleSeriesDataset dataset1 = new XYMultipleSeriesDataset();
addXYSeries(dataset1, titles, xValues, yValues, 0);
return dataset1;
}
private void addXYSeries(XYMultipleSeriesDataset dataset, String[] titles,
List<double[]> xValues, List<double[]> yValues, int scale) {
// TODO Auto-generated method stub
int length = titles.length;
for (int i = 0; i < length; i++) {
XYSeries series = new XYSeries(titles[i], scale);
double[] xV = xValues.get(i);
double[] yV = yValues.get(i);
int seriesLength = xV.length;
for (int k = 0; k < seriesLength; k++) {
series.add(xV[k], yV[k]);
}
dataset.addSeries(series);
}
}
}
A:
The new data needs to be added to the XYSeries, not to a random ArrayList. See this code that does exactly what you need.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP object question
Excuse what is probably a really basic question but how do I achieve this.
$cache = New Mem;
$cache->event($event)->delete;
Which is called via the function below. Without the ->delete, it works perfectly fine, but I just need to find a way to call the delete thus inside the function.
class Mem
{
function event($event)
{
global $pdo;
global $memcached;
$key = md5(sha1($event) . sha1('events'));
if ($this->delete)
{
return $memcached->delete($key);
}
else
{
return $memcached->get($key);
}
}
}
I hope that makes sense, sorry for my pseudo code basically for the delete part.
A:
You're calling delete as if it were a method within your class - but you have no method called delete...Instead, you should evaluate the $event variable as I'm doing below and determine what action you'll take:
class Mem {
private $pdo;
private $memcached;
public function event($event) {
$key = md5(sha1($event) . sha1('events')); #from your original code
switch ($event) {
case "delete":
#do delete stuff
$this->memchached->delete($key);
break;
case "add":
#do add stuff
break;
}
}
}
Update: Following additional questions in comments...
class Event {
private $key;
public function __construct($key) {
$this->key = $key;
}
public function delete($key) {
# do delete
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
adding space between x axis and xtics in gnuplot histogram
Currently I created graphs with small size. The spacing really important at this case. I want to add more vertical space between my xticlabels and x axis.
I have tried to set the x bar with
set xtics offset 0,graph 0.05
my gnuplot output:
The data and gnuplot script still same with my previous question here.
A:
You can do the following:
First add a little bit of bmargin by
set bmargin 3
Since you need to add vertical space between your xticlabels and x-axis, you need to adjust the Y-offset, which can be done by the following
set xtics offset 0,-1,0
You can play around with the values to suite your need.
| {
"pile_set_name": "StackExchange"
} |
Q:
optimizing memory resources for a big query response
I have to perform a query that can generates a very big string in response (up to 1Gb), which is basically a big, big JSON array. Yes, pagination is in order but I'm stressing the concept in order to get you the idea.
Symfony simply uses doctrine to get the response:
$stmt = $this->getEntityManager()->getConnection()->prepare(self::Q_GET_NUM_TIMEBOX);
$stmt->bindValue('t_end', $tEnd);
$stmt->bindValue('t_granularity', $tGranularity);
$stmt->bindValue('t_span', $varSelection->getStart());
$stmt->execute();
$resData = $stmt->fetchColumn(0);
and then I create a Response by setting the content I had in return from the execute.
$res = new Response();
$res->setStatusCode(200);
$res->headers->set('Content-Type', 'application/json');
$res->setContent($resData);
Keep in mind I oversimplified the code for the sake of clarity: I actually have a controller, a handler service performing the request and a Repository returning the query response.
Back straight to the problem: this implies that PHP must hold that big amount of data in memory and I was wondering if there was an lighter way to return the response in order to stress less PHP engine with big amount of data.
A:
this implies that PHP must hold that big amount of data
PHP is not required to keep in the memory a whole response body. Through output buffers and Symfony response streaming you can fetch result set row-by-row and send a data by chunks. Unfortunately I don't known well-tried solution for JSON stream encoding in PHP, but you can implement it manually (1, 2).
Update (2017-02-27):
Streaming JSON Encoder is a PHP library that provides a set of classes to help with encoding JSON in a streaming manner, i.e. allowing you to encode the JSON document bit by bit rather than encoding the whole document at once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exchanging variables between 2 classes
Whenever I call the method Draw in Sprite, it won't draw it because X, Y, Width and Height are 0. :(
code:
class Sprite
{
protected int Y;// { get; set; }
protected int X;// { get; set; } { get; set; }
protected int Width;// { get; set; } { get; set; }
public int Height;// { get; set; } { get; set; }
protected Image image;// { get; set; } { get; set; }
public Sprite()
{
}
public void Draw(Graphics drawArea)
{
Image sImage = Image.FromFile("alien.jpg");
drawArea.Clear(Color.White);
drawArea.DrawImage(sImage, X, Y, Width, Height);
}
}
class User:Sprite
{
public User()
{
}
public User(int width, int height, int userWidth, int userHeight)
{
Sprite sprite = new Sprite();
Image UserImage = Image.FromFile("alien.jpg");
X = width;
Y = height;
Width = userWidth;
Height = userHeight;
image = UserImage;
}
}
ps: sprite.Draw is declared in another method in another class, but that all should work just fine.
Thanks for helping and probably saving me hours of time :)
Nick
EDIT
here is the subclass which gives the parameter and other stuff.
Alien mAlien;
User mUser;
protected int mLevel;
public gameLogic()
{
}
public gameLogic(int width, int height, int level)
{
mUser = new User(width / 2, height - 30, 30, 30);
mAlien = new Alien(width / 2, 5, 30, 30, "alien.jpg", 10 * level);
mLevel = level;
}
public void drawAll(Graphics drawArea)
{
Sprite sprite = new Sprite();
sprite.Draw(drawArea);
}
Im sorry for all these errors that'll probably occur, Im a new student :)
A:
Try this:
public User(int width, int height, int userWidth, int userHeight)
{
Sprite sprite = new Sprite();
Image UserImage = Image.FromFile("alien.jpg");
sprite.X = width;
sprite.Y = height;
sprite.Width = userWidth;
sprite.Height = userHeight;
sprite.image = UserImage;
}
In order to access the fields of the sprite, you have to specify which Sprite object you are modifying. This is done by writing the name of the variable followed by .
EDIT: Just realized that there is another problem - your User class is inheriting from the Sprite class. Apparently your users are sprites, according to the comments, so you'll want to never instantiate a Sprite, and just use the User class instead:
class User:Sprite
{
public User(int width, int height, int userWidth, int userHeight)
{
Image UserImage = Image.FromFile("alien.jpg");
X = width;
Y = height;
Width = userWidth;
Height = userHeight;
image = UserImage;
}
}
Then instead of calling draw on a sprite in the other file, use the following:
User user = new User(x, y, width, height)
...
user.draw();
The key here is to make sure you are using new User... and not new Sprite - even if you are assigning to a Sprite variable e.g. Sprite s = new User(...);.
Then just make sure you call draw on the same object - the user.draw line. If you want to check that you're doing it right, try making Sprite abstract - abstract class Sprite - that way there will be compile errors if you try to instantiate Sprite instead of User.
EDIT 2: Ok, all you really need to do is change your calling code:
public void drawAll(Graphics drawArea)
{
mUser.draw(drawArea);
mAlien.draw(drawArea);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop through input fields with jQuery to find the highest value?
I have a number of input[type=text] fields on my page and I want to loop through all of them in order to find and return the highest value.
Is there a way to do this with jQuery?
Thanks for any help.
A:
Here is one solution:
var highest = -Infinity;
$("input[type='text']").each(function() {
highest = Math.max(highest, parseFloat(this.value));
});
console.log(highest);
Here is another solution:
var highest = $("input[type='text']").map(function() {
return parseFloat(this.value);
}).get().sort().pop();
console.log(highest);
A:
Use Math.max function:
var nums = [];
$("input[type=text]").each( function() { nums.push( $(this).val() ); });
var max = Math.max.apply(Math, nums);
| {
"pile_set_name": "StackExchange"
} |
Q:
Does grails needed to run the application on tomcat?
I'm very new to web development.
I see people running grails app on tomcat, without grails being installed in that system! How this can be possible? How come tomcat can understand "grails" terminology and semantics?
Am I missing anything over here?
Thanks in advance.
A:
Everything the app needs is in the WAR file that you deploy, including the Grails JARs. Tomcat merely hosts the app. It doesn't need to know Grails terminology and semantics. By the time Tomcat knows about it, it's already been translated into the things it knows: HTTP, HTML, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Requesting the mentor regarding the PhD research topic selection
One of my friends is doing PhD under a good faculty from one year.
The mentor wants to give PhD only if the student writes two papers in SCI journals. The student wants to do his PhD on number theory conjectures. The mentor is saying that the PhD and groundbreaking research work are independent and hence the mentor saying my friend to work on small incremental work that will give papers quickly.
How to make it allowed to work under the same mentor (mentor is good enough and one year completed)?
A:
It is a mistake for most students (Ramanujan excepted) to go against his or her advisor. I'm sure that the advisors complete thoughts are more complex than you present here, but probably involve the risk of taking on a big project as a student and ending up with nothing - no results and no degree. Some problems are hard and take years-decades-centuries to resolve.
The advisor is giving good advice and following it will put him or her on the side of the student.
If "your friend" wants to take on the big project there is no problem, but will be working from a stronger position by finishing the doctorate first.
Take the advice. It is the faster path to success.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is relational parametricity?
A complicated-sounding term with no good explanations from a simple google search... are there any more academically-oriented folk who could explain this one?
A:
Both answers are mostly right. I would say that parametricity is a possible property of polymorphism. And polymorphism is parametric if polymorphic terms behave the same under all instantiations. To "behave the same" is a vague, intuitive term. Relational parametricity was introduced by John Reynolds as a mathematical formalization of this. It states that polymorphic terms preserve all relations, which intuitively forces it to behave the same:
Consider f: a list -> a list.
If we have the relation a~1, b~2, c~3, ..., then we can lift it to lists and hav e.g.
[a, d, b, c] ~ [1, 4, 2, 3]
Now, if f([a, d, b, c]) = [c, b, d, a] and f preserves relations,
then f([1, 4, 2, 3]) = [3, 2, 4, 1].
In other words, if f reverses list of strings, it also reverses lists of numbers.
So relationally parametric polymorphic functions cannot "inspect the type argument", in that they cannot alter their behaviour based on the type.
A:
Relational parametricity seems to be the property that a function abstracted over types (like a generic in Java) can have. If it has this property, it means it never inspects its type argument or deconstructs it / uses it in some special way. For example, the function "id or inc" here is not relationally parametric:
public class Hey<T>
{
public T idOrInc(T var)
{
if (var instanceof Integer)
return (T)(new Integer(((Integer)var).intValue()+1));
return var;
}
public static void main(String[] args) {
Hey<Integer> h = new Hey<Integer>();
System.out.println(h.idOrInc(new Integer(10)));
Hey<Double> h2 = new Hey<Double>();
System.out.println(h2.idOrInc(new Double(10)));
}
}
The output is:
$ java Hey
11
10.0
| {
"pile_set_name": "StackExchange"
} |
Q:
In *nix, how to determine which filesystem a particular file is on?
In a generic, modern unix environment (say, GNU/Linux, GNU/Solaris, or Mac OS X), is there a good way to determine which mountpoint and filesystem-type a particular absolute file path is on?
I suppose I could execute the mount command and manually parse the output of that and string-compare it with my file path, but before I do that I'm wondering if there's a more elegant way.
I'm developing a BASH script that makes use of extended attributes, and want to make it Do The Right Thing (to the small extent that it is possible) for a variety of filesystems and host environments.
A:
The command df(1) takes one or more arguments and will return the mountpoint and device on which that file or directory exists, as well as usage information. You can then use the path or device to look up the filesystem type in the output of mount -v or similar.
Unfortunately, the output format of both df and mount are system-dependent; there is no apparent standard, at least as I can see between Solaris, NetBSD and Mac OS X.
A:
You could use stat. The command stat --printf '%d' filename.txt will return the device number as hex/decimal.
A:
For just a specific file it's as easy as
df -T "${FILE}" | awk '{print $2}' | tail -n1
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the default font for Bless hex editor?
bless seems slightly better to me then ghex, but it has this ugly default font I can't stand.
My system monospaced font is set to Droid Sans Mono, size 9 and bless uses Courier New, size 12. It's too big and not preferred here, but can't find way to change it. Don't know if this is because it's mono developed, don't praise that either, but I searched in all folders where bless is "unpacked":
/usr/lib/bless
/usr/share/bless
and then:
~/.config/bless
There is no file where font is defined.
A:
Although font can't be set from editor, bless comes with extensive help system, where it is explained that, font tag can be used as child element in <display> tag in bless layouts configuration files (w/o example)
In action:
open /usr/share/bless/bless-default.layout
on every <area> element add <display> child element (if not defined) in which child element <font> can be set
<area type="ascii">
<display><font>Droid Sans Mono 9</font></display>
</area>
| {
"pile_set_name": "StackExchange"
} |
Q:
Create list of variable type
I am trying to create a list of a certain type.
I want to use the List notation but all I know is a "System.Type"
The type a have is variable. How can I create a list of a variable type?
I want something similar to this code.
public IList createListOfMyType(Type myType)
{
return new List<myType>();
}
A:
Something like this should work.
public IList createList(Type myType)
{
Type genericListType = typeof(List<>).MakeGenericType(myType);
return (IList)Activator.CreateInstance(genericListType);
}
A:
You could use Reflections, here is a sample:
Type mytype = typeof (int);
Type listGenericType = typeof (List<>);
Type list = listGenericType.MakeGenericType(mytype);
ConstructorInfo ci = list.GetConstructor(new Type[] {});
List<int> listInt = (List<int>)ci.Invoke(new object[] {});
| {
"pile_set_name": "StackExchange"
} |
Q:
If-Then-Else for my simple HTML form
I've set up a server, which sends the following form to a client and tries to receive the submitted information. How can I add a If-Else to it as simple as possible? I need to say if the "use tracefile" is enabled, then show the dropdown box, otherwise, show the customized inputs so that user can enter his/her numbers?
My second concern is that the form does not seem very beautiful. How can I make it aligned, all input boxes be aligned, and such?
<html>
<body>
<p>
<h3>Please select a configuration below to run the emulator with:</h3>
<form action="run.html" method="GET">
<input type="checkbox" name="-w" value="-w">[-w]: wrap around at tracefile end and begin anew at time zero. </input>
<br>
<input type="checkbox" name="-z" value="-w">[-z]: zero packets routed through; route to co-resident webserver
</input>
<br>
<br> YSE Emulator to Run: <select name="yse">
<option value="yse1">YSE1</option>
<option value="yse2">YSE2</option>
<option value="yse3">YSE3</option>
<option value="yse4">YSE4</option>
<option value="yse5">YSE5</option>
<option value="yse6">YSE6</option>
</select> <br>
<br>
<input type="checkbox" id="isTracefile" checked/>Use a sample tracefile
<br>Sample Tracefiles to use: <select name="tracefile">
<option value="capacity.1Mbps_c50.txt">capacity.1Mbps_c50</option>
<option value="capacity.3Mbps_100RTT_PER_0.00001.txt">capacity.3Mbps_100RTT_PER_0.00001</option>
<option value="capacity.3Mbps_100RTT_PER_0.0001.txt">capacity.3Mbps_100RTT_PER_0.0001</option>
<option value="capacity.3Mbps_100RTT_PER_0.001.txt">capacity.3Mbps_100RTT_PER_0.001</option>
<option value="capacity.3Mbps_100RTT_PER_0.01.txt">capacity.3Mbps_100RTT_PER_0.01</option>
<option value="capacity.3Mbps_100RTT_PER_0.05.txt">capacity.3Mbps_100RTT_PER_0.05</option>
<option value="capacity.3Mbps_100RTT_PER_0.1.txt">capacity.3Mbps_100RTT_PER_0.1</option>
<option value="capacity.3Mbps_200RTT_PER_0.0001.txt">capacity.3Mbps_200RTT_PER_0.0001</option>
<option value="capacity.3Mbps_200RTT_PER_0.001.txt">capacity.3Mbps_200RTT_PER_0.001</option>
<option value="capacity.3Mbps_400RTT_PER_0.0001.txt">capacity.3Mbps_400RTT_PER_0.0001</option>
<option value="capacity.3Mbps_400RTT_PER_0.001.txt">capacity.3Mbps_400RTT_PER_0.001</option>
<option value="capacity.13Mbps_200RTT_PER_0.000001.txt">capacity.13Mbps_200RTT_PER_0.000001</option>
</select>
<br>
<b> OR </b>
<br>
<label>Forward Delay: </label><input id="fd" type="number" min="0" max="1000" step="1" value ="100"> ms</input>
<br>
<label>Reverse Delay: </label><input id="rd" type="number" min="0" max="1000" step="1" value ="100"> ms</input>
<br>
<label>Download Capacity: </label><input id="down" type="number" min="1" max="30" step="1" value ="1"> MBps </input>
<br>
<label>Upload Capacity: </label><input id="up" type="number" min="1" max="30" step="1" value ="1"> MBps </input>
<br>
<label>Packet Error Rate (PER): </label><input id="per" type="number" min="0.00001" max="1" step="0.00001" value ="0.00001"></input>
<br>
<br> <input type="submit" value="Run Emulator!">
</form>
</body>
</html>
A:
I think you can solve it easily, if you can make some minor markup changes
<div id="cttracefile">
Sample Tracefiles to use:
<select name="tracefile">
<option value="capacity.1Mbps_c50.txt">capacity.1Mbps_c50</option>
<option value="capacity.3Mbps_100RTT_PER_0.00001.txt">capacity.3Mbps_100RTT_PER_0.00001</option>
<option value="capacity.3Mbps_100RTT_PER_0.0001.txt">capacity.3Mbps_100RTT_PER_0.0001</option>
<option value="capacity.3Mbps_100RTT_PER_0.001.txt">capacity.3Mbps_100RTT_PER_0.001</option>
<option value="capacity.3Mbps_100RTT_PER_0.01.txt">capacity.3Mbps_100RTT_PER_0.01</option>
<option value="capacity.3Mbps_100RTT_PER_0.05.txt">capacity.3Mbps_100RTT_PER_0.05</option>
<option value="capacity.3Mbps_100RTT_PER_0.1.txt">capacity.3Mbps_100RTT_PER_0.1</option>
<option value="capacity.3Mbps_200RTT_PER_0.0001.txt">capacity.3Mbps_200RTT_PER_0.0001</option>
<option value="capacity.3Mbps_200RTT_PER_0.001.txt">capacity.3Mbps_200RTT_PER_0.001</option>
<option value="capacity.3Mbps_400RTT_PER_0.0001.txt">capacity.3Mbps_400RTT_PER_0.0001</option>
<option value="capacity.3Mbps_400RTT_PER_0.001.txt">capacity.3Mbps_400RTT_PER_0.001</option>
<option value="capacity.13Mbps_200RTT_PER_0.000001.txt">capacity.13Mbps_200RTT_PER_0.000001</option>
</select>
</div>
<!--Wrap the custom inputs and its labels in a container so that it can be shown/hidden-->
<div id="custom">
<label>Forward Delay: </label><input id="fd" type="number" min="0" max="1000" step="1" value ="100"/> ms
<br/>
<label>Reverse Delay: </label><input id="rd" type="number" min="0" max="1000" step="1" value ="100"/> ms
<br/>
<label>Download Capacity: </label><input id="down" type="number" min="1" max="30" step="1" value ="1"/> MBps
<br/>
<label>Upload Capacity: </label><input id="up" type="number" min="1" max="30" step="1" value ="1"/> MBps
<br/>
<label>Packet Error Rate (PER): </label><input id="per" type="number" min="0.00001" max="1" step="0.00001" value ="0.00001"/>
</div>
then assuming you have already added jQuery to the page
//dom ready handler
jQuery(function($){
//change event handler for the checkbox
$('#isTracefile').change(function(){
//if it is checked set the select element's container to display else hide
$('#cttracefile').toggle(this.checked);
//if it is unchecked set the input element's container to display else hide
$('#custom').toggle(!this.checked);
}).change()
})
Demo: Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Qt loop through QHash to return it's key-value pairs
I'm trying to loop through a QHash using foreach and get each pair in the QHash and then get the keys and values of those so I can append them to a string.
Here's what I have
QString Packet::Serialize() {
QString sBuilder = Command.toUpper() + " ";
foreach(QMap<QString,QString> pair, Attributes) {
sBuilder.append(pair); // i know this isn't right because I couldn't
// finish the statement
}
}
The variable Attributes is the QHash.
Also, I realize the code is probably 100% wrong because I'm converting it from C#.
A:
Looks like you're trying to append each key/value pair to a string? Something like this would work:
QStringList data;
foreach(const QString &key, Attributes.keys())
data << key << Attributes.value(key);
sBuilder += data.join(" ");
| {
"pile_set_name": "StackExchange"
} |
Q:
Multi Line Labels and an Image with UIStackView
I am trying to see if I can easily use a UIStackView to create multi line labels and also display an image.
Here are my current constraints.
When I run it I get the following:
If I remove the imageview then the multi line works. Somehow UIImageView width and height is messing up everything. What am I doing wrong?
A:
StackView does not really work well with constraints, as they kind of destroy the purpose of stack views. Since the vertical inner stackView is inside a horizontal stackView with the imageView. When you give imageView hard constraints, in order to satisfy these constraints and keep the height & width values of stackViews at same level with imageView and inner stackView, the inner stackView cannot expand and it's height and you cannot get the behaviour you want. So as also mentioned in the comments, it is better to achieve your design without stackViews.
PS: I'm not saying stackViews cannot be used with constraints in their subViews. It can be done, and sometimes allow programmers to successfully achieve their goal, but you will always get debugger warnings due to conflicting constraints about the views with constraints inside a stackView.
A:
Change height and width of the imageView to give proper look and don't give fixed height for the stackview, only give top, bottom, leading and trailing.
THis is how it will look like
| {
"pile_set_name": "StackExchange"
} |
Q:
Cordova 5.3.3 Android app crashes on calling 'registerDevice' for push notifications
Problem
I'm building an Android app using Cordova 5.3.3 (latest), and using the pushwoosh cordova plugin for push notifications ( https://github.com/Pushwoosh/pushwoosh-phonegap-3.0-plugin ).
The app also uses the facebook-connect plugin ( https://github.com/Wizcorp/phonegap-facebook-plugin )
The pushwoosh plugin seems to conflict with the facebook connect plugin. When the two plugins are added to a new cordova project, the application build starts failing. This is the message:
:compileDebugJava
:preDexDebug
:dexDebug
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
at com.android.dx.command.dexer.Main.run(Main.java:246)
at com.android.dx.command.dexer.Main.main(Main.java:215)
at com.android.dx.command.Main.main(Main.java:106)
:dexDebug FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
/Users/shishir.srivastava/Development/android-sdk-macosx/build-tools/22.0.1/dx --dex --no-optimize --output /Users/shishir.srivastava/Shishir/MallMate/Code/MallMateCordova-temp/platforms/android/build/intermediates/dex/debug --input-list=/Users/shishir.srivastava/Shishir/MallMate/Code/MallMateCordova-temp/platforms/android/build/intermediates/tmp/dex/debug/inputList.txt
Error Code:
2
Output:
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
at com.android.dx.command.dexer.Main.run(Main.java:246)
at com.android.dx.command.dexer.Main.main(Main.java:215)
at com.android.dx.command.Main.main(Main.java:106)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Fix
To fix the above issue, I added the following to build-extras.gradle file in the android folder.
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
}
This allowed the app to build without any issues. However, now, the app crashes when pushNotification.registerDevice() is called.
I used adb shell logcat to check the error logs, and saw this:
D/PushNotifications( 4751): Plugin Called
D/Pushwoosh( 4751): broadcastPush = true
I/Pushwoosh( 4751): Log level: NOISE
V/Pushwoosh( 4751): [RegistrationPrefs] Saving regId on app version 178
I/Pushwoosh( 4751): [PushManager] App ID: #####-#####
I/Pushwoosh( 4751): [PushManager] Project ID: 1088448295557
I/Pushwoosh( 4751): [PushManager] This is android device
W/ActivityManager( 943): Unable to start service Intent { cmp=com.shishir/com.pushwoosh.inapp.InAppRetrieverService } U=0: not found
V/Pushwoosh( 4751): [PushRegistrarGCM] number of receivers for com.shishir: 3
V/Pushwoosh( 4751): [PushRegistrarGCM] Found 1 receivers for action com.google.android.c2dm.intent.RECEIVE
W/Pushwoosh( 4751): [RequestManager] Try To sent: registerUser
W/PluginManager( 4751): THREAD WARNING: exec() call to PushNotification.onDeviceReady blocked the main thread for 61ms. Plugin should use CordovaInterface.getThreadPool().
I/chromium( 4751): [INFO:CONSOLE(1)] "pushwoosh initialized", source: file:///android_asset/www/app.js (1)
D/PushNotifications( 4751): Plugin Called
W/Pushwoosh( 4751): [RequestManager] Pushwoosh Request: {"request":{"v":"3.1.8.563","device_type":3,"application":"#####-#####","hwid":"###","userId":"###"}}
W/Pushwoosh( 4751): [RequestManager] Pushwoosh Request To: https://cp.pushwoosh.com/json/1.3/registerUser
V/Pushwoosh( 4751): [com.pushwoosh.GCMRegistrationService] Intent action = com.pushwoosh.gcm.intent.REGISTER
I/chromium( 4751): [INFO:CONSOLE(1)] "pushwoosh: post registration", source: file:///android_asset/www/app.js (1)
W/cr.BindingManager( 4751): Cannot call determinedVisibility() - never saw a connection for the pid: 4751
I/chromium( 4751): [INFO:CONSOLE(1)] "[object Object]", source: file:///android_asset/www/app.js (1)
E/AndroidRuntime( 4751): FATAL EXCEPTION: IntentService[com.pushwoosh.GCMRegistrationService]
E/AndroidRuntime( 4751): Process: com.shishir, PID: 4751
E/AndroidRuntime( 4751): java.lang.NoSuchMethodError: No virtual method getNoBackupFilesDir(Landroid/content/Context;)Ljava/io/File; in class Landroid/support/v4/content/ContextCompat; or its super classes (declaration of 'android.support.v4.content.ContextCompat' appears in /data/app/com.shishir-1/base.apk)
E/AndroidRuntime( 4751): at com.google.android.gms.iid.zzd.zzdo(Unknown Source)
E/AndroidRuntime( 4751): at com.google.android.gms.iid.zzd.<init>(Unknown Source)
E/AndroidRuntime( 4751): at com.google.android.gms.iid.zzd.<init>(Unknown Source)
E/AndroidRuntime( 4751): at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
E/AndroidRuntime( 4751): at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
E/AndroidRuntime( 4751): at com.pushwoosh.GCMRegistrationService.register(Unknown Source)
E/AndroidRuntime( 4751): at com.pushwoosh.GCMRegistrationService.onHandleIntent(Unknown Source)
E/AndroidRuntime( 4751): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
E/AndroidRuntime( 4751): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 4751): at android.os.Looper.loop(Looper.java:211)
E/AndroidRuntime( 4751): at android.os.HandlerThread.run(HandlerThread.java:61)
D/ActivityManager( 943): New dropbox entry: com.shishir, data_app_crash, ####
W/ActivityManager( 943): Force finishing activity 1 com.shishir/.MainActivity
From what I understand, this seems to be the mail reason behind the crash:
java.lang.NoSuchMethodError: No virtual method getNoBackupFilesDir(Landroid/content/Context;)Ljava/io/File; in class Landroid/support/v4/content/ContextCompat; or its super classes (declaration of 'android.support.v4.content.ContextCompat' appears in /data/app/com.shishir-1/base.apk)
I'm a little lost as to how I should proceed from here. Any help will be greatly appreciated.
Thank you!
A:
After much toil, I was able to figure out the root cause of the issue. I'm posting it here with the hope that it'll be of some help to the next person who faces the same issue.
I realised that the facebook connect plugin that I was using was using an outdated version of FB SDK.
I switched to this one, and the problem was resolved: https://github.com/jeduan/cordova-plugin-facebook4
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use eval() for php code stored in DB?
I have whole HTML code present in the db and it includes following HTML code-
<p class="card mb-4 shadow-sm"><img src="<?php echo SITE_URL; ?>/assets/images/blog/php.png" alt="php" title="php"></p>
This HTML is stored in db and I want it to print value of SITE_URL when it gets fetched because SITE_URL is dynamic (const here in this case).
I tried using PHP's own eval() function like the one mentioned in this article. But it's not working.
what would be the better way to do this OR
is there any other way to figure out this ?
Here, what I tried.
<p class="card mb-4 shadow-sm"><img src="<?php
$str = SITE_URL;
eval('\$str = \'$str\';');
echo $str; ?>/assets/images/blog/php.png" alt="php" title="php"></p>
A:
Presuming you know how dodgy using eval is..
As long as SITE_URL is defined, it would be fine. Then you would do something like:
<?php
define('SITE_URL', 'http://example.com');
$str = '<p class="card mb-4 shadow-sm"><img src="<?php echo SITE_URL; ?>/assets/images/blog/php.png" alt="php" title="php"></p>';
echo eval('?>'.$str);
https://3v4l.org/EEB54
An alternative to using eval, is to use a template and replace the placeholders with the values you define.
<?php
define('SITE_URL', 'http://example.com');
$vars = [
'SITE_URL' => SITE_URL
];
$template = '<p class="card mb-4 shadow-sm"><img src="{{ SITE_URL }}/assets/images/blog/php.png" alt="php" title="php"></p>';
// match any single word with _ or -, with spaces either side or not
// e.g: {{key}} or {{ key }} or {{key-foo}} or {{ key-foo }}
// not {{ a b c }}
$str = preg_replace_callback("/{{[ ]{0,}([\w\_-]{1,})[ ]{0,}}}/", function ($match) use ($vars) {
return array_key_exists($match[1], $vars) ? $vars[$match[1]] : '';
}, $template);
echo $str;
https://3v4l.org/cUK5B
Or look into using a template engine if you need more features.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculation of magnetic field saturation inside coil core
I want to try to make an electromagnet, but I don't have soft-iron available. I've read that ferrite MnZn are suitable as soft-iron to create a high efficiency magnets with the inconvenient of lower magnetic saturation.
I'd like to know If with my specifics I can occur in this saturation range. Magnet will be activated with a frequency of 10 kHz to control and keep current at 1A-1.5A. About 50 turns are applied. Dimensions of core are 10mm diameter and length 30mm Ferrite type is an MnZn. Relative permeability from datasheet 15000µ/µ₀ at 10kHz, permeability µ₀ 0.3*10-3 H/m at 10kHz.
Applying this equation: B = µ₀ * N * I / L
I've
µ₀ 0.3*10-3 H/m
N 50
I 1.5A
L 0.030m
B = 0.6 * 10-4
Can be this value be so low and can I be so far from saturation? Even if I apply 10A I'm very far from saturation. This mean that saturation is something that occur in very particular applications where high current, lengths and number of turn are involved?
A:
Apart from the fact that you are probably misusing the length dimension of the ferrite, you are also miscalculating flux density quite badly (See further below).
The length dimension for a ferrite core is the closed loop length that the magnetic field travels along and, for an electromagnet, it has to include the air gap. Any small amount of air gap will reduce the effective pemeability of the core to a value closer to air. You need to calculate the effective permeability and not use the initial permeability stated in the material data sheets.
Values
\$μ_0 = 4π × 10−7\$ H/m
\$μ_0\cdot μ_R = 0.01885\$ H/m
\$H = \dfrac{NI}{\text{length}} = \$50 turns x 1 amp / 0.03 metres = 1667 amp_turns per metre
Therefore B = 31.4 teslas.
Can be this value be so low and can I be so far from saturation?
No, you've made a math error somewhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Join Tables Apply Value Only Once To Each Set
I need to join two tables together. However, the table being joined must only apply its value once to a set a rows with the same value. This is what I mean...
TABLE JOIN I WANT IS BELOW
** LOGGED HOURS ** ** SICK HOURS ** ** RESULT TABLE **
+--------+-------+ +--------+-------+ +--------+-------+-------+
|Name | Hours | |Name | Hours | |Name |Hours |Sick |
+--------+-------+ +--------+-------+ +--------+-------+-------+
|David |47 | |David |9 | |David |47 |9 |
+--------+-------+ +--------+-------+ +--------+-------+-------+
|David |9 | |David |9 |0 |
+--------+-------+ +--------+-------+-------+
NORMAL LEFT TABLE JOIN RESULT:
** LOGGED HOURS ** ** SICK HOURS ** ** RESULT TABLE **
+--------+-------+ +--------+-------+ +--------+-------+-------+
|Name | Hours | |Name | Hours | |Name |Hours |Sick |
+--------+-------+ +--------+-------+ +--------+-------+-------+
|David |47 | |David |9 | |David |47 |9 |
+--------+-------+ +--------+-------+ +--------+-------+-------+
|David |9 | |David |9 |9 |
+--------+-------+ +--------+-------+-------+
Notice, 9 is applied to EACH row in a normal left table join. I want 9 to be applied ONLY ONCE to the set of rows whose name is DAVID.
Feel free to as any questions, thanks.
EDIT: If you're going to down-vote my question, please provide the courtesy of explaining why and how I can improve my question in the future. Thank you.
A:
Since you just want a single record for each "Name" to get your sick hours and the selection can be arbitrary, you can use a Window Function:
SELECT
LoggedHours.Name,
LoggedHours.Hours,
CASE WHEN ROW_NUMBER() OVER (PARTITION BY LoggedHours.Name ORDER BY 1) = 1 THEN SickHours.Hours ELSE NULL END AS SickHoursLogged
FROM
LoggedHours LEFT OUTER JOIN SickHours on LoggedHours.Name = SickHours.Name
So... that Window/Analytics function says:
Split the result set by Name (group of records with "David" for
example) and order them by whatever. Then give that group of records
row numbers starting at 1. If this particular record is row 1, then it
gets the sick hours from the SickHours table. Otherwise it gets
Null.
If... you wanted it to not be arbitrary, but instead wanted the record with the largest logged hours for each person to get the sick hours, you could change that ROW_NUMBER() function to:
ROW_NUMBER() OVER (PARTITION BY LoggedHours.Name ORDER BY LoggedHours.Hours DESC) = 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Writing text in multiline in python
I am working on a text editor. The only challenge left for me is to write text in next line when text width(written) exceeded from its maximum size(window).
Any help will be appreciated. I have a class photo viewer that controls text font, size etc.Thanks in advance
class PhotoViewer(QtWidgets.QGraphicsView):
photoClicked = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, parent):
super(PhotoViewer, self).__init__(parent)
self._zoom = 0
self._empty = True
self._scene = QtWidgets.QGraphicsScene(self)
self._photo = QtWidgets.QGraphicsPixmapItem()
self._textLayer = QtWidgets.QGraphicsSimpleTextItem ()
self._scene.addItem(self._photo)
self._scene.addItem(self._textLayer)
self.setScene(self._scene)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(80, 30, 30)))
self.setFrameShape(QtWidgets.QFrame.NoFrame)
self._textLayer.setFlags(QGraphicsItem.ItemIsMovable)
def updateText(self,text,font_size=50):
# Load the font:
font_db = QFontDatabase()
font_id = font_db.addApplicationFont("fonts/Summer's Victory Over Spring - TTF.ttf")
#families = font_db.applicationFontFamilies(font_id)
#print (families)
myFont = QFont("Summers Victory Over Spring")
myFont.setPixelSize(font_size*1.5)
self._textLayer.setFont(myFont)
self._textLayer.setText(text)
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.viewer = PhotoViewer(self)
# 'Load image' button
# Button to change from drag/pan to getting pixel info
self.btnPixInfo = QtWidgets.QToolButton(self)
self.btnPixInfo.setText('Create Text')
self.btnPixInfo.clicked.connect(self.loadText)
self.fontSize =QtWidgets.QSpinBox()
self.fontSize.valueChanged.connect(self.loadText)
self.editPixInfo = QtWidgets.QLineEdit(self)
#self.editPixInfo.setReadOnly(True)
self.viewer.photoClicked.connect(self.photoClicked)
# Arrange layout
VBlayout = QtWidgets.QVBoxLayout(self)
HBlayout = QtWidgets.QHBoxLayout()
HBlayout.setAlignment(QtCore.Qt.AlignLeft)
HBlayout.addWidget(self.btnPixInfo)
HBlayout.addWidget(self.editPixInfo)
VBlayout.addLayout(HBlayout)
VBlayout.addWidget(self.viewer)
HBlayout.addWidget(self.fontSize)
self.editPixInfo.setText("Sheeda")
self.fontSize.setValue(20)
self.loadText()
self.frame = QFrame()
self.frame.setFrameStyle(QFrame.StyledPanel)
self.frame.setLineWidth(20)
def loadText(self):
#self.viewer.toggleDragMode()
self.viewer.updateText(self.editPixInfo.text(),self.fontSize.value())
def photoClicked(self, pos):
if self.viewer.dragMode() == QtWidgets.QGraphicsView.NoDrag:
self.editPixInfo.setText('%d, %d' % (pos.x(), pos.y()))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 800, 600)
window.show()
sys.exit(app.exec_())
Here is my code so far.
A:
I see, you are using QGraphicsSimpleTextItem where as your easiest bet is to use QGraphicsTextItem. Reason being, later offers a setTextWidth method,defauls to -1. Just set this to your 'maximumSize' limit. also,you have to update your "setText" call to "setPlainText" call as per QGraphicsTextItem Docs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to get remote data that changes a lot
There are 3+ apps which collect parameters in the form of one string, like "Peter", "Jane", "Mary", etc. At the moment I keep this parameters in String[] array. However, the data needs to be changed a lot so every few days I have to amend strings, recompile APKs and publish it. Just waist of time.
What should be the simplest way to keep this data in a remote file (NOT database), maybe text file, so that the apps can download list of parameters on need? My idea is to change this file just once, upload it to some remote server and then the apps download parameters automatically. This way I would not have to recompile and republish the APKs.
If the text file is the simplest solution, what should be the form of it? For example, should I write parameters like this
Peter, Jane, Mary, ...
Or in some other form?
Is there a need for some layer between this text file and Android app, like when we make layer on the remote server to grab data from database? Or I can simply grab data directly from this remote text file?!
A:
Well the delivery mechanism could be a simple HTTP GET your app performs to a web server you control. It could be as simple as http://myhost/names.txt.
The data format depends on what you want to do. The super simple solution would be a text file with a different name on each line:
Peter
Jane
Mary
Or, you could serve up JSON from the server and parse it on your client.
{ "names": [ "Peter", "Jane", "Mary" ] }
The JSON solution would be more extendable, should you wish to add more values in future, e.g.:
{ "names": [ "Peter", "Jane", "Mary" ],
"lastnames": [ "Smith", "Johnston", "Cumberbatch" ] }
Really depends entirely on what you're comfortable with and what your situation calls for.
| {
"pile_set_name": "StackExchange"
} |
Q:
node.js server running but not loading
I've just installed node.js on my computer running Win7(64bit).
The problem is that when I run a simple hello-world application it is running (as confirmed by console.log() and me pushing the code to OpenShift where it works just fine) but when I try to load the page in localhost:1337 it just keeps on loading (eventually times out).
I've no idea what to check, since firewall is not blocking node and I'm not running anything that would block the port.
Here's the server code.
#!/bin/env node
// Include http module.
var http = require("http");
//Get the environment variables we need if on OpenShift
var ipaddr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 1337;
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(port, ipaddr);
console.log('It works');
console.log('IP : ' + ipaddr + '\nPort : ' + port);
Any help is appreciated, thank you.
edit
Here's a screenshot of commandline output.
http://i.stack.imgur.com/GGaLD.png
A:
The node server is hanging as you need to always call response.end.
I believe that listening to the end event on the request is causing the timeout. If you remove it will work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Any way to do true conditional compilation in Swift 3?
There are some related questions but I have insufficient site reputation to comment on the existing threads, forcing me to start a new one. Sorry about that.
It appears Swift doesn't have a true preprocessor. Workarounds are possible using #if / #else / #endif, but the problem here is that it doesn't hide the 'false' portion from the compiler, forcing both the 'true' and 'false' parts to be syntactically valid. This is tough given that Swift 3 is syntactically incompatible with Swift 2 -- has anyone found a workaround that will allow creating code that can be compiled for either environment? (If XCode 8 beta allowed Swift 2.2, or if XCode 7.3.1 allowed Swift 3, that would also give me a workaround here).
What I'm trying to do, to give just one trivial example, is something like
#if SWIFT3
let session = WCSession.default()
#else
let session = WCSession.defaultSession()
#end
I can't find any way to do this, and it seems surprising that there isn't a way to do it given how completely incompatible Swift3 syntax is with Swift2.
A:
I can't find any way to do this
Nevertheless, there is one, and there has been one since Swift 2.2; they planned ahead for exactly this contingency:
https://github.com/apple/swift-evolution/blob/master/proposals/0020-if-swift-version.md
So, like this (I don't know what a WCSession is, so I used a different example):
#if swift(>=3.0)
let screen = UIScreen.main()
#else
let screen = UIScreen.mainScreen()
#endif
EDIT According to Apple, Xcode 8 permits passing of arbitrary conditional compilation flags to Swift:
Active Compilation Conditions is a new build setting for passing conditional compilation flags to the Swift compiler. Each element of the value of this setting passes to swiftc prefixed with -D, in the same way that elements of Preprocessor Macros pass to clang with the same prefix. (22457329)
| {
"pile_set_name": "StackExchange"
} |
Q:
"Confused Digger" algorithm running too slow, any way to speed it up?
I have an algorithm that was based on a backtracking maze algorithm with some parts removed, resulting in this wonderful dungeon. Unfortunately, it runs extremely slowly which makes it almost impossible to fill a decently-sized map with. I really don't want to throw it out, but I can't think of any way to speed it up. I'm using Python, so I know that's part of my problem, but I'm not exactly prepared to throw out my roguelike's entire existing codebase, which runs fast enough right now. Here's the code currently:
start = (random.randint(0, self.width), random.randint(0, self.height))
self.dungeon['up_stairs'] = start
visited = [start]
while len(visited) < 300:
current = visited[-1]
apos = random.choice([(1, 0), (0, 1), (0, -1), (-1, 0)])
new = utils.tuple_add(current, apos)
if not new in visited and self.on_map(new):
self.place_cell(new, is_wall=False)
visited.append(new)
else:
visited.pop()
[edit]
To answer some questions in the comments, place_cell either creates a wall or an empty cell at the supplied position-tuple based on the positional argument is_wall. So for instance, in the code above, the self.place_cell(new, is_wall=False) call changes the cell at the position new on the map to an empty cell.
Visited should really be called something else, I'm just... lazy that way. I'll fix it later probably.
The < 300 condition is because 299 cells is the most it can draw in a reasonable time frame. (Beyond 299 cells, it suddenly starts hanging.)
A:
I would suggest following improvements:
Do not pop a visited cell only because you failed on one step. This may lead to starvation: popping and trying again, popping ... etc. You should instead pick another cell you visited in the past, and continue from there. If that fails, pick another one...
Use a set to keep track of the visited cells: this will allow faster lookup
Use another "frontier" set for keeping track of which visited cells still have unvisited neighbours
When a cell is visited, check all neighbours in random order whether they are unvisited. The first one that is will be your next visit. But if all of them were visited (or outside the grid) then choose a random cell from the frontier set.
Here is the suggested code:
start = (random.randint(0, self.width-1), random.randint(0, self.height-1))
self.dungeon['up_stairs'] = start
current = start
frontier = set()
visited = set([start])
while len(visited) < 400:
frontier.add(current)
self.place_cell(current, is_wall=False)
found = False
while not found:
choices = [(1, 0), (0, 1), (0, -1), (-1, 0)]
random.shuffle(choices)
for apos in choices:
new = utils.tuple_add(current, apos)
if not new in visited and self.on_map(new):
found = True
break
if not found:
# we can remove this cell from frontier as it is
# completely surrounded by visited cells
frontier.discard(current)
# pick a random other one to start from
current = random.sample(frontier, 1)[0]
current = new
visited.add(current)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return an unknown object which contains a specified member variable
There is some code I have seen where the returning object has a Visible member, which can set to be true. I would like to mimic this functionality, but I am getting the error 'object' does not contain a definition for 'Visible' and no extension method 'Visible' accepting a first argument of type 'object' could be found.
Here is the example code that works:
public AP.GlobalClass APObj = new AP.GlobalClass();
APObj.Application().Visible = true;
Here is what I am trying to do that doesn't work:
public APControl.A2APGlobalClass APObj_B = new APControl.A2APGlobalClass();
APObj_B.Application().Visible = true; //Error goes with this line
public class A2APGlobalClass
{
public AP.GlobalClass APObj = new AP.GlobalClass();
public Object Application() //Do I need to change "Object" to something else?
{
return APObj.Application(); //This returned object "Object" type does no longer contain the Visible member.
}
A:
The code may be closed source, but the public members of the types exposed by the assembly must by definition be visible. If you are working in any kind of decent environment, the intellisense will tell you the return type when you hover your mouse over the member. If your editor has no intellisense, there are other ways to extract this information.
With reference to @JeroenVannevel's comment, you might want to read up on static vs dynamic typing. C# is as heart a statically typed language, so you cannot call the Visible property on a reference of type Object, because Object has no Visible property. Instead of Object, you need to return one of the following:
the actual type of the object being returned
the class in which the Visible property is declared
a type that falls between the two previously mentioned types in the inheritance chain (if there are any such types)
an interface type (if any) implemented by the object being returned and that defines the Visible property
For example, with the types defined below, you could return any of the types except for A:
interface I { bool Visible { get; set; } }
class A { }
class B : I { public bool Visible { get; set; } }
class C : B { }
class D : C { }
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prevent people from dropping in non-droppable elements?
I am implementing drag and drop this way.
<?php echo $this->Html->script('modernizr/2.5.3/modernizr.min.js', array('block' => 'scriptTop')); ?>
$(document).ready(function () {
dropArea = document.getElementById("droparea");
dropArea.addEventListener("dragleave", function (evt) {
var target = evt.target;
if (target && target === dropArea) {
this.className = "";
}
dropArea.className = "";
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("dragenter", function (evt) {
this.className = "over";
evt.preventDefault();
evt.stopPropagation();
}, false);
dropArea.addEventListener("dragover", function (evt) {
evt.preventDefault();
evt.stopPropagation();
}, false);
// this is the initial add-drop
dropArea.addEventListener("drop", function (evt) {
doStuff();
this.className = "";
evt.preventDefault();
evt.stopPropagation();
}, false);
}
There are times when my users dropped stuff NOT into #droparea.
I want to prevent them from doing that.
What should I do?
A:
You need to add a noop dragover and drop handler for your document. This will prevent the default browser behavior of replacing current page with dropped file.
See here for a demo
// Handle dropping on non-droparea
document.addEventListener("drop", cancelEvent, false);
document.addEventListener("dragover", cancelEvent, false);
function cancelEvent(evt) {
evt.preventDefault();
evt.stopPropagation();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Choosing motor and battery for a robot
I have a project which requires a robot to move around a room with a flat surface (concrete floor).
The robot must carry a laptop. I estimated that the total weight would be 6-7kg (including motors, battery, laptop, motor controller board and other mics items). I would like it to move at about the same speed as a Roomba moves. The robot will have two motors and a castor.
I have tried doing the calculation to determine the type of motor to use, but I'm very confused.
Can someone advise me on the type of motor and type of battery (Lipo/SLA) to use?
A:
Roombas move slowly, below a walking pace, right?
If that's so, then you probably want a geared DC motor. I'm guessing that on concrete you can get away with a motor that's 100W or less, particularly if it's geared down a whole bunch. You might want to figure out the highest incline or steepest step that you want to negotiate, figure out what force you need to surmount that obstacle, multiply by two, and go from there.
To figure out the gear ratio (or to buy a gearbox-motor combination), decide on a wheel diameter and a top speed. Then figure out the wheel speed that gets you that top speed. Then go buy a pair of gear motor that are rated for that RPM as a unit, or select a motor with a known RPM and a gearbox with the right ratio to bring the RPM down.
As far as batteries -- SLA will be way cheaper, LiPo will be more expensive for both batteries and support equipment, but will hold more charge for the weight. You makes your choice and you pays your money...
If this is a one-off then just buy a pair of wheel units made for robots. Whatever you get you're just about guaranteed to be wrong somehow, so the most important thing to do is to start making the mistakes that you'll correct in Robot, Mark II.
| {
"pile_set_name": "StackExchange"
} |
Q:
ASPxGridView default unbound column filter from dropdown
So I am using ASPxGridView for displaying data. I have an unbound column with text in there. Normally, you can filter the column:
-by selecting a value from dropdown
-by typing some text in filter input
The behaviour I'm trying to achieve is: When you select a special value from the dropdown, I want to filter the column with BeginsWith filter. I tried using
<Settings AutoFilterCondition="BeginsWith" />
but it only seems to work with input filtering: when I type text into filter input, column is filtered with specified filter, but when I chose value from dropdown, EqualsTo filter is used instead. How can I achieve my goal behaviour?
A:
So thankfully I've found a solution. What I did:
-get the FilterValue of interest
-and then
filtervalue.Query = "StartsWith([Column], 'value')"
| {
"pile_set_name": "StackExchange"
} |
Q:
Plotting in Python Notebook (Docs)
Attempting to go through the pandas doc at http://pandas.pydata.org/pandas-docs/stable/visualization.html#basic-plotting-plot I get an error :
NameError: name 'Series' is not defined
I can import pandas and supply 'pandas.Series', but I want to know how to set up notebook, as in the docs, so that it's already included.
A:
You can customize Ipython notebook profile file ipython_config.py typically located in ~/.ipython/profile_default/ by adding something like :
c.InteractiveShellApp.exec_lines = [
'import pandas',
]
You can read the documentation for ipython latest version here
| {
"pile_set_name": "StackExchange"
} |
Q:
Data Management Gateway in Azure ML Studio
I built an experiment in Azure ML Studio and want to get the input to the model through On-Premise SQL-Server Database. Does Data Management Gateway help in connecting to the Database, if so can you please mention the steps to be followed.
A:
Yes you need to use Data Management Gateway.
Refer link below
Connect to DB from ML Studio
| {
"pile_set_name": "StackExchange"
} |
Q:
Как в PyQt5 к кнопке привязать другое окно и преобразовать всё в .exe файл?
Имеются 2 программы: бинарный калькулятор и прогноз погоды в отдельных окнах.
Надо сделать так, чтобы при нажатии на соответствующие кнопки в меню отображались соответствующие окна программ.
К главному меню относятся файлы mintro.py и mintro1.py:
mintro.py:
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(371, 300)
Dialog.setStyleSheet("background-color:#8430b8;")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(30, 160, 311, 51))
self.pushButton.setStyleSheet("color:#d7e535;\n"
"font: 14pt \"Onyx\";\n"
"background-color:#494f8a;")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(30, 220, 311, 51))
self.pushButton_2.setStyleSheet("color:#e01414;\n"
"font: 14pt \"Onyx\";\n"
"background-color:#dff022;")
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(0, 30, 371, 51))
self.label.setStyleSheet("color:#22f70f;\n"
"font: 8pt \"Playbill\";\n"
"border:none;\n"
"")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(30, 70, 321, 81))
self.label_2.setStyleSheet("font: 11pt \"MV Boli\";\n"
"")
self.label_2.setObjectName("label_2")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
self.pushButton.setText(QtWidgets.QApplication.translate("Dialog", "Бинарный калькулятор", None, -1))
self.pushButton_2.setText(QtWidgets.QApplication.translate("Dialog", "Узнать погоду в городе", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Dialog", "<html><head/><body><p align=\"center\"><span style=\" font-size:36pt; color:#ff0000;\">SWISS </span><span style=\" font-size:36pt; color:#ffffff;\">KNIFE </span><span style=\" font-size:12pt;\">v 1.0</span></p><p><span style=\" font-size:36pt;\"><br/></span></p><p align=\"center\"><span style=\" font-size:36pt;\"><br/></span></p></body></html>", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("Dialog", "Выберите одну из предложенных функций:", None, -1))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
mintro1.py:
import sys
from PySide2 import QtCore, QtGui, QtWidgets
from mintro import Ui_Dialog
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
# Здесь предполагаю возможные функции соединения c кнопками
def bincalc():
ui.pushButton.clicked.connect(bincalc)
def weathshow():
ui.pushButton_2.clicked.connect(weathshow)
sys.exit(app.exec_())
weath1.py
import sys, pyowm
from PySide2 import QtCore, QtGui, QtWidgets
from weath import Ui_Dialog
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
class Weathshow(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Weathshow, self).__init__(parent)
self.setupUi(self)
def get_weather_city():
owm = pyowm.OWM('API key', language = "ru")
place = ui.lineEdit.text()
observation = owm.weather_at_place(place)
w = observation.get_weather()
temper = w.get_temperature('celsius')['temp']
ui.label_2.setText(f"Температура сейчас {temper} по Цельсию.")
ui.label_3.setText( f"В городе {place} сейчаc {w.get_detailed_status()}.")
if temper < 10:
ui.label_4.setText( f"На улице довольно холодно: одевайтесь тепло." )
elif temper < 20:
ui.label_4.setText( f"На улице холодно: одевайтесь потеплее." )
else:
ui.label_4.setText( f"На улице тепло: одевайтесь свободно." )
ui.pushButton.clicked.connect( get_weather_city )
sys.exit(app.exec_())
my_weath.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(451, 363)
Dialog.setStyleSheet("background-color:#90d5fc;")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(90, 10, 251, 51))
self.label.setStyleSheet("font: 9pt \"MV Boli\";")
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(260, 130, 141, 51))
self.pushButton.setStyleSheet("QPushButton {\n"
"color:#2e0ff7;\n"
"background-color:#83f70f;\n"
"border:none;\n"
"font: 12pt \"Niagara Engraved\";\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color:silver;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color:red;\n"
"}\n"
"")
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(22, 70, 381, 41))
self.lineEdit.setStyleSheet("color:#404dc2;\n"
"border:none;\n"
"background:#77a17b;\n"
"font: 15pt \"Nirmala UI\";")
self.lineEdit.setObjectName("lineEdit")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(10, 190, 431, 51))
self.label_2.setStyleSheet("color:#db145d;\n"
"font: 75 italic 12pt \"MS Sans Serif\";")
self.label_2.setText("")
self.label_2.setTextFormat(QtCore.Qt.PlainText)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(6, 240, 441, 51))
self.label_3.setStyleSheet("color:#db145d;\n"
"font: 75 italic 12pt \"MS Sans Serif\";")
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(6, 292, 441, 51))
self.label_4.setStyleSheet("color:#db145d;\n"
"font: 75 italic 12pt \"MS Sans Serif\";")
self.label_4.setText("")
self.label_4.setObjectName("label_4")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Dialog", "Введите город, чтобы узнать погоду:", None, -1))
self.pushButton.setText(QtWidgets.QApplication.translate("Dialog", "Узнать погоду", None, -1))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
После того, как программы объединены нужно преобразовать все
это в .exe файл. Знаю, что с помощью pyinstaller делаются .exe файлы, но что именно из этих трёх преобразовывать в данное расширение?
A:
Ваше основное окно приложения выглядит так:
mintro.py
#from PySide2 import QtCore, QtGui, QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
from my_bincalc import Bincalc # из my_bincalc.py
#from my_weathshow import Weathshow # из my_weathshow.py
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(371, 300)
Dialog.setStyleSheet("background-color:#8430b8;")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(30, 160, 311, 51))
self.pushButton.setStyleSheet("color:#d7e535;\n"
"font: 14pt \"Onyx\";\n"
"background-color:#494f8a;")
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(30, 220, 311, 51))
self.pushButton_2.setStyleSheet("color:#e01414;\n"
"font: 14pt \"Onyx\";\n"
"background-color:#dff022;")
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(0, 30, 371, 51))
self.label.setStyleSheet("color:#22f70f;\n"
"font: 8pt \"Playbill\";\n"
"border:none;\n"
"")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(30, 70, 321, 81))
self.label_2.setStyleSheet("font: 11pt \"MV Boli\";\n"
"")
self.label_2.setObjectName("label_2")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
self.pushButton.setText(QtWidgets.QApplication.translate("Dialog", "Бинарный калькулятор", None, -1))
self.pushButton_2.setText(QtWidgets.QApplication.translate("Dialog", "Узнать погоду в городе", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Dialog", "<html><head/><body><p align=\"center\"><span style=\" font-size:36pt; color:#ff0000;\">SWISS </span><span style=\" font-size:36pt; color:#ffffff;\">KNIFE </span><span style=\" font-size:12pt;\">v 1.0</span></p><p><span style=\" font-size:36pt;\"><br/></span></p><p align=\"center\"><span style=\" font-size:36pt;\"><br/></span></p></body></html>", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("Dialog", "Выберите одну из предложенных функций:", None, -1))
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.bincalc)
self.pushButton_2.clicked.connect(self.weathshow)
def bincalc(self): # бинарный калькулятоp
print('bincalc')
self.bincalc = Bincalc() # бинарный калькулятоp
self.bincalc.show()
def weathshow(self): # прогноз погоды
print('weathshow')
#self.weathshow = Weathshow()
#self.weathshow.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
# Dialog = QtWidgets.QDialog()
# ui = Ui_Dialog()
# ui.setupUi(Dialog)
# Dialog.show()
w = Dialog()
w.show()
sys.exit(app.exec_())
ваш модуль, который содержит бинарный калькулятор выглядит так:
my_bincalc.py
#from PySide2 import QtCore, QtGui, QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
#from binar import Ui_Dialog
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(452, 360)
Dialog.setStyleSheet("background-color:#e6fad2;\n"
"")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(10, 70, 381, 31))
self.lineEdit.setStyleSheet("color:#1db823;\n"
"font: 10pt \"Tw Cen MT Condensed Extra Bold\";\n"
"background-color:#0a2c40;\n"
"border:none;")
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(10, 130, 111, 31))
self.pushButton.setStyleSheet("\n"
"QPushButton {\n"
"\n"
" color:#f1f52a;\n"
" font: 8pt \"MS Serif\";\n"
" font: 11pt \"MS Shell Dlg 2\";\n"
" background-color:#822af5;\n"
" border:none;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color:silver;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color:red;\n"
"}\n"
"\n"
"\n"
"")
self.pushButton.setObjectName("pushButton")
self.lineEdit_2 = QtWidgets.QLineEdit(Dialog)
self.lineEdit_2.setGeometry(QtCore.QRect(10, 240, 381, 31))
self.lineEdit_2.setStyleSheet("color:#1db823;\n"
"font: 10pt \"Tw Cen MT Condensed Extra Bold\";\n"
"background-color:#0a2c40;\n"
"border:none;")
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton_2 = QtWidgets.QPushButton(Dialog)
self.pushButton_2.setGeometry(QtCore.QRect(10, 300, 111, 31))
self.pushButton_2.setStyleSheet("\n"
"QPushButton {\n"
"\n"
" color:#f1f52a;\n"
" font: 8pt \"MS Serif\";\n"
" font: 11pt \"MS Shell Dlg 2\";\n"
" background-color:#822af5;\n"
" border:none;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color:silver;\n"
"}\n"
"\n"
"QPushButton:pressed {\n"
" background-color:red;\n"
"}\n"
"\n"
"")
self.pushButton_2.setObjectName("pushButton_2")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(20, 20, 401, 31))
self.label.setStyleSheet("font: 9pt \"MV Boli\";")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(20, 190, 411, 31))
self.label_2.setStyleSheet("font: 9pt \"MV Boli\";")
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Dialog)
self.label_3.setGeometry(QtCore.QRect(156, 282, 291, 61))
self.label_3.setText("")
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(Dialog)
self.label_4.setGeometry(QtCore.QRect(156, 112, 291, 61))
self.label_4.setText("")
self.label_4.setObjectName("label_4")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
self.pushButton.setText(QtWidgets.QApplication.translate("Dialog", "Преобразовать", None, -1))
self.pushButton_2.setText(QtWidgets.QApplication.translate("Dialog", "Преобразовать2", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Dialog", " Перевести из десятичной системы исчисления в двоичную:", None, -1))
self.label_2.setText(QtWidgets.QApplication.translate("Dialog", " Перевести из двоичной системы исчисления в десятичную:", None, -1))
class Bincalc(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Bincalc, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.binarik)
self.pushButton_2.clicked.connect(self.binarik_2)
def binarik(self):
num = int(self.lineEdit.text())
newNum = ''
while num > 0:
newNum = str(num % 2) + newNum
num //= 2
self.label_4.setText(newNum)
def binarik_2(self):
a = self.lineEdit_2.text()
def underdef(digit):
length = len(digit)
helpdig = 0
for i in range(0, int(length)):
helpdig = helpdig + int(digit[i]) * (2**(int(length) - i - 1))
return helpdig
self.label_3.setText(str(underdef(a)))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Bincalc()
w.show()
sys.exit(app.exec_())
Чтобы собрать .exe файл выполните:
pyinstaller -F -w mintro.py
Все запускайте mintro.exe
| {
"pile_set_name": "StackExchange"
} |
Q:
App: use address book to find friends::: How to deal with country codes
I am working on a social network. I need to add a "find-friends" feature based on users' phone number and their address book (like whatsapp and others).
The app I am developing will be available globally and I was wondering how others deal with the problem of predials and country codes. Of course I could find a way around but I am sure this is a relatively common challenge associated with that feature. The problem is, some people save numbers with a country code and some people don't. Do i need two versions of a phone number in my database?
What I think about doing:
1) user registers with the number and types in the country code and the rest of the number separately (two text fields). Then there are two separate columns in the database. One with the whole number including the country code and another with the number excluding the country code.
2) Then another user looks for friends via its address book. In the PHP, each number is checked and the ones that start with "00" are compared against the numbers in the column of the international numbers. Vice versa, the ones that don't start with "00" are compared against the number without the country code. This way users can find their friends irrespective of how they saved their number.
I would appreciate any help, links, advice or direction. I am looking for best practice approaches.
Thanks!
A:
You can format local country phone number to international phone number using this library
libPhoneNumber. It use big data of phones format and country codes.
And then search friends by international phone number.
Example of usage:
NSError* error = nil;
//Parse local phone number using country code from CTCarrier
NBPhoneNumber * phoneNumberObject = [[NBPhoneNumberUtil sharedInstance] parseWithPhoneCarrierRegion: phoneNumber
error: &error];
if(error)
{
//This will get if no CTCarrier info. Maybe iPod, iPhone or iPad without sim
error = nil;
//You may put there another way to get user country code, or use default(Russia in example)
phoneNumberObject = [[NBPhoneNumberUtil sharedInstance] parse: phoneNumber
defaultRegion: @"RU"
error: &error];
}
NSString* formattedInternationalPhoneNumber;
if(!error)
{
formattedInternationalPhoneNumber = [[NBPhoneNumberUtil sharedInstance] format: phoneNumberObject
numberFormat: NBEPhoneNumberFormatE164
error: &error];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ActionScript Preloader More Detailed Percentages
I am building a preloader for a flash application I am building. I am looking for a way to gain more detailed percentages from the ProgressEvent.PROGRESS that all preloaders use to track downloading progress. When I run a trace() statement on the loader percentages for a small file, my output window displays something like this:
4
8
13
17
23 etc...
I am looking for a way to be able to monitor this progress more closely, so I get 1, 2, 3, etc.... If numbers are repeated, that is okay. Parts of my preloader rely on these values, and thus, it would be great to be able to get them from 1 - 100 with no skipped whole numbers.
Thank you for your time.
A:
This doesn't make sense - unless your internet connection loaded exactly 1% of the file at a time.
What's happening is that after each new packet is received, it could be any size based on your download speed (let's say between 200 and 230kb). ProgressEvent.PROGRESS is dispatched each time one of these is received, adding to the total percentage loaded as you would expect.
So basically, let's say we're loading a 1000kb file, and your download speed is 100-150kbps.
Each trace() in your function called on each dispatch of ProgressEvent.PROGRESS will be run when a new packet has been received, so:
100kb loaded - 100 total - traces
10 120kb loaded - 220 total -
traces 22 150kb loaded - 370
total - traces 37
Etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if ConfigurationProperty value is not set
Let's say I have a ConfigurationProperty defined this way:
[ConfigurationProperty("TheProp")]
public double TheProp
{
get{//some code}
set{//some code}
}
How do I check if this ConfigurationProperty has a value or not? DefaultValue will not work in this case, because any double value is a valid value for the configuration property.
A:
You could try making the type of the property 'Nullable':
[ConfigurationProperty("TheProp")]
public double? TheProp
{
get{//some code}
set{//some code}
}
This will allow you to test for if(TheProp.HasValue).
| {
"pile_set_name": "StackExchange"
} |
Q:
Move to a Div/ID from Navbar Link
Ok, So I have a navbar that, when a link is clicked, I want it to move to a specific div (i.e. when clicking the "About" link, the page moves to the About section of the page).
A JSFiddle of the Code in question:
HTML in question:
<nav class="navbar navbar-toggleable-lg sticky-top navbar-inverse bg-inverse">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">David Madrigal's Portfolio</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#About">About</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link projects">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>
The plan is to add classes that would match the id names of the parts of the page I want to go to.
Here is the JS I have so far:
function main() {
$
$('.nav-item').on('click', function() {
$(this).toggleClass('active');
});
}
$(document).ready(main);
Note, I am using Bootstrap 4.0. Any help is much appreciated.Thanks in advance!
A:
Here is a solution with smooth scrolling (the jquery slim libs does not support the animate property)
Snippet below
$('a[href^="#"]').on('click', function(event) {
var target = $(this.getAttribute('href'));
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
});
body {
background: #f5f5dc;
}
.jumbotron {
text-align: center;
background: url(imgs/los-angeles-skyline.jpg);
background-size: cover;
background-repeat: no-repeat;
color: white;
border-radius: 0;
}
#bootstrap-link {
text-decoration: none;
color: white;
}
#bootstrap-link:hover {
text-decoration: underline;
color: #014c8c;
}
#info-cards {
margin-bottom: 20px;
padding-bottom: 5px;
}
#card-blocks {
padding-bottom: 20px;
margin-bottom: 20px;
}
.card-button {
margin-left: 5px;
margin-right: 5px;
}
#form-container {
border: 5px solid rgba(220, 220, 220, 0.4);
margin-top: 10px;
padding: 30px;
padding-bottom: 25px;
background: #ffffff;
}
.form-button {
margin-top: 20px;
}
.footer {
text-align: center;
background-color: #292b2c !important;
padding-bottom: 5px;
padding-top: 20px;
margin-top: 5px;
margin-bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<nav class="navbar navbar-toggleable-lg sticky-top navbar-inverse bg-inverse">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">David Madrigal's Portfolio</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#About">About</a>
</li>
<li class="nav-item">
<a href="#projects" class="nav-link">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron">
<h1 class="display-3">Welcome!</h1>
<p class="lead">This is a site to which I will be adding all of my website works.</p>
<hr class="my-4">
<p>This site uses <a href="https://v4-alpha.getbootstrap.com/" id="bootstrap-link">Bootstrap 4</a> to make the site visually pleasing.</p>
<p class="lead">
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</p>
</div>
<div class="container-fluid" id="About">
<div class="row">
<div class="col-sm-12 div.md-12" id="info-cards About">
<div class="card">
<h3 class="card-header">About the <strong>Developer</strong></h3>
<div class="card-block">
<div class="media">
<img class="d-flex mr-3" src="https://avatars1.githubusercontent.com/u/17634751?v=3&u=764e15995bb82b2f37a3bdb15ba59e11f038a2f1&s=400" alt="githubProfilePic">
<div class="media-body">
<h5 class="mt-0">Welcome to My Portfolio!</h5>
Hello there! This is a personal portfolio of all of my works will be open source and can be changed however you please. Just make sure to provide links to the frameworks used so others can create projects with them!
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid" id="card-blocks projects projects">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="card">
<div class="card-header">
Block #1
</div>
<div class="card-block">
<h4 class="card-title">Special title treatment</h4>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="card">
<div class="card-header">
Featured: "Just Random Musing..."
</div>
<div class="card-block">
<h4 class="card-title">My First Site W/ Bootstrap!</h4>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="https://mexdave1997.github.io/Just-Random-Musings/" class="btn btn-outline-primary card-button">View the Site!</a>
<a href=https://github.com/MEXdave1997/Just-Random-Musings "" class="btn btn-outline-info card-button">View Source!</a>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="card">
<div class="card-header">
Block #2
</div>
<div class="card-block">
<h4 class="card-title">Special title treatment</h4>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid" id="skillbars">
<div class="card">
<h3 class="card-header">Featured Skills</h3>
<div class="card-block">
<p class="card-text">HTML</p>
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: 95%" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100">95%</div>
</div>
<br>
<p class="card-text">CSS</p>
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: 85%" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100">85%</div>
</div>
<br>
<p class="card-text">JavaScript</p>
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" style="width: 65%" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100">65%</div>
</div>
</div>
</div>
</div>
<form class="container-fluid" id="contact">
<div id="form-container">
<div class="form-group row">
<label for="InputName" class="col-4 col-form-label">Full Name</label>
<div class="col-8">
<input type="name" class="form-control" id="InputName" aria-described-by="nameHelp" placeholder="Enter Name" />
<small id="nameHelp" class="form-text text-muted">Please enter your Full Name (First and Last)</small>
</div>
</div>
<div class="form-group row">
<label for="InputEmail" class="col-4 col-form-label">Email Address</label>
<div class="col-8">
<input type="email" class="form-control" id="InputEmail" aria-described-by="emailHelp" placeholder="Enter Email" />
<small id="emailHelp" class="form-text text-muted">We will never share your email with anyone else.</small>
</div>
</div>
<div class="form-group row">
<label for="exampleInputPassword1" class="col-4 col-form-label">Password</label>
<div class="col-8">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
</div>
<button type="button" class="btn btn-primary form-button">Submit</button>
</div>
</form>
<footer class="footer text-muted">
<p>© 2017. David Madrigal-Hernandez.</p>
</footer>
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I apply the same animation to multiple text fields?
I'm creating a method that shakes my UITextField and use POP to do the heavy lifting.
- (void)textFieldErrorAnimation {
POPSpringAnimation *shake = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
shake.springBounciness = 10;
shake.velocity = @(2000);
[self.value.layer pop_addAnimation:shake forKey:@"shakeValue"];
[self.year.layer pop_addAnimation:shake forKey:@"shakeYear"];
}
It seems to be working when I apply the animation to the object "value" but not when it's applied to "value" and "year" at the same time.
I know I can create a shake2, shake3 etc so basically one for each textField but it seems strange that i'd need to do that.
Any ideas how I can reuse this animation?
A:
Of course you can. What I really do about, this kind of reusing animations is creating a method that returns the animation and setting the name and key values correctly.
- (POPSpringAnimation *)popShakeAnimation {
POPSpringAnimation *shakeAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
shakeAnimation.velocity = @2000;
shakeAnimation.springBounciness = 20;
shakeAnimation.name = @"shakeAnimation";
return shakeAnimation;
}
and then whenever I need to shake any views I simply add them to the views' layer.
[self.textfield001.layer pop_addAnimation:[self popShakeAnimation]
forKey:@"shakeAnimation"];
[self.textfield002.layer pop_addAnimation:[self popShakeAnimation]
forKey:@"shakeAnimation"];
[self.textfield003.layer pop_addAnimation:[self popShakeAnimation]
forKey:@"shakeAnimation"];
Just remember to set key values to the name you've created with the animation in the first place.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the explanation of this Medrash about Moshe entering Eretz Yisroel?
The Medrash says that Moshe tells Hashem "it says in your Torah that if a slave says 'I love my master and children and I do not wish to go free' then he stays in his servitude, and I do both". Hashem answers him "do not continue to speak". What is the underlying conversation and explanation of this Medrash?
A:
The question is simple Moshe wants to go into Eretz Yisroel so he wants to stay in Hashem's servitude but the answer Hashem replies can only be understood in the context of the Gemara in Kiddushin (כב, א) there the Gemara explains that in order to enslave himself further he must make this statement twice. Therefore Hashem tells him do not continue to speak for if you do I will be forced to allow you into Eretz Yisroel
| {
"pile_set_name": "StackExchange"
} |
Q:
Are contest-like questions fair game?
https://philosophy.stackexchange.com/questions/25076/can-you-tell-me-plianly-what-is-the-difference-between-truth-and-fact
As far as I can tell, the OP is looking for short answers (as in "number of words can be counted on fingers"). I'm not 100% confident on the value in such an answer, but the format is intriguing. This almost sounds like Philosophy SE's equivalent of code golf.
As a community, would philosophy questions asked in this phrase be valuable? They'd certainly be fun, and that seems like it's worth something.
A:
Fortunately, the question you linked to is a pretty obvious duplicate, so we can close it for that reason.
I think questions in this format are a bad idea, for many reasons:
Answers to questions already are supposed to be as succinct as possible. Answers that are more succinct than possible are therefore (by definition) wrong.
Answers that are on the order of few words are not likely to actually be philosophy, they are more likely to be the sort of thing that people put on a bumper sticker. Rather than opening up participants in the community to understand philosophy better, they are a way of shutting down conversations.
The idea is incredibly presumptuous: I can tell the difference between fact and truth in six words, can you? Well, Plato, Cicero, Augustine, and so on either couldn't or decided not to.
This question at least sounds more like a riddle than a search for wisdom.
The original asker proposes his "six word solution"... and then needs to spend a whole paragraph explaining why his six word solution makes sense (that his answer itself is entirely just his own opinion is a whole other issue). Therefore, the actual length of his answer is not six words, it's a paragraph.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to programmatically invoke zoom event in MatLab?
I am using "plot_google_map.m" that uses the Google Maps API to plot a map in the background of the current figure. A figure generated with this auto-refreshes the map upon zooming event, and I added some codes to make it refresh data upon panning event, too.
Now I would like to programmatically change the range of axes without using zoom or pan buttons, but the problem is map is not refreshed automatically. So, I am thinking of generating zooming or panning event programatically, but I haven't found a way to do that.
Any idea on this?
Let me elaborate my question.
In the 'plot_google_map.m', there is subfunction which is a callback of zooming event.
function plot_google_map
% Listen to Zoom events
h = figure(1); plot(1:10);
hz = zoom(h);
set(hz,'ActionPostCallback',@mypostcallback);
function mypostcallback(obj,evd)
disp('Refreshes map data');
What I want to do is, to call this subfunction outside the 'plot_google_map'.
Any idea is welcomed, and thank you for your answers in advance!
A:
You heard about the zoom command?
>> help zoom
zoom Zoom in and out on a 2-D plot.
Actually it seems that's how the program recognizes you zooming.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generic types comparison
I have two objects of generic type T.
T x , T y
I want to be able to do comparison like:
if (x >= y)
Therefore I try to use the compareTo method which is missing until I add the constraint where T:IComparable. Only then I see it in the intellisence.
Not sure why only then I see it and not before writing it.
A:
Not sure why only then I see it and not before writing it.
Because until that constraint exists, the compiler has no idea what members are available on T, other than those which are present as part of object. You wouldn't expect to be able to write:
object x = GetObjectFromSomewhere();
object y = GetObjectFromSomewhere();
int comparison = x.CompareTo(y);
would you? C# is a statically typed language (aside from dynamic) - the compiler has to know which members you're talking about when you use them.
As an aside, if the types you're interested in implement IComparable<T> rather than just the non-generic IComparable, that would be a better constraint. It performs better (because it can avoid boxing) and it's more type-safe (as it prevents you from trying to compare unrelated types).
| {
"pile_set_name": "StackExchange"
} |
Q:
Deserialize JSON in Dictionary in Web Api: always empty string
I have such JSON string: {"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
return null;
}
But rawJson always is empty string. I don't understand why?
But d1.Length is the same as in JSON string. I don't know how to get JSON string from d1...
Thank you!
A:
use content type parameter instead of dataType when performing ajax call:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Keep element always centered with side text to the left
I need help to structure a page, i thought it was easy but it wasn't, at least not for me.
Logo: always centered, of course.
Element: For instance, an image, always centered. Image can be vertical or horizontal, but needs to be centered.
Text: Next to the element/image.
There are no boxes really, i saw other questions where they where trying to keep center box always centered, but in this case i just have one main box/container and then text/caption next to the image.
What i cannot do is keeping image centered, because if i add text next to the image, will try to center the whole thing.
Thanks!
A:
Horizontal and vertical centering is most easily solved with flexbox. Simply set the following on your container:
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
Note that you'll want a height too! I've gone with 100vh to occupy the full viewport.
To centralise your element at the top just give it align-self: flex-start.
From here it's just a matter of having a child which contains both the central item and offset item, both of which need position: absolute. The offset item will additionally want margin-left equal to the width of the centralised item, but it should only be applied inside of a media query.
To drop the offset item below for mobile screens, you'll want a second media query which adds margin-top.
This can be seen in the following (click Full page after Run code snippet to see the desktop view).
body {
margin: 0;
}
.container {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
height: 100vh;
}
.top {
border: 1px solid black;
width: 50%;
height: 10%;
align-self: flex-start;
}
.inner-container {
border: 1px solid black;
width: 50%;
height: 50%
}
.center, .off-center {
position: absolute;
}
@media screen and (min-width: 769px) {
.off-center {
margin-left: 50%;
}
}
@media screen and (max-width: 768px) {
.off-center {
margin-top: 50vh;
}
}
<div class="container">
<div class="top">Logo</div>
<div class="inner-container">
<div class="center">Center</div>
<div class="off-center">Off-center</div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
how to prevent SQL Injection in a asp.net website
For email entry in a text box by the user i am doing client side check, to find whether the email is valid or not
string emailexist = "SELECT COUNT(DISTINCT UserID) as count FROM tbl_user WHERE Email=@Email ";
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" ValidationGroup="Login" ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" CssClass="Error"
runat="server" />
is this regular expression good enough to prevent sql injection for email.
Other Text:
string groupExistQuery = "SELECT COUNT(DISTINCT GroupID) as count FROM tbl_group WHERE GroupName=@GroupName";
I am doing a query in server side to check whether the group name entered by the user is already available in the database, there is a strong possibility to perform sql injection here. How should I prevent from it.
A:
A regex is unrelated to SQL injection (blacklisting etc is never the strongest approach); however, the use of the parameter @Email means (assuming it remains parameterised) that is not susceptible to SQL injection.
SQL injection relates to inappropriate concatenation of input; the main tool to fight it is parameters, which has already happened here.
For example, if you did:
var sql = "SELECT ...snip... WHERE Email='" + email + "'"; // BAD!!!!!
then that is heavily susceptible to SQL injection. By using a parameter, the value is not treated as part of the query, so the attacker does not have at attack vector.
A:
If you use parameterised values, you are going to be fine regardless, you can not inject via parameters, only via concatenated values.
A:
You can prevent it by not using Direct SQL and using parameterised queries and/or Stored Procedures instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add multiple elements to a single var and detect if any of those are clicked?
I have a page that can have one of three possible elements. I would like to assign whatever element exists to a var and then check if the var is clicked.
I tried using the add(), but it has confused me:
var testingVar = $('#element-one').find('.object').add('#element-two').find('.object').add('#element-three').find('.object');
$(testingVar ).click(function() {
alert('works');
});
It seems to me that the add() overwrites the previous add()? if I am on a page that has #element-three, it works, if on a page with element-one or element-two, it doesn't. If I change the var to
var testingVar = $('#element-one').find('.object');
Then a page with element-one works.
Can someone help me understand how to use the add() properly in this case?
Thanks
A:
I think what you're looking for is this:
$('#element-one .object').add('#element-two .object').add('#element-three .object');
.find() returns a new jquery object.
However, I think this would be easier in this case:
$('#element-one .object, #element-two .object, #element-three .object');
Or even easier, if you can change markup, is to give each element you're currently selecting by id a common class, and do this:
$('.common-class .object')
| {
"pile_set_name": "StackExchange"
} |
Q:
Is std::move(*this) a good pattern?
In order to make this code with C++11 reference qualifiers work as expected I have to introduce a std::move(*this) that doesn't sound right.
#include<iostream>
struct A{
void gun() const&{std::cout << "gun const&" << std::endl;}
void gun() &&{std::cout << "gun&&" << std::endl;}
void fun() const&{gun();}
void fun() &&{std::move(*this).gun();} // <-- is this correct? or is there a better option
};
int main(){
A a; a.fun(); // prints gun const&
A().fun(); // prints gun&&
}
Something doesn't sound right about it. Is the std::move necessary? Is this a recommended use for it? For the moment if I don't use it I get gun const& in both cases which is not the expected result.
(It seems that *this is implicit and lvalue reference always, which makes sense but then the only way to escape to use move)
Tested with clang 3.4 and gcc 4.8.3.
EDIT: This is what I understand from @hvd answer:
1) std::move(*this) is syntactically and conceptually correct
2) However, if gun is not part of the desired interface, there no reason to overload the lv-ref and rv-ref version of it. And two functions with different names can do the same job. After all the ref-qualifiers matters at the interface level, which is generally only the public part.
struct A{
private:
void gun() const{std::cout << "gun const&" << std::endl;}
void gun_rv(){std::cout << "gun called from fun&&" << std::endl;}
public:
void fun() const&{gun();}
void fun() &&{gun_rv();} // no need for `std::move(*this)`.
};
But again, if gun is part of the (generic) interface then std::move(*this) is necessary, but only then. And also, even if gun is not part of the interface there readability advantages in not splitting the function gun as two differently named function and the cost of this is, well..., std::move(*this).
EDIT 2: In retrospect this is similar to the C++98 case of const and no-const overload of the same function. In some cases it makes sense to use const_cast (another form of cast) to not repeat code and have the two functions with the same name (https://stackoverflow.com/a/124209/225186)
A:
Yes, *this is always an lvalue, no matter how a member function is called, so if you want the compiler to treat it as an rvalue, you need to use std::move or equivalent. It has to be, considering this class:
struct A {
void gun() &; // leaves object usable
void gun() &&; // makes object unusable
void fun() && {
gun();
gun();
}
};
Making *this an rvalue would suggest that fun's first call to gun can leave the object unusable. The second call would then fail, possibly badly. This is not something that should happen implicitly.
This is the same reason why inside void f(T&& t), t is an lvalue. In that respect, *this is no different from any reference function parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the domain of convergence change after this integration?
So, while trying to derive the Taylor expansion for $\ln(x+1)$ around $x=0$, I started by using the well-known power series:
$$\frac{1}{1-x}=1+x+x^2 +x^3 +... \qquad \text{when } \lvert x \rvert < 1$$
Letting $x \mapsto-x$, we get:
$$\frac{1}{1+x}=1-x+x^2 -x^3 + ... \qquad \text{when } \lvert x \rvert < 1$$
So then perfoming this integration gives us:
$$\begin{align*}
\ln(1+x) = \int_0^x \frac{dt}{1+t} &=\int_0^x (1-t+t^2-t^3+...)dt \\
&= x-\frac{x^2}{2}+\frac{x^3}{3}- \frac{x^4}{4} +... \qquad \text{when } \vert x \rvert<1
\end{align*}$$
However, the real domain of convergence for this is $-1 < x \leq 1$ as $\ln(2) = 1- \frac{1}{2} +\frac{1}{3} - \frac{1}{4}+ ...$
So my question is why did the domain over which the original function converges in change after this integration and is there a way to predict when this happens given some power series, or should one always check the endpoints again?
A:
Writing
$$\tag{*}\ln(1+x) = \int_0^x \frac{dt}{1+t} =\int_0^x (1-t+t^2-t^3+...)\,dt \\ = x-\frac{x^2}{2}+\frac{x^3}{3}- \frac{x^4}{4} + \ldots $$
is true for $x < 1$ because the power series converges uniformly on the compact interval $[0,x]$ (within the interval $(-1,1)$ bounded by the radius of convergence) and termwise integration is permissible.
The series $1-t+t^2-t^3+...$ is neither pointwise convergent at $t=1$ nor uniformly convergent on $[0,1)$.
As much as one might like to simply substitute $1$ for $x$ in (*) and conclude that
$$\tag{**} \ln 2 = 1-\frac{1}{2}+\frac{1}{3}- \frac{1}{4} + \ldots ,$$
it cannot be justifed without further analysis, i.e. there are other examples of this type where it would be false.
In this case, however, we can establish that the series on the RHS of (**) is convergent by the alternating series test and by Abel's theorem it follows that
$$\ln 2 = \lim_{x \to 1-} \ln(1+x) = 1-\frac{1}{2}+\frac{1}{3}- \frac{1}{4} + \ldots $$
Again -- knowing only the radius of convergence is not enough information to establish this result.
| {
"pile_set_name": "StackExchange"
} |
Q:
What's the command that Kirk gives when he turns over command?
Which is correct, A or B? As he turns over the command, Kirk says
A) 'You have the COM' [as in Command]
or
B) You have the CONN.' [as in ???]
I've always assumed the former, A, is correct, but a recent television commercial for the new Star Trek app, claims B, which has left me thoroughly confused.
A:
The command is "you have the conn", as can be seen in this original screenplay from Star Trek: The Motion Picture
KIRK: Mr. Decker, I'd like to see you in my quarters.
(toward helm)
You have the conn, Mr. Sulu.
The term "conn" is a naval/nautical expression;
One of the most important principles of ship handling is that there be
no ambiguity as to who is controlling the movements of the ship. One
person gives orders to the ship's engine, rudder, lines, and ground
tackle. This person is said to have the "conn."
— James Alden Barber, 2005, "Introduction", The Naval Shiphandler's Guide, p. 8.
The etymology is lost, but it may have something to do with the conduct of the vessel.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a better way to get the Camera pixels than onPreviewFrame on Android?
onPreviewFrame only gets called when the preview frames from the camera get displayed. I'm processing the image as an open gl texture using the same technique here:
http://nhenze.net/?p=172&cpage=1#comment-8424
But it seems like a waste to render the preview to the screen just so I can draw over it with my textured image. Is there a better way to get the pixels from the camera than during the call to onPreviewFrame?
A:
yes, you can use a SurfaceTexture. There's some mild trickiness here as it needs to be an external texture not the normal 2D texture.
This means that if you render the texture with ES2 you need some like
#extension GL_OES_EGL_image_external : require
uniform samplerExternalOES s_texture;
in the fragment shader.
Example code:
int[] textures = new int[1];
// generate one texture pointer and bind it as an external texture.
GLES20.glGenTextures(1, textures, 0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textures[0]);
// No mip-mapping with camera source.
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
// Clamp to edge is only option.
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
int texture_id = textures[0];
SurfaceTexture mTexture = new SurfaceTexture(texture_id);
mTexture.setOnFrameAvailableListener(this);
Camera cam = Camera.open();
cam.setPreviewTexture(mTexture);
| {
"pile_set_name": "StackExchange"
} |
Q:
What style of lager is Corona? And what other beers are similar?
Corona Extra is a Mexican beer that is very popular (in Australia anyway). Most people seem to like it for it's drinkability, and suitability for enjoyment in hot weather.
Is there a name for this style of lager? Eg; I don't think it's a pilsener or dark lager.
And what other beers are in the same style?
A:
The BJCP classifies Corona Extra as a Premium American Lager, being, clear, yellow, not hoppy but with a little more body than a light.
Assuming 'dry' isn't some radically different beer, the category would probably still be correct. BJCP draft guidelines (not official) consider putting Asahi Super Dry and Corona Extra in 2A 'International Pale Lagers' which is 'Loosely derived from original Pilsner-type lagers....'
1MB PDF if you want to read the draft.
| {
"pile_set_name": "StackExchange"
} |
Q:
How would you design an AppEngine datastore for a social site like Twitter?
I'm wondering what would be the best way to design a social application where members make activities and follow other member's activities using Google AppEngine.
To be more specific lets assume we have these entities:
Users who have friends
Activities which represent actions made by users (lets say each has a string message and a ReferenceProperty to its owner user, or it can use parent association via appengine's key)
The hard part is following your friend's activities, which means aggregating the latest activities from all your friends.
Normally, that would be a join between the Activities table and your friends list but thats not a viable design on appengine as there are no join simulating it will require firing up N queries (where N is number of friends) and then merging in memory - very expensive and will probably exceed request deadline...)
I'm currently thinking of implementing this using inbox queues where creation of a new Activity will fire a background process that will put the new activity's key in the "inbox" of every following user:
Getting "All the users who follow X" is a possible appengine query
Not a very expensive batch input into a new "Inbox" entity that basically stores (User, Activity Key) tuples.
I'll be happy to heard thought on this design or alternative suggestions etc.
A:
Take a look at Building Scalable, Complex Apps on App Engine (pdf), a fascinating talk given at Google I/O by Brett Slatkin. He addresses the problem of building a scalable messaging service like Twitter.
Here's his solution using a list property:
class Message(db.Model):
sender = db.StringProperty()
body = db.TextProperty()
class MessageIndex(db.Model):
#parent = a message
receivers = db.StringListProperty()
indexes = MessageIndex.all(keys_only = True).filter('receivers = ', user_id)
keys = [k.parent() for k in indexes)
messages = db.get(keys)
This key only query finds the message indices with a receiver equal to the one you specified without deserializing and serializing the list of receivers. Then you use these indices to only grab the messages that you want.
Here's the wrong way to do it:
class Message(db.Model):
sender = db.StringProperty()
receivers = db.StringListProperty()
body = db.TextProperty()
messages = Message.all().filter('receivers =', user_id)
This is inefficient because queries have to unpackage all of the results returned by your query. So if you returned 100 messages with 1,000 users in each receivers list you'd have to deserialize 100,000 (100 x 1000) list property values. Way too expensive in datastore latency and cpu.
I was pretty confused by all of this at first, so I wrote up a short tutorial about using the list property. Enjoy :)
A:
I don't know whether it is the best design for a social application, but jaiku was ported to App Engine by it's original creator when the company was acquired by Google, so it should be reasonable.
See the section Actors and Tigers and Bears, Oh My! in design_funument.txt. The entities are defined in common/models.py and the queries are in common/api.py.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find if something was committed every 6 months
I have a request for a query and its throwing me for a loop here.
Scope: Build a report that will tell us if a taskey was used every 6 months
I.e. Sally made report x this month, she needs to make that report again with in 6 months.
I need the report that tells me which ones are out of the range and which ones where out of the range.
I just need a count.
So I made this view
SELECT ed.eventkey,
ed.contactkey,
ed.wfstagekey,
ed.contact1id,
ed.contact2id,
ed.startdate,
ed.enddate,
ed.eventstatusid,
ed.activeind,
ed.modifiedbyid,
ed.modifieddate,
ed.ScheduledDate
FROM STMA_CM.dbo.eventdefinition ed
WHERE ( (ed.wftaskkey = 120 AND year (ed.enddate) = 2013)
AND ed.eventstatusid IN (15, 16)) and activeind=1
And did this to try and get and understadning but it only gave me the ones in compliance
select * from (select * from {{POC}} where month(enddate)=1) as A
left join (select * from {{POC}} where month(enddate)=2) as b on b.contactkey=a.contactkey
left join (select * from {{POC}} where month(enddate)=3) as c on c.contactkey=a.contactkey
left join (select * from {{POC}} where month(enddate)=4) as d on d.contactkey=a.contactkey
left join (select * from {{POC}} where month(enddate)=5) as e on e.contactkey=a.contactkey
left join (select * from {{POC}} where month(enddate)=6) as f on f.contactkey=a.contactkey
left join (select * from {{POC}} where month(enddate)=7) as g on g.contactkey=a.contactkey
I tried some dynimic sql but it wasnt working either.
BEGIN
DECLARE @ckey INT,
@ekey INT,
@cstat INT,
@ustat INT,
@pocdate1 DATETIME,
@pocdate2 DATETIME,
@pocdate3 DATETIME,
@pcount INT,
@ecount INT,
@pcdate DATETIME,
@dcdate DATETIME
DROP TABLE #yractive
CREATE TABLE #yractive(
contactkey INT,
pcdate DATETIME,
dcdate DATETIME,
branch VARCHAR(100),
numpoc INT,
pocupdate1 DATETIME,
pocupdate2 DATETIME,
pocupdate3 DATETIME,
msg VARCHAR(1000))
INSERT INTO #yractive(contactkey)
SELECT c.contactkey
FROM contact c LEFT OUTER JOIN dbo.ContactRole cr
ON c.contactkey=cr.contactkey
WHERE c.activeind=1 AND cr.rolekey=8
AND dbo.getContactBranch(c.contactkey) LIKE 'MA%'
AND (YEAR(dbo.getwftaskDate(c.contactkey, 6,75))=2013
OR dbo.getContactStatus(c.contactkey,'ts')IN ('Placed','Suspension'))
DECLARE c_poc CURSOR FAST_FORWARD FOR
SELECT contactkey
FROM #yractive
FOR READ ONLY
OPEN c_poc
FETCH NEXT FROM c_poc
INTO @ckey
SELECT @cstat=@@FETCH_STATUS
WHILE @cstat<>-1
BEGIN
IF @cstat<>-2
BEGIN
SET @pcount=0
SELECT @pcount=COUNT(*)
FROM dbo.eventdefinition
WHERE wftaskkey=120
AND eventstatusid =16
AND contactkey=@ckey
AND enddate > '2013-01-01'
UPDATE #yractive
SET numpoc=@pcount
WHERE contactkey=@ckey
SELECT @pcdate=MAX(wfdate)
FROM dbo.contactworkflow
WHERE contactkey=@ckey AND wfstagekey=4 AND wftaskkey=49
UPDATE #yractive
SET pcdate=@pcdate
WHERE contactkey=@ckey
SELECT @dcdate=MAX(wfdate)
FROM dbo.contactworkflow
WHERE contactkey=@ckey AND wfstagekey=6 AND wftaskkey=75
UPDATE #yractive
SET dcdate=@dcdate
WHERE contactkey=@ckey
IF @pcount>3
BEGIN
UPDATE #yractive
SET msg='# of pocs for this year exceeds '+LTRIM(RTRIM(CAST(@pcount AS VARCHAR(2))))
WHERE contactkey=@ckey
END
IF @pcount>0
BEGIN
DECLARE c_upd CURSOR FAST_FORWARD FOR
SELECT eventkey
FROM dbo.eventdefinition
WHERE wftaskkey=120
AND eventstatusid =16
AND contactkey=@ckey
AND enddate > '2013-01-01'
ORDER BY enddate DESC
FOR READ ONLY
OPEN c_upd
FETCH NEXT FROM c_upd
INTO @ekey
SELECT @ustat=@@FETCH_STATUS
SET @pocdate1=''
SET @pocdate2=''
SET @pocdate3=''
SET @ecount=1
WHILE @ustat<>-1
BEGIN
IF @ustat<>-2
BEGIN
IF @ecount <= @pcount
BEGIN
IF @ecount=1
BEGIN
SELECT @pocdate1=enddate
FROM dbo.eventdefinition
WHERE eventkey=@ekey
UPDATE #yractive
SET pocupdate1=@pocdate1
WHERE contactkey=@ckey
END
IF @ecount=2
BEGIN
SELECT @pocdate2=enddate
FROM dbo.eventdefinition
WHERE eventkey=@ekey
UPDATE #yractive
SET pocupdate2=@pocdate2
WHERE contactkey=@ckey
END
IF @ecount=3
BEGIN
SELECT @pocdate3=enddate
FROM dbo.eventdefinition
WHERE eventkey=@ekey
UPDATE #yractive
SET pocupdate3=@pocdate3
WHERE contactkey=@ckey
END
END
SET @ecount=@ecount+1
END
FETCH NEXT FROM c_upd
INTO @ekey
SELECT @ustat=@@FETCH_STATUS
END
CLOSE c_upd
DEALLOCATE c_upd
END
FETCH NEXT FROM c_poc
INTO @ckey
SELECT @cstat=@@FETCH_STATUS
END
END
CLOSE c_poc
DEALLOCATE c_poc
SELECT * FROM #yractive
END
A:
This is how I did it. Got me what i wanted using the partion helped out alot.
select c.contactkey,c.firstname, c. lastname , ed2.enddate'second most recent', ed.enddate'most recent'
from STMA_CM.dbo.contact c
inner join (select * from
(select *,RANK() over (PARTITION BY contactkey order by enddate desc) as 'rn'
from eventdefinition
where wftaskkey in( 120) and eventstatusid=16) as s
where s.rn =1) ed on ed.contactkey = c.contactkey
left join (select * from
(select *,RANK() over (PARTITION BY contactkey order by enddate desc) as 'rn'
from eventdefinition
where wftaskkey in (173,120) and eventstatusid=16) as s
where s.rn =2) ed2 on ed2.contactkey = c.contactkey
WHERE ed.activeind=1 and ed2.activeind=1 order by contactkey
| {
"pile_set_name": "StackExchange"
} |
Q:
Django ImportError for models.py
(Updating my question with more information.)
My django app is running fine on my dev server.
I have a view that pulls from the database using the below line that works fine:
from myapp.models import MyTable
However, if I add the above 'from/import' to another module (see below structure, it's the module named 'problem_module.py') I'm writing where I want to pull from the sqlite3 database, I get this error.
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myfolder.settings' (Is it on sys.path?): No module named myfolder.settings
I've read and tried various solutions recommended when people get this error, but I missing something because i'm unable to resolve it.
I'm using Django 1.4 and have the lay-out as recommended.
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
models.py
admin.py
views.py
indevelopment/
__init__.py
problem_module.py
A:
I figured out what was happening and why after going through the traceback carefully and looking at the django source code. Here is what happens.
When you run:
python manage.py runserver
the environment variable gets set properly assuming you already changed this small little file or just don't pay attention to it because django 1.4 automatically configures it for you.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
However, because this setting of os.environ is under a:
if __name__ = "__main__"
expression, it only gets run if call that file directly, as you do with:
python manage.py runserver
Otherwise, if you are running a file that needs that environment variable - say testing a module in Eclipse - , the os.environ needs to get set in another place (shell, etc).
All the that I got generally pointed to this but I needed the context.
But as a little adjustment (yes, not a good idea as it couples) on the source code you can also hardcode it in manually in/django/conf/__init__.py
Specifically to see where it happens, the change below works:
# in module: /django/conf/__init__.py
class LazySettings(LazyObject):
def _setup(self):
try:
# Comment out the call to os.environ and hardcode in your app settings
# settings_module = os.environ[ENVIRONMENT_VARIABLE]
# WARNING: bad practice to do this. ;.
settings_module = "myapp.settings"
| {
"pile_set_name": "StackExchange"
} |
Q:
c++, object created on the heap vs. local - when returning a pointer
This is a follow up question from
Safe in C# not in C++, simple return of pointer / reference,
Is this:
person* NewPerson(void)
{
person p;
/* ... */
return &p; //return pointer to person.
}
the same as?
person* NewPerson(void)
{
person* pp = new person;
return pp; //return pointer to person.
}
I know that the first one is a bad idea, because it will be a wild pointer.
In the second case, will the object be safe on the heap - and like in c#
go out of scope when the last reference is gone to it?
A:
Yes, the second case is safe.
But the caller will need to delete the returned pointer. You could change this to use boost::shared_ptr and it will be destroyed when it is no longer in use:
boost::shared_ptr<person> NewPerson()
{
boost::shared_ptr<person> pp = boost::make_shared<person>();
return pp;
}
If C++11 then you can use std::shared_ptr or std::unique_ptr.
A:
It's safe, the object will still be alive after the return.
But don't expect the object to be automatically cleaned up for you in C++. Standard C++ does not have garbage collection. You'll need to delete the object yourself, or use some form of smart pointer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arrray of objects store same attributes in key
I'm creating a javascript array of objects. Inside the objects i want one key with all the attributes associated with that key in the same bucket.
For example food[{fruits: 'apples', 'bananas'}, {spices: 'chili', 'cajun'}]
If the key is unique then add to the array otherwise just place in the same bucket.
Code below
$('.options li').each(function() {
$name = $(this).parent().attr('id');
$attr = $(this).attr('data-attr');
food[$name] = $attr;
});
Here is what i have code wise https://jsfiddle.net/fqyt18y7/
A:
Working Fiddle
To achieve this, you need to store each keyword with an array of its elements. Something like this should do the trick:
$('.options li').each(function() {
$name = $(this).parent().attr('id');
$attr = $(this).attr('data-attr');
// Check to see if this keyword has been used before
// because if not, we need to store an empty array there
if(typeof food[$name] === 'undefined'){
food[$name] = [];
}
// Add our element to that array
food[$name].push($attr);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I mutate a value in a genetic algorithm using Gaussian distribution?
I've been reading 'Introduction to Evolutionary Algorithms'. This method is stated, but not described, and I can't find anything more specific online. p44/45 of 2nd Ed for reference.
adding to the current gene value an amount drawn randomly from a Gaussian distribution with mean zero and user-specified standard deviation
Would be great to get the step by step, from initial to mutated value, including how Gaussian distribution works (or a link to something that could fill that gap).
A:
A gaussian distribution is that favorite curve from math and stats also known as the bell curve or a normal distribution.
An example of this can be seen with the sum of rolling 10x 10 sided dice:
From AnyDice output 10d10
What this means is that the amount of mutation for a gene is most likely very little. If you roll this set of dice 30 times, you'll get some data that looks like:
53, 38, 52, 62, 51, 50, 71, 44, 52, 55, 56, 45, 48, 67, 48, 63, 33, 40, 62, 60, 54, 48, 67, 60, 44, 63, 50, 50, 64, 56
Notice that most of these numbers are fairly close to the value of 55. Thats the key to this - you want a middle value.
When doing a mutation on a gene that has a possible change of -10 .. +10 you want most of the chance to be about 0. Maybe some 1s, or 2s, or -1s, or -2s... but you don't want a +10 to have an equal chance of a mutation as a +1.
So? How do you do this?
In Java, one would use java.util.Random#nextGaussian(). That will give you a number that has a normal distribution with a mean of 0.0.
You would take the value you get from nextGaussian(), and then... well, do math to it to get it into the range you want. Just because you're getting a number with a mean of 0.0 doesn't mean that any given value will be in a certain range.
The specifics of the nextGaussian() for your chosen language is just a matter of finding the right library for the language. Its there somewhere. You may wish to browse the tag: normal-distribution on Stack Overflow filtered for your language to see if any of those questions specifically help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Actionscript 3: How do I get date from server (not client)
I am working on a Christmas calendar for my school, when I noticed that, the Date-class is not what I though it was.
It gets the time from the client CPU, and that won't do.
So, I been looking around on the web, but there have been no good answers (at least that I could make any sense of).
So here it is:
How do i get the time and date (*) in UTC +1, from the server my flash-program are hosted, or some external time-server?
*In UNIX-time, or somehow else actionscript 3 can understand
My search for answers had suggestions for some php-scripts, but i don't understand how to use that (there where a few examples, but they where in AS2).
A:
A more secure way of doing this (eg not using flash vars which can be tampered with), would be to create a very simple server page (outputs plain text instead of html) that outputs the date, then load that into flash with a loader and parse it into a native Date object.
The flash side would look like this:
var loader:URLLoader = new URLLoader()
loader.load(new URLRequest("your server page"))
loader.addEventListener(Event.COMPLETE, onLoaded)
function onLoaded(evt:Event){
var date:Date;
try{
date = new Date(Number(loader.data)); //need to cast the loader data as a number
}catch(e:Error){
}
if(!date){
//your output from the server isn't formatted in a way flash can convert it
date = new Date(); //use local time
}
}
The reason for using try/catch, is because if output from the server isn't a valid date it will throw an error when trying to convert it. If an error is thrown anywhere inside of a try block, it will exit at the line of the error (skip the rest of the code) and run what is in the catch block. If there is no error in the try block, the code in the catch block will never run.
With PHP (though I don't have php anywhere handy to check so this may need to be corrected by someone, and it's been about 10 years since I've programmed with it)
<?php
header("Content-Type: text/plain");
print time() * 1000;
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Uso de CONCAT, CONCAT_WS e GROUP_CONCAT
Estou construindo uma query em que procuro resultados dentro da concatenação e apanhei o bastante para pedir ajuda. Utilizo atualmente o MySQL com a aplicação em PHP.
No exemplo abaixo, busco as palavras "F1000" e "GRID" numa concatenação de colunas de ambas as tabelas. O produto pode, ou não, ter uma grade.
SELECT p.id,
p.id_maker,
p.name,
p.description,
p.specifications
FROM product AS p
WHERE CONCAT(
CONCAT_WS(
' ',
p.name,
p.description,
p.specifications
), ', ',
GROUP_CONCAT(
(
SELECT CONCAT_WS(
' ',
g.description,
g.original_cod_maker
)
FROM product_grid AS g
WHERE g.fk_son = p.id
)
SEPARATOR ', ')
)
REGEXP '(.*)GRID(.*)F1000(.*)'
Esta query apresenta erro 1111 (invalid use of group function) referente ao uso dos métodos de concatenação.
Agradeço desde já por sua ajuda.
A:
O comando GROUP_CONCAT serve para concatenar grupos quando se utiliza funções de agregação como SUM, MAX, AVG, etc.
Para a sua consulta, você pode apenas pesquisar dentro dos campos diretamente. Uma sugestão de query:
SELECT p.id,
p.id_maker,
p.name,
p.description,
p.specifications
FROM product AS p
LEFT JOIN product_grid AS g
ON (p.id = g.fk_son)
WHERE (
p.name LIKE '%GRID%' OR p.name LIKE '%F1000%'
OR
p.description LIKE '%GRID%' OR p.description LIKE '%F1000%'
OR
p.specifications LIKE '%GRID%' OR p.specifications LIKE '%F1000%'
OR
g.description LIKE '%GRID%' OR g.description LIKE '%F1000%'
OR
g.original_cod_maker LIKE '%GRID%' OR g.original_cod_maker LIKE '%F1000%'
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Get DateTime object given local time as string, date as UTC DateTime and a timezone-locale string?
I'm working with data from several sources, and I need to put together an accurate DateTime.
I have:
A) a string representing a time of day, e.g.: "4:00 pm"
B) a DateTime object intended to represent a pure date, by having been created as midnight, zulu time (offset of 00:00) for a particular date.
C) a string representing a timezone locale, e.g.: "America/Los_Angeles"
How do I get a precise DateTime object, with correct number of ticks, representing the time (A) experienced in that locale (C), on that date (B)??
A:
Here you have an example using NodaTime, which is more reliable of any of the framework classes when dealing with calendars, time zones, dates and times:
var timeString = "4:00 pm";
var pureDate = new DateTime(2017, 5, 22, 0, 0, 0, DateTimeKind.Utc);
var timezoneString = "America/Los_Angeles";
var localTime = ParseTimeString(timeString);
var localDate = LocalDate.FromDateTime(pureDate);
var localDateTime = localDate.At(localTime);
var zone = DateTimeZoneProviders.Tzdb[timezoneString];
var zonedDateTime = localDateTime.InZoneStrictly(zone);
Inside zonedDateTime you will find your full date:
"2017-05-22T16:00:00 America/Los_Angeles (-07)"
You may than use zonedDateTime.ToDateTimeUtc() to get a System.DateTime instance in UTC.
ParseTimeString parses your time string using your format specifier:
public static LocalTime ParseTimeString(string timeString)
{
var pattern = LocalTimePattern.CreateWithInvariantCulture("h:mm tt");
return pattern.Parse(timeString).Value;
}
Considerations if you use DateTime, DateTimeOffset and TimeZoneInfo
If you do not want to use NodaTime be aware of the possible pitfalls of the built-in classes:
TimeZoneInfo in Windows uses a different specifier that is not compatible with IANA/TZDB. Your America/Los_Angeles time zone string will not work if you do not convert it before use (see https://stackoverflow.com/tags/timezone/info)
DateTimeOffset (which is more reliable then DateTime) still loses information when created. The time zone data cannot be persisted and you will have just a date with an offset from UTC.
You'll need to manually parse your custom time string (maybe using regexes).
| {
"pile_set_name": "StackExchange"
} |
Q:
Can py.test support multiple -k options?
Can py.test supports multiple -k options?
Each testcase belongs to a particular group such as _eventnotification or _interface, etc.
Is it possible to run test cases that belong to either one or both at the same time?
ie, run testcases that has _eventnotification or _interface in the name at the same time.
I tried the following and only the testcases with _interface were executed.
If that is not supported, is there another way to do this?
py.test -k "_eventnotification" -k "_interface"
A:
The bad news: pytest-2.3.3 does not support it.
The good news: i took your question as an opportunity to finally enhance "-k" behaviour, so that you can use "not", "or", "end" etc, see the [extended -k example][1]. It works now like "-m" except that it matches on (substrings of) test names, not markers. You can use this in-development pytest version with "pip install -i http://pypi.testrun.org -U pytest".
| {
"pile_set_name": "StackExchange"
} |
Q:
add product title into product tabs
I am trying to add the product title and short description within the product tabs on the luma theme. With short description, I am happy to use the move object to place this into the tabs but I need to style it with a tag, with the product title I want to replicate this so I will have it as a h1 and h3. Below is the code I have added to description.phtml but I cannot get this to render correctly
<h3><?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getName())) ?></h3>
<h4><?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getShortDescription())) ?></h4>
<?= /* @escapeNotVerified */ $this->helper('Magento\Catalog\Helper\Output')->productAttribute($block->getProduct(), $block->getProduct()->getDescription(), 'description') ?>
A:
I ended up getting this working but adding following to details.phtml
<div class="data item content" id="<?= /* @escapeNotVerified */ $alias ?>" data-role="content">
<?php if ($alias === 'description') { ?>
<h3 class="page-title"><span class="base"><?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getName())) ?></span></h3>
<h4><?= $block->escapeHtmlAttr($block->stripTags($block->getProduct()->getShortDescription())) ?></h4>
<?php } ?>
<?= /* @escapeNotVerified */ $html ?>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
XSL How to sum elements in different nodes
I need to sum elements from different nodes. I tried to write different variation of codes but it seems, that I'll missing something important here. Here is my simplified XML file:
<documents>
<document>
<rows>
<row>
<name>apple</name>
<amount>10</amount>
</row>
<row>
<name>carrot</name>
<amount>10</amount>
</row>
</rows>
<client_name>customer_x</client_name>
</document>
<document>
<rows>
<row>
<name>banana</name>
<amount>20</amount>
</row>
</rows>
<client_name>customer_x</client_name>
</document>
<document>
<rows>
<row>
<name>banana</name>
<amount>50</amount>
</row>
</rows>
<client_name>customer y</client_name>
</document>
</documents>
And here is my current code:
<xsl:for-each select="/documents/document">
<xsl:if test="contains(client_name, 'customer_x')">
<xsl:value-of select="sum(rows/*/amount)"/>
</xsl:if>
</xsl:for-each>
Output is:
20 20
But I need output where all these amount values are sum'd together and end result is in this case 40
A:
Let XPath do the work for you:
<xsl:value-of select="sum(/documents/document[client_name='customer_x']//amount)"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
missing .h file when creating lexical analyzer
I am trying to compile a .l file to create a lexical analyzer. the code is:
%{
#include "ifanw.tab.h"
extern int yylval;
%}
%%
"=" { return EQ; }
"!=" { return NE; }
"<" { return LT; }
"<=" { return LE; }
">" { return GT; }
">=" { return GE; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return MULT; }
"/" { return DIVIDE; }
")" { return RPAREN; }
"(" { return LPAREN; }
":=" { return ASSIGN; }
";" { return SEMICOLON; }
"IF" { return IF; }
"THEN" { return THEN; }
"ELSE" { return ELSE; }
"FI" { return FI; }
"WHILE" { return WHILE; }
"DO" { return DO; }
"OD" { return OD; }
"PRINT" { return PRINT; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
[a-z] { yylval = yytext[0] - 'a'; return NAME; }
\ { ; }
\n { nextline(); }
\t { ; }
"//".*\n { nextline(); }
. { yyerror("illegal token"); }
%%
the commands I have entered were:
flex filename.l
gcc -c lex.yy.c -o out
the output was
filename.l:2:23: fatal error: ifanw.tab.h: no such file or directory.
Is the problem in gcc libraries? If so, where can I download an updated/fixed library?
Otherwise, what's the problem?
A:
gcc is telling you what the trouble is: it cannot find the include file you specified.
It's not a problem of libraries.
You need to create that file from your .y file first
bison --debug --verbose -d ifanw.y
You might find this small tutorial useful.
If you do not have the .y file, then you're trying to compile an incomplete package, and that just won't work. You will have to somehow obtain the missing files from wherever you got the files you already have.
| {
"pile_set_name": "StackExchange"
} |
Q:
what this method return?
I am reading the following code,
public static <t> T getFirst(List<T> list)
I understand the List<T> list, the method get a reference to List<T> as parameter, and return
an object with type T, but what about the <t> after the keyword public static?
what does this mean?
A:
<t> declares a type parameter. That means that the method has a type parameter that can change on each invocation.
Unless T is a concrete type in your project (which is unlikely), the <t> should be <T>.
So in plain english <T> T getFirst(List<T> list) means:
there's a method called getFirst
it has a type parameter T (i.e. an arbitrary type which is aliased to T)
it takes a List<T> as its argument (i.e. a List of objects of that arbitrary type).
it returns a T object (i.e. an instance of that arbitrary type).
If you just wrote T getFirst(List<T> list) then the meaning would change:
there's a method called getFirst
it takes a List<T> as its argument (i.e. a List of objects of the concrete type T)
it returns an object of the concrete type T.
| {
"pile_set_name": "StackExchange"
} |
Q:
Binding a command and a CommandParameter in the same view
I have an Entry and a Button. I want the command "CallWebServiceCommand" to be called when I press the button. The call to that command needs to include the url of the web service as a CommandParameter. The BindingContext is set to the ViewModel of the page.
The CommandParameter property of the button needs to reference the Text property of the entry. In WPF, I could do something like this:
<Button Text="Call web service" Command="{Binding CallWebServiceCommand}" CommandParameter="{Binding ElementName=url, Path=Text}" />
I know that it's not possible to have multiple binding contexts per view, but what would be a good workaround for this particular situation?
A:
This is a bit of a hack, but it's worked for us in the past:
Use the ViewModel as a "relay" for the view. To do this, create a String property on your ViewModel that the text field binds its Text property to, and bind the CommandParameter of the button to this property. If you raise the PropertyChanged event for this "parameter" property, the command will supply the updated value to the method specified as the command's Action. It's certainly non-ideal, but it does work as a poor man's replacement for RelativeSource binding.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rotating 3D wireframe
This code consumes a lot of CPU. Could you tell me where it is possible to improve the code or change the way rendering?
Or it is possible to reduce the overhead of calculations? If you are using only 1 point when drawing the load on the CPU is not changed! Load 50-60%
Ubuntu 15.04 / intel® Core ™ i5-3230M CPU @ 2.60GHz × 4
Run the code without rendering lines - 20-30% load. So they are quite costly...
Demo: http://codepen.io/jonfint/full/VLYMMW
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d'),
points = [],
r = 0;
var a = 50; // количество точек
var b = 1; // скорость поворота
var d = 20; // увеличение радиуса*
var minDist = 200; // ??
var dist; // ??
canvas.width = 500; // Originally window.innerWidth, changed for Stack Snippet
canvas.height = 600; // Originally window.innerHeight, changed for Stack Snippet
for (var i = 0; i < a; i++) {
var rand = Math.random() * canvas.height;
points.push({
cy: rand,
cx: rand * 0.3 + 300,
r: 360 / a * i,
p: {x: null, y: null},
d: Math.random() * (d + 5) + 50,
s: (Math.random() - 0.5) * 0.7,
size: Math.random() * 3 + 1,
})
}
function render(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#202020';
for (var i=0, len = points.length; i < len; i++) {
var p = points[i];
for (var j = i + 1; j < points.length; j++) {
var p2 = points[j];
distance(p.p.x, p.p.y, p2.p.x, p2.p.y);
}
p.r += p.s;
var vel = {
x: p.d * Math.cos(p.r * Math.PI / 180),
y: p.d * Math.sin(p.r * Math.PI / 180) / 2
};
var centx, centy;
centx = p.p.x - p.size * 0.5;
centy = p.p.y - p.size * 0.5;
ctx.beginPath();
ctx.rect(centx, centy, p.size, p.size);
ctx.fill();
ctx.closePath();
p.p.x = p.cx + vel.x;
p.p.y = p.cy + vel.y;
}
}
function distance(p1x, p1y, p2x, p2y) {
var dx = p1x - p2x;
var dy = p1y - p2y;
dist = Math.sqrt(dx*dx + dy*dy);
// Нарисовать линию, если расстояние меньше, чем minDistance
if (dist <= minDist) {
ctx.beginPath();
ctx.strokeStyle = 'rgba(200, 200, 200,'+ (1.0-dist/minDist) +')';
ctx.moveTo(p1x, p1y);
ctx.lineTo(p2x, p2y);
ctx.lineWidth = 1;
ctx.stroke();
ctx.closePath();
}
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 30);
};
})();
(function animloop() {
requestAnimFrame(animloop);
render();
})();
<canvas id="canvas"></canvas>
A:
I profiled your code and calling your render function takes 3.1-4.2 ms on my machine (i7 2.1 ghz running chrome/linux). I managed to cut that to only 0.6 ms by removing what is AFAIK the performance killer in this type of drawings using the canvas API. Check it out for yourself http://codepen.io/anon/pen/QbwQmo
The performance killer that I'm talking about is that you're drawing a million separate paths instead of batching them all in a single .beginPath ... .stroke. The catch is however that you can't have multiple colors (alpha levels) in the same path - so changing the color for every segment is not possible anymore. You could instead bucketize the paths - choose 10 shades of grey and add segments to these buckets; then call .stroke for each bucket (that'll amount to max 10 calls - way better than (50*50 which is what you can have)). The only way to overcome this limitation of the canvas API is to not use it in the first place :). Instead use a WebGL renderer (pixi.js, goo.js, three.js).
There's another thing which you can do to increase performance especially if you'll want more than 50 points. Right now you're checking every point against every other point. The number of calls to distance (not the best name btw) grows quadratically with the number of points. You can reduce the number of checks by discarding points that are too far - and you achieve this by splitting the whole space ([0...600] x [0...600]) into smaller buckets of 100 x 100 or something. You'd have to update the buckets every frame such that they contain the points that lie within their bounds. The upside is that you only need to check points in nearby buckets and not in the whole space.
(Disclaimer: I am a dev of goo.js)
A:
I see these performance reducers in your code:
Resetting context state is modestly expensive--especially when done inside a loop. Don't needlessly reassign ctx.fillStyle = '#202020' inside your render loop. Just do it once at the start of your app.
Math trig methods are expensive. Prebuild the Math.cos & Math.sin values you need into a lookup table. You may need to confine your p.r values to a slightly more limited set of values matching the lookup table.
Math.sqrt is extremely expensive-especially when done within nested loops (50*50==2500 distance calculations per animation frame!). Instead, do the equally effective test on the squared values. This fix may get you "the most bang for the buck":
// at the top of your app
var minDistSquared = minDist*minDist;
// in your distance function
var dx = p1x - p2x;
var dy = p1y - p2y;
dist = Math.sqrt(dx*dx + dy*dy);
// ?????????? ?????, ???? ?????????? ??????, ??? minDistance
if (dx*dx+dy*dy <= minDistSquared) {
// do stuff
}
Resetting context state is modestly expensive--especially when done inside a loop. You'll need to perf-test this one: Resetting the opacity using context.globalAlpha may be faster than resetting the alpha value of the context.strokeStyle. Or alternatively, confine your opacities to a smaller set and sort the points based on opacity before drawing them (again, perf-test required).
Calling a function is slightly expensive--more so when done inside a loop (50*50==2500 times). Move your function distance calculation & drawing inside function render.
Minor improvement--almost not worth mentioning: use while loops to iterate through points: var pointsCountdown=points.length and then while(--pointsCountdown)
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I group a foreach loop's output?
I'm working with Bootstrap's grid and I'm iterating through an array of names. The problem is that I don't know how to place X amount of results per parent div.
$names = mysql result containing 9 names.
<div class="container">
<div class="row">
<?php
foreach ($names as $name){
echo '
<div class="col-xs-3 col-sm-3">
<p>Customer name:'.$name.'</p>
</div>';
}
</div>
</div>
That would output this 9 times.
<div class="col-xs-3 col-sm-3">
<p> Customer name: Foo </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: bob </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: jim </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: dave </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: lucy </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: sarah </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: geoff </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: matt </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: alex </p>
</div>
How can I make it output 3 column divs per .row like this?
<div class="row">
<div class="col-xs-3 col-sm-3">
<p> Customer name: Foo </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: bob </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: jim </p>
</div>
</div>
<div class="row">
<div class="col-xs-3 col-sm-3">
<p> Customer name: dave </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: lucy </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: sarah </p>
</div>
</div>
<div class="row">
<div class="col-xs-3 col-sm-3">
<p> Customer name: geoff </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: matt </p>
</div>
<div class="col-xs-3 col-sm-3">
<p> Customer name: alex </p>
</div>
</div>
A:
You may want to think about an array_chunk() which would take care of uneven number of names:
$names = array('Dave','Frank','Sarah','Dan','Andrew','Jessica','Alena','Debbie','Jeff');
$split = array_chunk($names,3);
?>
<div class="container">
<?php
foreach ($split as $group){
echo '
<div class="row">';
foreach ($group as $name){
echo '
<div class="col-xs-3 col-sm-3">
<p>Customer name:'.$name.'</p>
</div>';
}
echo '
</div>';
}
?>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting multiple image names either with separated commas or to make image table separate
I am having product table with product id(PK), product name, category name, product price, brand, image and category table having columns category id and name from category table. I am adding category wise product as well as only one image to the product table. I want to insert (at least 5) images in the image column for each product.
If in future I want to add subcategory for product, what is better either to make separate table of image and then add them to that table or to insert the image with separated commas in image column of same product table.
How do I implement it ? What is the code for that?
Valuable help will be appreciated...
Here, I'm sharing my code:add_prodcut.php
if(isset($_POST['save_product']))
{
extract($_POST);
$target = "images/products/";
$target = $target . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $target);
$add_product = mysql_query("INSERT INTO `tbl_product` (`product_name` ,`category_id` ,`product_price` ,`product_brand` , `image`) VALUES ('".$product_name."','".$category_id."','".$product_price."', '".$product_brand."', '".$_FILES['file']['name']."')");
if (mysql_affected_rows($con) > 0)
{
$_SESSION["msg"] = "Product Added Successfully";
}
}
?>
<html>
<head>..//scripts</head>
<body>
<form method="post" action="">
<?php $category = mysql_query("select * from tbl_category ");
$lists = array();
while($category_list = mysql_fetch_assoc($category))
{
$lists[] = $category_list;
}
?>
<select name="category_id" >
<option value="">Select Category</option>
<?php foreach ($lists as $categories) { ?>
<option value="<?php echo $categories['category_id']; ?> "><?php echo $categories['category_name']; ?></option>
<?php } ?>
</select>
<input name="product_name" type="text">
<input name="product_price" type="text">
<input name="product_brand" type="text">
<input name="file" type="file">
<button name="save_product">Save</button>
</form>
</body>
</html>
A:
When using a relational database you should never insert serialized data into cells. It's a violation of First Normal Form. It will in the long term cause you a world of pain. Trust me, I've had enough experience fixing up the mess that inevitably gets left behind by this kind of design to know what a bad idea it is.
What you should do instead is create a dependant table that has a foreign key back into the primary table. This is the correct way to represent a 1-n relationship in a RDBMS.
Here's some example psuedo-code for creating the tables (NOTE: This is not valid MySQL, just a fairly general SQL-like psudeo-code. For proper syntax, see the MySQL manual).
CREATE TABLE products (
SERIAL product_id,
// ...
) PRIMARY KEY product_id;
CREATE TABLE product_images (
SERIAL image_id,
INT product_id,
// ...
) PRIMARY KEY image_id
FOREIGN KEY product_id REFERENCES products.product_id
I'll leave inserting and querying these tables as an exercise for the OP, but it should be fairly straightforward.
Inserting can be done by populating the images product_id field with the ID of the product to which the image belongs.
Getting the images is a simple matter of selecting from images based on product ID, or even joining the two tables together on the foreign key.
| {
"pile_set_name": "StackExchange"
} |
Q:
Translate this quote from The Producers?
In the Broadway play The Producers (and subsequent movie), the character Max Bialystock recalls a quote from his dying mentor. He says it's in Yiddish, but more than one person has told me that, in fact, it's German. I don't speak either, so please bear with me.
Linked here is the exact location in this video where he says the words. I will also attempt a transliteration, though it will certainly be inaccurate:
Alle mensche musse machen, haden tugagatzen kashen pichen pippin
kachen.
Initial research shows that it is not a high-minded quote, and coming from Mel Brooks, it's bound to be comedic in nature. No lyrics sites I found have the entire quote written out, they shorten it for some reason (probably all copying from one bad source).
A:
I'm pretty sure second half is babbling, as people have suggested. The OP has given:
"...haden tugagatzen kashen pichen pippin kachen."
I would transliterate it a bit differently:
"...heden to the gantzen kasha'n pischen pippik kachen."
"Heden" isn't a word. "Kasha" (buckwheat groats) is the iconic food of poverty in Jewish culture, and it is here juxtaposed ungrammatically with the word for "pissing". This is also in close proximity to "kachen", which is probably supposed to be "kacken" (to defedcate) altered to rhyme with "machen".
Finally, the "pippik" is the belly-button, and it is universally considered a funny word in Yiddish. One of its most picturesque applications is in the following couplet taken from Isaac Rosenfeld's Yiddish paroday of t.s. eliots' "The Love Song of J. Alfred Prufrock":
"Ich wer' (=werde) alt, ich wer' alt
Un der pippik wert mir kalt."
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting "TypeError: undefined is not a function" with functional programming
I'm trying to solve the following issue using nested functions, so the result I am looking for is 11, but instead it is coming up as an error that the countWordsInReduce function is undefined. That function works fine by itself, but for some reason when using it with the reduce function I have, there is an issue. Any idea how I would use this correctly inside the reduce function? Any help would be appreciated.
function reduce(array, start, func){
current = start;
for (var i = 0; i < array.length; i++){
current = func(current, array[i]);
}
return current;
}
var countWordsInReduce = function(array, start){
var count = start;
count += array.join(", ").split(" ").length;
return count;
}
word_array = ["hello there this is line 1", "and this is line 2"];
reduce(word_array, 0, countWordsInReduce)
A:
Here is a working version I got after messing around with it a little. The problem is that you were passing the current array index to your countWordsInReduce function.
What the countWordsInReduce function should actually do is accept as the first parameter the next element of the array, and the second parameter is the current running total.
So the first time you call countWordsInReduce, you are passing the first string, with a running total of 0. The second time you call it, you are passing the second string, with a running total of 6. And then it will add the length of the second string to that and come out with the answer of 11.
So basically your reduce function is looking at the array as a whole, and the countWordsInReduce function is just processing it piece by piece.
function reduce(array, start, func) {
var current = start;
for (var i = 0; i < array.length; i++) {
current = func(array[i], current);
}
return current;
}
var countWordsInReduce = function (element, base) {
var count = base;
count += element.split(" ").length;
return count;
};
var word_array = ["hello there this is line 1", "and this is line 2"];
reduce(word_array, 0, countWordsInReduce);
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoiding duplicated values in Web.config
<appSettings>
<add key="ApiKey" value="xyz"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.cloudmailapp.com" port="587" userName="user@gmail.com" password="xyz" />
</smtp>
</mailSettings>
</system.net>
As you can see, the API key "xyz" appears twice, hardcoded.
Can I use code here? I'd like to be able to call
WebConfigurationManager.AppSettings["ApiKey"]
within the Web.config file, or something similar.
A:
I think the short answer to your question is no. The config files cannot include C# code like you are trying to add out of the box.
I did find another post that asks a question very similar to this. Its from a few years back, but there is a lot of feedback in it that looks like it may apply here. Rather than trying to summarize the top answer, I will just add a link. Variables within app.config/web.config
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert nested JSON to nested Java object using gson TypeAdapter
I am trying to use google gson TypeAdapter for converting nested JSON into nested Java object having implementation of TypeAdapter for each class. But I don't want to write complete read() method logic in single adapter class. I have referred few questions and blog examples over net. But complete read logic is in single class.
For small nested object its fine to have logic in single Adapter but for big object (having more than 10-15 fields in each class) it's not good.
[Update]
For example json keys look same as of class attributes, but in actual I will be getting input as hyphen-separated-small-case keys instead of Camel case keys. So my json and java classes attribute names will not be same hence I have to write my custom logic for mapping.
E.g.
Sample Json input :
{
"id": 1,
"name": "Alex",
"emailId": "alex@gmail.com",
"address": {
"address": "21ST & FAIRVIEW AVE",
"district": "district",
"city": "EATON",
"region": "PA",
"postalCode": "18044",
"country": "US"
}
}
And Java beans are as below :
//Employee object class
public class Employee {
private int id;
private String name;
private String emailId;
private Address address;
..
}
//Address object class
public class Address {
private String address;
private String district;
private String city;
private String region;
private String postalCode;
private String country;
..
}
I want to have two different adapters and integrate multiple adapters in read() method.
public class EmployeeAdapter extends TypeAdapter<Employee> {
@Override
public void write(JsonWriter out, Employee employee) throws IOException {
//
}
@Override
public Employee read(JsonReader jsonReader) throws IOException {
//read logic for employee class using AddressAdapter for address json
}
}
public class AddressAdapter extends TypeAdapter<Address> {
@Override
public void write(JsonWriter out, Address address) throws IOException {
//
}
@Override
public Address read(JsonReader jsonReader) throws IOException {
//read logic for Address class
}
}
How can I use AddressAdapter inside EmployeeAdapter?
A:
I use a TypeAdapterFactory for this kind of thing. It allows passing the gson instance to the TypeAdapter instance.
(In the example below, I left in passing "rawType" to the TypeAdapter instance, since its often useful. Pull that out if not needed.)
Example TypeAdapterFactory:
public class ContactTypeAdapterFactory implements TypeAdapterFactory {
// Add @SuppressWarnings("unchecked") as needed.
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
final Class<? super T> rawClass = typeToken.getRawType();
if (Employee.class.isAssignableFrom(rawClass)) {
// Return EmployeeAdapter for Employee class
return EmployeeAdapter.get(rawClass, gson);
}
if (Address.class.isAssignableFrom(rawClass)) {
// Return AddressAdapter for Address class
return AddressAdapter.get(rawClass, gson);
}
return null; // let Gson find somebody else
}
private static final class EmployeeAdapter<T> extends TypeAdapter<T> {
private final Gson gson;
private final Class<? super T> rawClass; // Not used in this example
private EmployeeAdapter(Class<? super T> rawClass, Gson gson) {
this.rawClass = rawClass;
this.gson = gson;
}
private static <T> TypeAdapter<T> get(Class<? super T> rawClass, Gson gson) {
// Wrap TypeAdapter in nullSafe so we don't need to do null checks
return new EmployeeAdapter<>(rawClass, gson).nullSafe();
}
@Override
public void write(JsonWriter out, T value)
throws IOException {
// We should only ever be here for Employee types
// Cast value to Employee
Employee record = (Employee)value;
// Output start of JSON object
out.beginObject();
// Output key / value pairs
out.name("name");
gson.getAdapter(String.class).write(out, record.getName());
// [...]
out.name("address");
gson.getAdapter(Address.class).write(out, record.getAddress());
// Output end of JSON object
out.endObject();
}
@Override
public T read(JsonReader in)
throws IOException {
String fieldName;
// Create an empty Employee object
Employee record = new Employee();
// Consume start of JSON object
in.beginObject();
// Iterate each key/value pair in the json object
while (in.hasNext()) {
fieldName = in.nextName();
switch (fieldName) {
case "name":
record.setName(gson.getAdapter(String.class).read(in));
break;
// [...]
case "address":
record.setAddress(gson.getAdapter(Address.class).read(in));
break;
default:
// Skip any values we don't support
in.skipValue();
}
}
// Consume end of JSON object
in.endObject();
// Return new Object
return (T)record;
}
}
private static final class AddressAdapter<T> extends TypeAdapter<T> {
private final Gson gson;
private final Class<? super T> rawClass; // Not used in this example
private AddressAdapter(Class<? super T> rawClass, Gson gson) {
this.rawClass = rawClass;
this.gson = gson;
}
private static <T> TypeAdapter<T> get(Class<? super T> rawClass, Gson gson) {
// Wrap TypeAdapter in nullSafe so we don't need to do null checks
return new AddressAdapter<>(rawClass, gson).nullSafe();
}
@Override
public void write(JsonWriter out, T value)
throws IOException {
// We should only ever be here for Address types
// Cast value to Address
Address record = (Address)value;
// Output start of JSON object
out.beginObject();
// Output key / value pairs
out.name("address");
gson.getAdapter(String.class).write(out, record.getName());
// [...]
out.name("country");
gson.getAdapter(String.class).write(out, record.getCountry());
// Output end of JSON object
out.endObject();
}
@Override
public T read(JsonReader in)
throws IOException {
String fieldName;
Address record = new Address();
in.beginObject();
// Iterate each parameter in the json object
while (in.hasNext()) {
fieldName = in.nextName();
switch (fieldName) {
case "address":
record.setAddress(gson.getAdapter(String.class).read(in));
break;
// [...]
case "country":
record.setCountry(gson.getAdapter(String.class).read(in));
break;
default:
in.skipValue();
}
}
in.endObject();
return (T)record;
}
}
}
Use:
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ContactTypeAdapterFactory())
.create();
Employee employee = gson.fromJson(jsonString, Employee.class);
| {
"pile_set_name": "StackExchange"
} |