text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Create a StackLayout inside a Frame in Xamarin Forms using C# as background code
I use an <Frame> in my xaml page like this:
<StackLayout>
<Frame>
<StackLayout>
<Button></Button>
<Label></Label>
</StackLayout>
<StackLayout>
<Label></Label>
</StackLayout>
</Frame>
</StackLayout>
But I want to do the same thing on the C# side.
I define the StackLayout, Label and Button.
Now I can add the Button to the StackLayout using Children, but I cannot add the StackLayout to the Frame because it doesn't have a Children property.
Is it possible to add a StackLayout inside a Frame using C# as background code ?
A:
A frame has a unique property: Content. Follow this snippet to create your UI in code behind:
var stackLayout = new StackLayout();
//add content...
stackLayout.Children.Add(new Label);
var frame = new Frame;
frame.Content = stackLayout
Moreover, if you want to have multiple children in your Frame, wrap it in an unique Container (Grid, RelativeLayout, AbsoluteLayout, ...)
See https://developer.xamarin.com/api/type/Xamarin.Forms.Frame/
| {
"pile_set_name": "StackExchange"
} |
Q:
Symfony 4, .env files and production
.env files are very handy with docker, kubernetes, etc
But what if I have simple nginx server without any orchestration and a pack of cron workers and a pack of daemons(systemd/supervisord/etc)?
I can write these env variables to nginx server section, but I have to set up hundreds of env variables to each cron worker or daemon.
I found a quick solution: using symfony/dotenv component in production.
But it seems to me dirty. Who can suggest better solution?
A:
First of all, not all variables need to be specified using environment variables. Keep variables that do not differ per system in a separate yaml file.
When you have just one environment per server you can specify the environment variables globally in /etc/environment. (Might be different depending on your Linux flavour)
Personally I find that using DotEnv poses more difficulties than solutions when you run multiple environments on the same server. Specifying the variables in a global configuration like /etc/environment doesn't work in that case.
Specifying the environment variables in nginx isn't a solution either since, as you mentioned, they won't be picked up by cron, supervisor, the console, etc. For me, this was the reason to completely remove DotEnv and work with the good old parameters.yaml file again. Nothing will stop you from doing that.
Another solution however is to keep using DotEnv in your development environment and to include a separate parameters.yaml in production. You can then define the environment variables as follows:
parameters:
env(APP_ENV): prod
env(APP_SECRET): 3d05afda019ed4e3faaf936e3ce393ba
...
A way to include this file is to put the following in your services.yaml file:
imports:
- { resource: parameters.yaml, ignore_errors: true }
This way, the import will be ignored when no parameters.yaml file exists. Another solution is to add a line to configureContainer() in your Kernel class:
$loader->load($confDir.'/parameters'.self::CONFIG_EXTS, 'glob');
| {
"pile_set_name": "StackExchange"
} |
Q:
how to make suspend calls "wait" for a blocking thread inside, in Kotlin?
Let me explain it better...
I have a suspended function
suspend fun foo(){
if(startFlag){
myMethod()
}
}
when I call myMethod() on the first time I will check for the value of startFlag and if it is false will call myMethod.
I cannot use a init {} for this, must be when I call foo() the first time (due more complex logic).
My problem:
At the first time I call foo() will call myMethod() (lets says it takes a long time to resolve)
Then another call is made to foo(), I want to detect that myMethod() is already running in a thread and I should wait for it.
But since fun foo() is itself suspended, not sure if I can do it.
Any ideas?
A:
This is an interesting problem and I want to share an approach to solve it, hoping this will help.
Basic Solution
You can restore the myMethod() computation using a Deferred. Basically the code could look like this:
val myMethodDeferred = GlobalScope.async {
myMethod()
}
suspend fun foo(){
myMethodDeferred.await()
}
The async function returns a Deferred object that holds the computation of myMethod. When you call myMethodDeferred.await() it waits for the end of the computation and returns the result of myMethod (for using it if needed).
If you want the computation to be done only when calling foo() you could add a parameter to the async call like this: async(start = CoroutineStart.LAZY){ .... It will cause the computation to lazily start on the first .await() call.
(The GlobalScope could be replaced with any CoroutineScope, or with a scope that is passed as constructor parameter to the class. If myMethod() is not a suspending function but a blocking function as you described, you may want to use an appropriate CoroutineScope, for example CoroutineScope(Dispatchers.IO) if it does an I/O computation.)
Handling Failures
The downside of this solution is when myMethod() failed with exception. If myMethod() failed, the failure will be stored in the deferred, and every call to foo() will fail too, instead of trying to run myMethod() again.
To handle failures of myMethod(), I suggest to declare a class with a name Retryable that will hold a computation that can be retried, similarly to how Deferred hold a computation. The code:
class Retryable<T>(private val computation: suspend CoroutineScope.() -> T) {
private var deferred: Deferred<T>? = null
suspend fun await(): T {
val oldDeferred = deferred
val needsRetry = oldDeferred == null || oldDeferred.isCompleted && oldDeferred.getCompletionExceptionOrNull() != null
if (needsRetry) {
deferred = GlobalScope.async(block = computation)
}
return deferred!!.await()
}
}
The usage should look like this:
val myMethodRetryable = Retryable { myMethod() }
suspend fun foo(){
myMethodRetryable.await()
}
Now, every call to foo() will wait to the computation of myMethod() to be completed, but if it has already end with failure it will re-run it and wait for the new computation.
(Here, the CoroutineScope should be passed as parameter to the Retryable, but I don't want to complicate the sample code.)
Alternative Solution: Use asynchronous factory function
Since myMethod() should only be called once, if you cannot call it on init {} you can instead call it on a factory function.
Example code:
class MyClass(private val myMethodResult: String) {
companion object {
suspend fun create(): MyClass {
val myMethodResult = myMethod()
return MyClass(myMethodResult)
}
private suspend fun myMethod(): String {
...
}
}
...
}
It is useful if you can init MyClass once from a suspending function before using it.
(If myMethod() is not a suspending function but a blocking function as you described, you may want to wrap it with an appropriate context, for example withContext(Dispatchers.IO) { myMethod() } if it does I/O computation.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How would you explain an eclipse in a world where all our myths are true?
In a world parallel to ours, equal in both technology and philosophy, how would you explain an eclipse but still have science behind in all parts of the world?
How would I be able to tie in all these different mythological explanations to happening on the same day or being related somehow? I want to do this without changing parts of every mythology to tie in to one event and I want help in an explanation for them.
A:
Given that different cultures have different myths explaining eclipses it would be difficult to have them "All" be true.
I would say that the best path would be to have the different eclipse-related lore of different cultures be interpretations of the same event. Otherwise you will have contradicting myths and endless causes and reasons behind why it is happening.
A:
Generally speaking, an eclipse doesn't necessarily have to be physically affecting the entire world, just a small segment of it for a story to carry out. Therefore, in my mind, a powerful being or event that creates an eclipse without literally destroying the entire world or moon by moving it near instantaneously in the atmosphere, would be either through illusion or overlapping dimensions.
Especially overlapping dimensions, consider the Shadow Realm from World of Warcraft - it is an exact replica of the normal Universe, however, Death Knights of the Lich king have the ability to pull, or project an object from that realm. So really, this can be answered in a lot of different ways.
Probably the easiest, as in, uses the least amount of energy, would be to just project an image of a moon into the sky that blocks out the sun. To explain multiple mythologies co-existing, the deities that reign over similar elements, objects, etc. aren't ruling over the physical objects themselves.
For instance, Egyptian Ra, where the Sun is still in the same place, however a given deity believes they have the ability to utilize its power.Belief is often the driving force in mythology, so while the deity believes this is the case, that makes it true. Of course, in reality, they kind of just control the effects of the thing they reign over, how it affects their region of influence.
Therefore, if something had "power over the moon", they're really just removing people's perception of the real one and replacing it with their own, and the effects that come with it. You can think of it like those Sci-Fi Nature domes in spaceships - it looks and generally feels like the moon, but in technicality it isn't. It could be a lot more complex than just a screen over the area, it could do with manipulating beings perception of their surrounding.
Does that make sense? Broadly speaking, abilities and powers like that in intertwining myth don't often have literal control over something, just the perception/idea of it that's physically believable enough that it's nearly indistinguishable.
EDIT: To add on even more, for specifics, projections could be by magic illusions, targeted psychological projection, "window" to a different realm/dimension, physical manifestations, and more, but the idea of projection opens a lot of flexibility and technicalities in a being's/event's scope of power.
| {
"pile_set_name": "StackExchange"
} |
Q:
$X,Y$ has same distribution function $\implies P(X=Y)=1$ ?
Suppose $X,Y$ are two random variables with same distribution function. Denote $F_X$ for the distribution function of $X$ and $F_Y$ the distribution function of $Y$, then $F_X(t)=F_Y(t)$ for all $t\in\mathbb{R}$. I want to know if $P(X=Y)=1$. If this is not the case, could you show me some counter example.
PS: if the statement is valid, I'm looking for some argument not using expectations.
Thank you.
A:
This doesn't hold at all if $X$ and $Y$ are non-degenerate. Consider for example the space $\Omega = \{0, 1\}$ with the uniform distribution and the random variables $X(\omega) = \omega$ and $Y(\omega) = 1 - \omega$. They both have the distribution, but $P(X = Y) = 0$.
The reason for this is that the connection between the distribution of a random variable and the probability measure on the domain of $X$ and $Y$ is very weak. For example, two random variables can be defined on completely different probability spaces, but still have the same distribution.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to do central home directories and user accounts on Ubuntu?
I need to set up a network of twenty Ubuntu machines and a server. As it is now, the users have local accounts on the machines, but I want to have centralized user authentication, with all user info stored on the server, and with server-side home directories. So when a user logs in on any of the client computers, his username and password should be checked on the server, and then his home directory should be mounted from the server via NFS or something.
How do I do this? Which is the best way?
A:
I've run something like this in the past. LDAP is your best bet for centralized accounts. This is reasonably standard, and should be easy to set up. The client is merely a matter of installing a few packages (ldap-utils, libnss-ldap, and libpam-ldap), and editing /etc/pam.d/common-(everything). You'll need to add a line like
<type of file goes here> sufficient pam_ldap.so
As well as this, you'll have to edit /etc/nsswitch.conf, to add ldap at the end of shadow, group, and passwd.
The server is somewhat more complicated. This seems to include a relatively up to date example of how to set it up. The OpenLDAP docs are also well worth reading.
For homedirs, you'll want to use NFS. Depending on whether you need them unmounted when users are not logged in, you may want to use the automounter (autofs). I've never used this, so I can't tell you where you're going to run into trouble there, but working without it should be perfectly doable, and will give you much the same effect, with a far less complicated setup.
A:
Apparently you can use LDAP for centralized user accounts. I'm told it's not easy to set up. We never did because we didn't have very many users. However, the centralized directories were implemented. This was done by doing an NFS mount of the home directory of the central server on the other server. It works very well.
| {
"pile_set_name": "StackExchange"
} |
Q:
NSComboBox: How to tell user has typed in information that is not in the pop up list and read it
I have an NSComboBox with a seperate class that conforms to NSComboBox dataSource and delegate.
If the user types text into the combo box that that does not match one of the items in the pop up list, how do I receieve a notification that the user has typed something in and also read the value that the user has typed?
At the moment I'm implimenting the delegate methods:-
-(void)comboBoxSelectionDidChange:(NSNotification *)notification
-(void)comboBoxWillDismiss:(NSNotification *)notification
However these appear only to be notified when the user has selected an item from the popup, not when the user types something else in stops editing
A:
Since NSComboBox is a subclass of NSTextField, and thus NSControl, you can also use the NSControlTextEditingDelegate methods such as control:textShouldEndEditing: to affect the behavior of your combo box.
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing all rows for keys with more than one row
Table kal
id integer primary key
init char 4 indexed
job char4
id init job
--+----+------
1 | aa | job1
2 | aa | job2
3 | bb | job1
4 | cc | job3
5 | cc | job5
I want to show all rows where init has more than one row:
id init job
--+----+------
1 | aa | job1
2 | aa | job2
4 | cc | job3
5 | cc | job5
I tried:
select * from kal where init in (select init from kal group by init having
count(init)>2);
Actually, the table has 60000 rows, and the query was
count(init)<40,
but it takes a humongous amount of time, phpmyadmin and my patience runs out.
Both
select init from kal group by init having count(init)>2)
and
select * from kal where init in ('aa','bb','cc')
runs in "no time", less than 0.02 seconds.
I've tried different subqueries, but all takes "infinite" time, more than a few minutes; I've actually never let them finish.
A:
Here's an example, and you can see it in action:
Query
SELECT a.id, a.init, a.job
FROM kal a
INNER JOIN
(SELECT init, COUNT(init)
FROM kal
GROUP BY init
HAVING COUNT(init) > 1) b ON b.init = a.init
Result
| ID | INIT | JOB |
--------------------
| 1 | aa | job1 |
| 2 | aa | job2 |
| 4 | cc | job3 |
| 5 | cc | job5 |
| {
"pile_set_name": "StackExchange"
} |
Q:
Browser and OS detection script
I understand not to rely on user agent information for anything detrimental towards the site since it can be faked or hidden etc, it's more of just an extra feature for something.
Is there anyway this can be made shorter perhaps? Also it will be running on a few pages, so I was wanting to know if it's performance is good/bad?
<?php
function getBrowserOS() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = "Unknown Browser";
$os_platform = "Unknown OS Platform";
// Get the Operating System Platform
if (preg_match('/windows|win32/i', $user_agent)) {
$os_platform = 'Windows';
if (preg_match('/windows nt 6.2/i', $user_agent)) {
$os_platform .= " 8";
} else if (preg_match('/windows nt 6.1/i', $user_agent)) {
$os_platform .= " 7";
} else if (preg_match('/windows nt 6.0/i', $user_agent)) {
$os_platform .= " Vista";
} else if (preg_match('/windows nt 5.2/i', $user_agent)) {
$os_platform .= " Server 2003/XP x64";
} else if (preg_match('/windows nt 5.1/i', $user_agent) || preg_match('/windows xp/i', $user_agent)) {
$os_platform .= " XP";
} else if (preg_match('/windows nt 5.0/i', $user_agent)) {
$os_platform .= " 2000";
} else if (preg_match('/windows me/i', $user_agent)) {
$os_platform .= " ME";
} else if (preg_match('/win98/i', $user_agent)) {
$os_platform .= " 98";
} else if (preg_match('/win95/i', $user_agent)) {
$os_platform .= " 95";
} else if (preg_match('/win16/i', $user_agent)) {
$os_platform .= " 3.11";
}
} else if (preg_match('/macintosh|mac os x/i', $user_agent)) {
$os_platform = 'Mac';
if (preg_match('/macintosh/i', $user_agent)) {
$os_platform .= " OS X";
} else if (preg_match('/mac_powerpc/i', $user_agent)) {
$os_platform .= " OS 9";
}
} else if (preg_match('/linux/i', $user_agent)) {
$os_platform = "Linux";
}
// Override if matched
if (preg_match('/iphone/i', $user_agent)) {
$os_platform = "iPhone";
} else if (preg_match('/android/i', $user_agent)) {
$os_platform = "Android";
} else if (preg_match('/blackberry/i', $user_agent)) {
$os_platform = "BlackBerry";
} else if (preg_match('/webos/i', $user_agent)) {
$os_platform = "Mobile";
} else if (preg_match('/ipod/i', $user_agent)) {
$os_platform = "iPod";
} else if (preg_match('/ipad/i', $user_agent)) {
$os_platform = "iPad";
}
// Get the Browser
if (preg_match('/msie/i', $user_agent) && !preg_match('/opera/i', $user_agent)) {
$browser = "Internet Explorer";
} else if (preg_match('/firefox/i', $user_agent)) {
$browser = "Firefox";
} else if (preg_match('/chrome/i', $user_agent)) {
$browser = "Chrome";
} else if (preg_match('/safari/i', $user_agent)) {
$browser = "Safari";
} else if (preg_match('/opera/i', $user_agent)) {
$browser = "Opera";
} else if (preg_match('/netscape/i', $user_agent)) {
$browser = "Netscape";
}
// Override if matched
if ($os_platform == "iPhone" || $os_platform == "Android" || $os_platform == "BlackBerry" || $os_platform == "Mobile" || $os_platform == "iPod" || $os_platform == "iPad") {
if (preg_match('/mobile/i', $user_agent)) {
$browser = "Handheld Browser";
}
}
// Create a Data Array
return array(
'browser' => $browser,
'os_platform' => $os_platform
);
}
$user_agent = getBrowserOS();
$device_details = "<strong>Browser: </strong>".$user_agent['browser']."<br /><strong>Operating System: </strong>".$user_agent['os_platform']."";
print_r($device_details);
echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
Update with new script
<?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];
function getOS() {
global $user_agent;
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
function getBrowser() {
global $user_agent;
$browser = "Unknown Browser";
$browser_array = array(
'/msie/i' => 'Internet Explorer',
'/firefox/i' => 'Firefox',
'/safari/i' => 'Safari',
'/chrome/i' => 'Chrome',
'/opera/i' => 'Opera',
'/netscape/i' => 'Netscape',
'/maxthon/i' => 'Maxthon',
'/konqueror/i' => 'Konqueror',
'/mobile/i' => 'Handheld Browser'
);
foreach ($browser_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$browser = $value;
}
}
return $browser;
}
$user_os = getOS();
$user_browser = getBrowser();
$device_details = "<strong>Browser: </strong>".$user_browser."<br /><strong>Operating System: </strong>".$user_os."";
print_r($device_details);
echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
Added a couple more browsers and operating systems to the list in the new version :)
A:
First of all, I guess somebody has already written a library for that. I would do some research and check existing libraries.
1, Split the code to two smaller functions: getOperatingSystem() and getBrowser().
2,
} else if (preg_match('/linux/i', $user_agent)) {
$os_platform = "Linux";
}
// Override if matched
if (preg_match('/iphone/i', $user_agent)) {
$os_platform = "iPhone";
The second if should be on the same indentation level as the else if. It's a little bit confusing.
3, I'd put the regular expressions and the result browsers to an associative array and iterate over it:
$os_arr['/windows|win32/i'] = 'Windows';
$os_arr['/windows nt 6.2/i'] = 'Windows 8';
...
foreach ($os_arr as $regexp => $value) {
if (preg_match($regexp, $user_agent)) {
$os_platform = $value;
}
}
It isn't exactly the same logic as your if-elseif structure but it also could work and it's more simple. Note: the order of the elements in the array is important.
4, Instead of this:
if ($os_platform == "iPhone" || $os_platform == "Android" || $os_platform == "BlackBerry"
|| $os_platform == "Mobile" || $os_platform == "iPod" || $os_platform == "iPad") {
set an $is_mobile flag:
$is_mobile = false;
if (preg_match('/iphone/i', $user_agent)) {
$os_platform = "iPhone";
$is_mobile = true;
} else if (preg_match('/android/i', $user_agent)) {
$os_platform = "Android";
$is_mobile = true;
...
if ($is_mobile && preg_match('/mobile/i', $user_agent)) {
...
}
You can also combine it with the associative array solution:
$os_arr['/windows|win32/i']['os'] = 'Windows';
$os_arr['/windows|win32/i']['is_mobile'] = FALSE;
$os_arr['/windows nt 6.2/i']['os'] = 'Windows 8';
$os_arr['/windows nt 6.2/i']['is_mobile'] = FALSE;
(If you use it you should change the os and is_mobile strings to constants.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass database value in form (django)
My form.py:
class BannerForm(forms.ModelForm):
name = forms.CharField(max_length=32)
#Affiliazione = forms.CharField(disabled = True, initial='red') #in original question
#affiliation = forms.ModelChoiceField(Affiliation.objects.all(),
#widget=forms.HiddenInput(), initial=Affiliation.objects.get(id=1)) #in original question
Affiliazione = forms.CharField(disabled = True, required=False) #added after first answer
affiliation = forms.ModelChoiceField(Affiliation.objects.all(),
widget=forms.HiddenInput()) #added after first answer
The 'Affiliazione' field display 'red' but it isn't saved because Disabled controls cannot be successful. The 'affiliation' field actually pass the data but is hidden. They together give what I want (a disabled field that pass data so the user can see the value but can't change it).
The problem is I don't like to hardcode that values ('red' and 'id=1'). I have the 'Options' class in models where I choose the value to pass but I don't know how... I think it's a silly question, sorry, but someone can help me?
My models.py:
class Options(models.Model):
new_affiliation = models.ForeignKey('Affiliation')
class Affiliation(models.Model):
name = models.CharField(max_length=32, unique=True)
def __str__(self):
return self.name
class Banner(models.Model):
name = models.CharField(max_length=32, unique=True)
affiliation = models.ForeignKey(Affiliation)
Edit. My View.py:
def add_banner(request):
# A HTTP POST?
if request.method == 'POST':
form = BannerForm(request.POST)
print('form is post') #control
# Have we been provided with a valid form?
if form.is_valid():
print('form is valid') #control
# Save the new banner to the database.
banner = form.save(commit=False)
#some irrilevant code here
form.save(commit=True)
print('form salvato') #control
# Now call the homepage() view.
# The user will be shown the homepage.
return homepage(request)
else:
# The supplied form contained errors - just print them to the terminal
print (form.errors)
else:
# If the request was not a POST, display the form to enter details
#form = BannerForm(request.POST) #in original question
#initial_value = 'red' #added after first answer
#init = Affiliation.objects.get(id=1) #added after first answer
form = BannerForm(request.POST or None, initial={
'affiliation': Campaign_Options.new_regent_affiliation}) #added after first answer
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
print ('fine')
return render(request, 'core/add_banner.html', {'form': form})
My add_banner.html:
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.label }}
{{ field }}
{{ field.help_text }}
<br />
{% endfor %}
A:
Even if I don't quite get the intention of your form, but for the sake of answering your question, you could pass the initial value from your views when you initialize the form, this will make the value flexible:
def your_view(request):
# get the string for affilizione by applying your logic here
# initial_value = 'red'
form = BannerForm(request.POST or None, initial={'Affiliazione': initial_value})
| {
"pile_set_name": "StackExchange"
} |
Q:
hyphen converts into comma in web-scrapping
I am scraping data from page with help of JavaScript & displaying on fancybox popup.
var str = "$26.61 - Framed bulletin board offers a self-stick surface for quick and easy note positioning, repositioning, and removing.";
When I output it, however, I get this:
$26.61 , Framed bulletin board offers a self,stick surface for quick and easy note positioning, repositioning, and removing.
Here is some javascript:
var pro_desc = $('meta[name=Description]').attr("content");
var shortDesc = $.trim(pro_desc).substring(0, 225);
var count1 = shortDesc.search(/$/i);
if(count1!=-1) {
var short_desc1 = shortDesc.replace("$", "");
var short_desc2 = short_desc1.split("-");
var desc1 = short_desc2;
} else {
alert('In Else Section---'+shortDesc);
}
var product_description = desc1;
alert(product_description);
Why does my output have ,'s instead of -'s?
A:
Why does my output have ,'s instead of -'s?
You are splitting on hyphens:
var short_desc2 = short_desc1.split("-");
So short_desc2 is an array containing strings, each of which was separated from the other by a hyphen. Example:
'foo-bar'.split('-');
// returns the array ['foo', 'bar']
Now, when you alert an array (alert(product_description);), i.e. convert it back to a string, the elements are concatenated with a comma in between:
alert('foo-bar'.split('-'))
// alerts 'foo,bar'
// or
alert([1,2,3]);
// alerts '1,2,3'
It's the same as doing:
alert(arr.join(','));
| {
"pile_set_name": "StackExchange"
} |
Q:
Returning Null Value - Coalesce and ISNULL
I may be having a brain fog, but if I have below:
COALESCE(NULLIF(Address.Info,''), 'Invalid')
Which gives me the value of invalid for all fields in my info column that have an empty space,
if I used ISNULL instead of COALESCE would it give me the same result? I cannot access a sql engine currently so just wanted to sanity check. Thanks!
ISNULL(NULLIF(Address.Info,''), 'Invalid')
A:
The two expressions should be equivalent in e.g. Oracle, which supports these functions.
Presto does support the standard coalesce(). It does not have isnull function though. See more at https://prestosql.io/docs/current/functions/conditional.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery for retaining the checked value in radio button
I am having two radiobuttons,
<div class="class1">
<span><input name="chk1" type="radio" checked="checked" id="check1"/>Option 1</span>
<span><input name="chk2" type="radio" id="check2"/>Option 2</span>
</div>
Now, i am displaying a hidden div using Jquery when the radio button with an ID check1 is cliked and hiding the same div when the radio button with an ID check2 is clicked, here is the code for that,
$(document).ready(function(){
$("#check1").click(function(){
$("#detail").slideDown("slow");
});
$("#check2").click(function(){
$("#detail").slideUp("slow");
})
});
My problem is, when an ID check1 is clicked(Div is displayed now) and the values are posted to the server and while return back to the same page, the div is not getting displayed, even though the option check1 is clicked. Is there any other way to retain the div using attr :checked or something? Appreciate your help...
A:
$(document).ready(function(){
if ($("#check1:checked").length) {
$("#detail").slideDown("slow");
}
$("#check1").click(function(){
$("#detail").slideDown("slow");
});
$("#check2").click(function(){
$("#detail").slideUp("slow");
})
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Работа с MySQL в Android'e
Здравствуйте, я начанающий программист под андройд, и по джаве собственно тоже. Пишу приложение для андройда и столкнулся со следующей задачей. Приложение должно брать информацию с сайта, а именно из базы MySQL. И тут ко мне в голову пришло два варианта решения этой задачи. Первый - это использовать стандартные классы джавы для работы с MySQL. Но будет ли приложение нормально работать на устройствах? В данном случает я так понимаю, что данные для доступа к базе (адрес, логин, пароль) будут храниться в самом приложении. Насколько это безопасно? Второй вариант решения - это создавать на сайте XML-страницу с данными из базы, а приложение уже будет парсить этот XML-файл. Какой вариант будет более оптимальным на ваш взгляд? Или может быть есть еще какие нибудь варианты?
Из этого всего выплывает очередной вопрос. Если я буду применять второй вариант, получается что приложение должно обращаться сначало не к XML-странице, а к php-скрипту которому приложение, сначало должно передать определенные параметры, а вот только потом получить сгенерированую налету XML-страницу и только потом ее считать. Не совсем понимаю как это реализовать, подскажите способы.
Ребята, подскажите возможно ли сделать так, что бы класс в джаве отправлял POST-запрос с параметрами к php-скрипту, который в свою очередь, возвращал бы в своем теле (например в echo) XML-разметку? И тут же этот ж класс обработал XML и выдал ее на экран. Со сторы php-проблем нет, опыт в нём у меня большой, скрипт я напишу без проблем, но вот со стороны джавы подскажите в какую сторону капать? =)
A:
Первый вариант имеет один плюс - он гибче. Но это и его недостаток. Если завтра захотите поменять одну таблицу, то нужно будет обновить программы на всех устройствах. А это может быть непросто. С другой стороны, если кто то подглянет внутрь кода, то может вытянуть не только параметры подключения к базе, но и в базу наведаться и там пошалить. А это уже очень печально.
Второй способ значительно лучше. Если структура базы поменяется - нужно просто переписать серверный скрипт. Более того, если запись в базу происходит не часто, а выборка значительно чаще, то кеширования файла с результатом сильно все разгрузит и ускорит. И это не преждевременная оптимизация. Это нормальное проектирование.
Но у второго способа есть один большой недостаток - xml. Мало того, что он сильно избыточный, так ещё распарсить его на клиенте не так и быстро (в одном из проектов, где я участвовал, был xml, на килобайт 30, который с ресурсов загружался и оттудова доставались разные параметры. Отказавшись от него в пользу массива (а по факту - просто питоновский скрипт, который при компиляции генерировал жава код по xml), удалось сэкономить около полусекунды при старте приложения).
Мое предложения - используйте второй вариант, то с json (его парсер есть в поставке), а для некоторых данных может и простой текстовый формат. - нужно смотреть на конкретные данные. А ещё по верху можно прикрутить gzip сжатие.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pandas new column returning lookup of max from groupby of several columns
I have a dataframe as such, and i'm trying to generate the RESULT column, using a groupby on the Set, Subset and Subsubset columns. I tried returning idmax on perc.
| Set | Subset | Subsubset | Class | perc | RESULT |
|-----|--------|-----------|-------|------|--------|
| 1 | A | 1 | good | 100 | good |
| 1 | A | | ok | 0 | good |
| 1 | A | | poor | 0 | good |
| 1 | A | | bad | 0 | good |
| 1 | A | 2 | good | 20 | bad |
| 1 | A | | ok | 10 | bad |
| 1 | A | | poor | 20 | bad |
| 1 | A | | bad | 50 | bad |
| 1 | A | 3 | good | 0 | poor |
| 1 | A | | ok | 10 | poor |
| 1 | A | | poor | 80 | poor |
| 1 | A | | bad | 10 | poor |
| 1 | B | 1 | good | 50 | good |
| 1 | B | | ok | 0 | good |
| 1 | B | | poor | 1 | good |
| 1 | B | | bad | 49 | good |
| 1 | B | 2 | good | 60 | good |
| 1 | B | | ok | 10 | good |
| 1 | B | | poor | 20 | good |
| 1 | B | | bad | 10 | good |
To clarify, the result will always be a single value (never will see a 50/50 split for example).
Sets number in the hundreds, subsets upto ZZ (very long table).
This is different to a similar question Python : Getting the Row which has the max value in groups using groupby as here i am interested in looking at grouping on MULTIPLE columns.
A:
Since you mentioned idxmax , then we using idxmax
idx=df.groupby(['Set','Subset','Subsubset'])['perc'].transform('idxmax')
df['RESULT']=df.loc[idx,'Class'].values#df.Class.reindex(idx).values
| {
"pile_set_name": "StackExchange"
} |
Q:
How to integrate partial version control, data exchange and research assistants?
Currently, my coauthors and I use GitHub to collaborate in coding and writing but also in data exchange. We have a lot of data, often not in text format (e.g. pdf). Most of this is collected by research assistants, which which we don't share our Git repo.
More specifically, we use python, shell, R, Stata and Latex and most of it is fully integrated. That is, python and shell scripts generate the data that is used by R and Stata whose output is directly compiled in Latex.
We don't want to deviate from this high level of automatization, but our approach has two major shortcomings:
Research assistants can and may not upload their data directly into our repo. Instead, they send us their data and files via another git repo. This puts additional workload on me but we want to make them use git for it's fascinating issue tracker. However, there is too much additional work for us and git is often to complicated for young research assitants (even the GUIs).
Because of the data, which eventually changes, our repo is very large (>1,5GB) and internet is sometimes restricted. Getting the repo on a new computer is very time-consuming and often not working. Although the raw data changes from time to time, git, which was not made for the data exchange, keeps track of these changes. But that's useless for our purpose.
Can you suggest to me other software(s) or approaches, which combine the integration we have achieved so far where we can easily exchange data?
A:
I've run into similar problems in collaboration with biologists, and found that a two-technology approach is best.
Large-scale experimental data is shared via one or more BitTorrent Sync folders. The experimentalists can just drop their files into the appropriate place in the folder, and they get synchronized with the server and everybody else's copy (like DropBox, but private, free, and unlimited size).
The analytical tool-chain, research products, write-ups, etc. are maintained in your preferred version system (e.g., git). This is then integrated with the experimental data just by giving a pointer to the appropriate directories.
This has the advantage of maintaining the data separation that you need, keeping the scary version control software away from the experimentalists, and also avoiding juggling massive globs of data in a version control system that was never intended to support this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Availability of for WIF Extensions for SAML2 Protocol?
We are currently designing the security of a system, which has a WPF client (.net 4) and Java Web Services (SOAP 1.2). We would like to use claims based security with SAML Tokens.
Since we have a .net client we are considering using WIF.
There was a CTP release of WIF Extensions for SAML2 Protocol in May 2011, I have not been able to find anything newer than this.
When will the WIF Extensions for SAML2 Protocol be available?
If they are not available in the near future, could we use SAML 1.1 with SOAP 1.2?
A:
You probably don't need WIF at all for this scenario. WCF supports claims based security bindings. You will just need to configure WCF for that.
You could use WIF to request a Security Token from the STS the Java web service is trusting, but that's optional.
Of course, being an interop scenario, I would strongly suggest a proof of concept, because all stacks are equal, but some are more equal than others when it comes to standards implementations.
Notice that a common source of confusion is the fact that SAML is both a protocol (as in the messages exchanged between clients, servers and STSs) and a token format. For example, SAML-P (a protocol) uses SAML tokens, but so does WS-Federation (another protocol).
Look at any of the "Active" samples in WIF or in this guide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Measure on $([0,1], \mathcal{P}([0,1]))$
I'm working on measures and I need to prove the following:
There exists no measure on $([0,1]\mathcal{P}([0,1]))$ such that
$\mu([0,1]) = 1$
$\mu(A) \in \{0,1\}$ for any $A \subseteq[0,1]$
$\mu(F) = 0$ for any $F \subseteq[0,1]$ finite
I understand why this is so and to some extent how to prove it:
1) We suppose there is such a measure.
2) We split the interval in two disjoint intervals and use the additivity of measures on disjoint sets to show that one of the subintervals has measure 1 and the other one 0.
3) We do it recursively and we obtain a sequence of intervals of measure 1 that converges to a singleton of measure 1.
4) This is a contradiction since the measure of finite sets is 0.
I'm not sure how to mathematically write step 3) in a rigorous way. Could anyone please help me? I'm pretty sure this is a standard exercise for an undergraduate course on Lebesgue theory but I didn't manage to find a proof online. If there has already been such a post, a redirection would be appreciated. Thanks in advance.
A:
We define the sets $A_n$ recursively as follows:
Let $A_0=[0,1]$. Given an interval $I=[a,b]$ let $f(I):=[a,\frac{a+b}{2}]$ and $g(I):= [\frac{a+b}{2},b]$ we clearly have that $I=f(I)\bigcup g(I)$ (also the union is disjoint up to measure zero).
Assuming we constructed $A_n$ such that $\mu(A_n)=1$, we construct $A_{n+1}$ as follows:
Look at $f(A_n),g(A_n)$, then we have that $A_n=f(A_n)\cup g(A_n)$ is of measure $1$. Therefore $\mu(f(A_n))+\mu(g(A_n))=1$ and so either $f(A_n)$ or $g(A_n)$ is of measure $1$. Let $A_{n+1}$ be this interval (the one of measure $1$).
We obtain a sequence of intervals $A_n$ such that $\mu(A_n)=1$. Moreover $A_{n+1}$ is either $f(A_n)$ or $g(A_n)$ and so it's length is half the length of $A_n$.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the oldest still running music festival?
What is the oldest still running music festival? 1970 - Pinkpop festival is at least a start, but I'm sure there are older ones.
A:
According to Wikipedia, it's the Three Choirs Festival - running in the UK every year since 1719. http://en.wikipedia.org/wiki/Three_Choirs_Festival
| {
"pile_set_name": "StackExchange"
} |
Q:
Boldening text "Inside" a textarea
I have a textarea #myarea into which I'm typing text. I've typed this text.
This is a sentence and only this word
will end up being bolded
Now I have a button on the side, like a bold button. I want to select the letters I want bolded, click the button, and see those letters turn bold inside the textarea. It's similar to the standard functionality found in many editors, but I'm looking for something much simpler as I described here.
So is there a way to do this with jquery? I'm guessing it's a 2-part problem. I need to find the letters selected, then apply bold to them so it shows bold inside the textarea.
A:
If you don't mind using a div that has its ContentEditable property set to true then you can easily do this using:
document.execCommand('bold',null,false);
You can easily style this div to look and feel like a textarea.
See jsFiddle here: http://jsfiddle.net/hqvDT/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open the ios Native dialer app from my App
I want to open the native dialer app and allow the user to enter the phone number there. The reason why i want this is because in my app the user needs to use USSD codes in order to make calls, but using the code bellow nothing happens (nothing is started)
NSString *phoneNumber = [@"tel://" stringByAppendingString:number];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
I read here (StackOverflow) that making calls from your app that contain * and # are forbidden.
So i want to ask is there any work around this limitation.
A:
No, there is no workaround with those symbols.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it ok to close as duplicate of closed/downvoted question?
I've just closed question as insta-duplicate of closed (and heavily downvoted due original quality) question. Should I have instead search for other better looking/open match or do something else altogether?
Clearly I should not be answering again with copy-paste of my other answer. I also feel that simple downvote due to quality/close as "not enough details to debug" would waste effort of other people...
Post in question C#, integer overflow, duplicate Why computing factorial of realtively small numbers (34+) returns 0 (The easiest to find duplicate for me as I've edited/answered it long time ago).
A:
Yes it is.
Whether a question is a duplicate or not is not related to its' (or the target's) quality.
| {
"pile_set_name": "StackExchange"
} |
Q:
Typescript syntax error on CommonJS/Node module: Unexpected token ':' on function param
This file checks out to be valid via TS, no more errors but during runtime, I get Unexpected token ':' on any of the TS I specified such as it immediately errors on function (err: string)
Here are my build and start scripts. I of course run build, then run start:
"start": "node --trace-warnings dist/server.ts",
"build": "NODE_ENV=production webpack -p --env=prod",
api.ts
const _ = require('lodash'),
companyTable = require('./shared/data/companies.json'),
countryTable = require('./shared/data/countries.json'),
compression = require('compression'),
express = require('express'),
expressApp = (module.exports = express()),
historyApi = require('connect-history-api-fallback'),
oneYear = 31536000;
expressApp.use(compression());
module.exports = expressApp
.on('error', function (err: string) {
console.log(err);
})
.get('/api/v1/countries', (res: any) => {
res.json(
countryTable.map((country: any) => {
return _.pick(country, ['id', 'name', 'images']);
})
);
})
server.ts
const app = require('./api.js');
const cluster = require('cluster'),
os = require('os'),
port = process.env.PORT || 8080;
console.log(port);
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
console.log('Ready on port %d', port);
} else {
app.listen(port, (err: string) => {
console.log(`express is listening on port ${port}`);
if (err) {
console.log('server startup error');
console.log(err);
}
});
}
tsconfig.json
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "es6", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["es6"], /* Specify library files to be included in the compilation. */
"moduleResolution": "node",
"allowJs": true, /* Allow javascript files to be compiled. */
"checkJs": true, /* Report errors in .js files. */
"jsx": "react",
"noImplicitAny": true,
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"removeComments": true, /* Do not emit comments to output. */
"strict": true, /* Enable all strict type-checking options. */
"noUnusedLocals": true, /* Report errors on unused locals. */
"noUnusedParameters": true, /* Report errors on unused parameters. */
// "rootDirs": ["."], /* List of root folders whose combined content represents the structure of the project at runtime. */
"typeRoots": [
"node_modules/@types"
], /* List of folders to include type definitions from. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "resolveJsonModule": true,
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true
},
"include": [
"src"
],
"exclude": [
"/node_modules",
"/src/client/js/ink-config.js",
"**/test"
]
}
UPDATE
So someone pointed out the obvious. Asking why does my dist have a .ts file in it (server.ts) and api.ts. That's because I'm copying it over in my webpack.config.js:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';
const html = () => {
return new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'src/client', 'index.html'),
filename: 'index.html',
hash: true,
});
};
const copyAllOtherDistFiles = () => {
return new CopyPlugin({
patterns: [
{ from: 'src/client/assets', to: 'lib/assets' },
{ from: 'src/server.ts', to: './' },
{ from: 'src/api.ts', to: './' },
{ from: 'package.json', to: './' },
{ from: 'ext/ink-3.1.10/js/ink-all.min.js', to: 'lib/js' },
{ from: 'ext/ink-3.1.10/js/autoload.min.js', to: 'lib/js' },
{ from: 'ext/js/jquery-2.2.3.min.js', to: 'lib/js' },
{ from: 'ext/ink-3.1.10/css/ink.min.css', to: 'lib/css/ink.min.css' },
{ from: 'feed.xml', to: './' },
{
from: 'src/shared',
to: './shared',
globOptions: {
ignore: ['**/*suppressed.json'],
},
},
],
});
};
module.exports = {
entry: './src/client/index.tsx',
output: {
filename: 'scripts/app.[hash].bundle.js',
publicPath: '/',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
devtool: 'inline-source-map',
devServer: {
writeToDisk: true,
port: 8080,
},
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(tsx|ts)?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: process.env.NODE_ENV === 'development',
},
},
'css-loader',
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: 'lib/assets/fonts',
},
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['url-loader'],
},
],
},
plugins: isProduction
? [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: isProduction ? 'lib/css/main.[hash].css' : 'main.css',
}),
html(),
copyAllOtherDistFiles(),
]
: [new CleanWebpackPlugin(), html(), copyAllOtherDistFiles()],
};
So...I need to do something different. While I do need server.ts and api.ts during development, not sure how I can transpile then copy those two files over (ouside of the web bundle I create).
A:
So I'm not entirely sure what the use case for copying over the files directly is - but let me answer by pointing out how you can achieve having the transpiled files in the output directory while still using the original .ts source file in development:
First, you can use ts-node-dev in development which helpfully allows you to run the original source files by transpiling on the fly so you can use it just as you would use the node binary, but on the source files rather than the emitted files. I use a command similar to this for development: NODE_ENV=development ts-node-dev --watch ./src/server.ts --transpileOnly ./src/server.ts
Then, for production, provided that you do not specify the noEmit option in your compiler options, TypeScript will transpile and emit files to the provided outDir. So, you can run these emitted files using the node binary: NODE_ENV=production node ./dist/server.js. This would allow you to remove the files under your source directory from your copy plugin, as TypeScript will transpile and emit the transpiled js in the directory for you
Edit (from comments): To include only the files which you want to be transpiled, you can specify those in include in your tsconfig:
include: ['./src/api.ts', './src/server.ts']
| {
"pile_set_name": "StackExchange"
} |
Q:
Paginating findManyToManyRowset result
I have two database tables (lets call them A and B) with many-to-many bridge table (AB). I have written Zend_Db_Table models for all three tables.
I have an A_Row object I extracted from the database using for example Zend_Db_Row::find method. Now I need get print a table of all rows, which are in relationship with this row. The problem is I need to have this table paginated, but the table is rendered using a method of B_Rowset.
I can see two options (if I want to use Zend_Paginator)
1) Use Zend_Paginator_Adapter_Iterator to paginate the rowset returned by findManyToManyRowset. This would look like this:
$b_rowset = $a_row->findManyToManyRowset('B_Table', 'AB_Table');
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Iterator($b_rowset));
However, there are two problems:
a) Whole result set (not only items on the page) is fetched.
b) I use a method of B_Rowset to render the table HTML, so I would have to convert the results back into result set.
This solution seems a little too ugly.
2) Build the Zend_Db_Table_Select manually and use Zend_Paginator_Adapter_DbTableSelect.
But building multi-table queries with Zend_Db_Table_Select is very unpretty (and the results need to be converted into B_Rowset). I would likely end up with 50 or so lines of messy code.
I could use either method (and I would likely be done faster than writing this post), but I want to see some opinions, how to solve this nicely (since I expect to encounter this scenario again and again).
A:
I have tried both of these, or at least 2, I did have a solution that was similar to 1 which used findDependentRowset().
One. Worked well. It was harder to set up and get working, but it means that the queries are built for me with less hassle when it comes to implementation.
Two. I ended up using this method however. It allows for greater flexibility and allows you to join tables only when you need them joined. This works well with Zend pagination too. My solution was to write functions within my model to which I can pass a Zend_Db_Select object to, the function in the model would then apply a join to the Zend_Db_Select object, similar to this.
// In Model A, you would create a function to join table B
// this is much simpler, but hopefully you get the idea
function joinB(Zend_Db_Select &$select)
{
$select->join(...);
return $this;
}
This is of course not the solution for everyone, but it provides me with what I need.
I wrote 'one' and 'two' earlier because the proper list syntax seemed to be messing up the code highlighting
| {
"pile_set_name": "StackExchange"
} |
Q:
PDF Printer with Preview
I'm often sending letters as PDF and prefer to proof read the final document to be sure embedded pictures, paragraphs etc. are correct.
Hence I am looking for a PDF Printer that will show a preview of the (about to be printed) document, similar to the way macOS does it when you do
Print>PDF>Open in Preview. It then should have a save/cancel choice.
Ideally free (ad-free) or with moderate (about $25-$40) one-time payment price.
A:
FinePrint pdfFactory opens with Preview. You can even edit it (delete those last white pages for example).
It is a bit outside your price range though, US$50
| {
"pile_set_name": "StackExchange"
} |
Q:
mimetypes.mime_guess() on google app engine behaves strange
In my python shell, i can do
>>> import mimetypes
>>> mimetypes.guess_type("ulla.svg")
('image/svg+xml', None)
And it behaves as expected, however, running the same code (or at least, this equal example) on google app engine, it returns (None, None)
class TestHandler(webapp2.RequestHandler):
def get(self):
import mimetypes
self.response.out.write(mimetypes.guess_type("ulla.svg"))
Am i doing it wrong? :)
BTW - It's python 2.7 in my macbooks shell, and also 2.7 on app-engine
A:
.svg is not included in the default types_map embbeded in the mimetypes module:
>>> import mimetypes
>>> print '.svg' in mimetypes.types_map
False
mimetypes module add additional extension/mimetypes from system files, and svg is defined on most distribution in /etc/mime.types
$ cat /etc/mime.types | grep svg
image/svg+xml svg svgz
But unfortunately it is not defined in the App Engine sandbox.
You should fill a defect on the public issue tracker
As a workaround you can register the mimetype yourself with mimetypes.add_type
>>> import mimetypes
>>> mimetypes.guess_type("ulla.svg")
(None, None)
>>> mimetypes.add_type("image/svg+xml", ".svg")
>>> mimetypes.guess_type("ulla.svg")
('image/svg+xml', None)
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues with Liferay 7.1 workspace imported from Github
I have cloned my Liferay 7.1 workspace from my Github repository. When I try to get Assistance in Liferay IDE using Control+Space, I get error:
This compilation unit is not on the build path of a java project
This happens on the new module project created in the same workspace(that was cloned from Github).
But when I create/import module from my local workspace that was created by Liferay for first time, this issue is not there.
I feel like there is some extra workspace setting that I am not doing in my Github workspace. Like we had to create build.username.properties in the SDK folder for Liferay 6.2. Totally stuck and no solutions anywhere.
I tried fixing Project Build path and Project Facets but did not help.
A:
There were some differences between the workspace that I imported from Github and the one that Liferay was creating on my local. I opened both the workspaces in Beyond Compare. Following are the files that had major differences. I made them same and it started working after Gradle Refresh in Eclipse.
liferay-workspace/gradle/wrapper/gradle-wrapper.properties
liferay-workspace/.project
liferay-workspace/gradle.properties
liferay-workspace/gradlew
liferay-workspace/settings.gradle
| {
"pile_set_name": "StackExchange"
} |
Q:
Using preventDefault
I've been looking at some code posted by someone and I can't make sense of why he used preventDefault.
var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'), $buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
$windows.hide();
$buttons.on('click', function(e) {
var $id;
e.preventDefault();
$buttons.removeClass('closebutton');
$id = $('#' + this.id.split('-')[0] + '-window');// Get window id
$windows.slideUp();
if(! $id.is(':visible') ) {
$id.slideDown();
$(this).addClass('closebutton');
}
});
It seems to behave exactly the same with or without it. My best guess so far is that it's common practice to use preventDefault/return false in function bodies.
My question is why he used that method at all?
Oh, yeah. I'm new to JavaScript.
http://jsfiddle.net/62NPt/53/
A:
From the docs:
If this method is called, the default action of the event will not be
triggered.
So if your button is an input submit button for example, the event.preventDefault() will prevent the default behaviour of your button and prevent your form from submitting and reload the page. This is normally helpful when you want to apply AJAX call.
| {
"pile_set_name": "StackExchange"
} |
Q:
Haskell: execute IO action and extract value inside list comprehension
I am trying to generate a list of randomized boolean values based on a moving threshold.
This is my code. The function at issue is isActionRandom:
randomBool :: Int -> IO Bool
randomBool p = do n <- randomRIO(1,100)
return (if n > p then True else False)
isActionRandom :: Float -> Int -> Int -> Int -> IO [Bool]
isActionRandom eps n m step = [ randomBool (floor (eps-(0.01*y) * 100))
| x <- [1..(n*m)]
, y <- floor(x/(m*step))]
isActionRandom does not compile because the list created is type [IO Bool] and not IO [Bool] as I intended. How do I "extract" the boolean value from the IO function at each iteration, and build a list of the intended type?
A:
You can use the sequence method from Traversable:
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
In your case, it will have the type:
sequence :: [IO Bool] -> IO [Bool]
| {
"pile_set_name": "StackExchange"
} |
Q:
Couldn't upload a manifest in azure management portal
I am following the post http://blogs.msdn.com/b/exchangedev/archive/2015/01/22/building-demon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow.aspx to develop an application which needs to access the calendar mail and contact API s . I am able to get an id_token . I generated a self signed certificate and have the values for $base64Thumbprint, $base64Value and $keyid. But when i make the changes in the manifest and try to upload it shows an error
"ParameterValidationException=Invalid parameters provided; BadRequestException=One or more properties contains invalid values.;"
"keyCredentials": [
{
"customKeyIdentifier":"tt89GrwSlCRxxUiDfJMW8p29NCU=",
"keyId":"3b65c351-4869-4a6d-6d6f-5fd53fc2a802",
"type":"AsymmetricX509Cert",
"usage":"Verify",
"value":"MIIDLDCCAhagAwIBAgICBNIQK************j0tSzvQmi7DJR0R5gpvii"// have omitted characters in between
}
],
may i know where am i going wrong??
A:
You probably not doing anything wrong. I had this error a few times and in my case it seemed somehow related to the editor putting in some invisible character. Maybe you want to try with a different editor. Give it a try and let me know if you can't get it to work.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I change a .scrollToTop () to a scrollToBottom () in jQuery?
I'm trying to get my code to load some data when the client is at the bottom of the page, but I load it when I scroll up. How can I change this in my code?
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
getData();
});
A:
@Allaiks did answer the question.
I suspect if you are developing online that caching is the issue you can't see the update.
Try to improve your question or add more code and html if it didn't work for you.
Here is a jsfiddle:
$(window).scroll(function () {
if($(window).scrollTop() >= (($(document).height() - $(window).height())))
alert("This is the bottom of the page!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div style="width:200px; height:2000px; background:#b2000b;">Some div</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
ListFragment with Asynctask and Custom Adapter
My problem is very basic, however I can't see the solution to it. That's my 3rd project on Android.
So far I was using fragments with a ListView declared in it, onCreateView where I was inflating my ListView and onActivityCreated to initialize the layout. Now I want to do the same but using ListFragment.
I was using this exmaple as reference: http://developer.android.com/training/basics/fragments/creating.html
Below is modified code that I used for Fragment with a ListView. I have changed this to work with a ListFragment but without success. Can someone help me out? Thank you in advance.
public class PlayersListFragment extends ListFragment {
OnPlayerSelectedListener mCallback;
// URL to make request
private static String URL = Utils.URL;
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
private Dialog pDialog;
// The container Activity must implement this interface so the frag can
// deliver messages
public interface OnPlayerSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onPlayerSelected(int position);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We need to use a different list item layout for devices older than
// Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
// Create an array adapter for the list view, using the Ipsum headlines
// array
setRetainInstance(true);
new PlayersLoadTask().execute();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initLayout();
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
private void initLayout() {
if(getActivity().getIntent()!=null) {
userID = getActivity().getIntent().getIntExtra("id", 0);
} else {
return;
}
playerView = (ListView) getActivity().findViewById(R.id.list);
playersList = new ArrayList<HashMap<String, Object>>();
int[] colors = {0, 0xFFFF0000, 0}; // red for the example
}
@Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected
// list item
// (We do this during onStart because at the point the listview is
// available.)
if (getFragmentManager().findFragmentById(R.id.playerDetailFragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnPlayerSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnPlayerSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onPlayerSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
class PlayersLoadTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(getActivity(), "",
"Loading. Please wait...", true);
}
@Override
protected String doInBackground(String... params) {
try {
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("request", "getPlayers"));
parameters.add(new BasicNameValuePair("clubid", Integer
.toString(userID)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters,
("ISO-8859-1")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// if this is null the web service returned an empty page
if (httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(httpEntity);
if (jsonString != null && jsonString.length() != 0)
{
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
map.put("id", id);
map.put("name", name);
playersList.add(map);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e("ERROR SOMEWHERE!!!! ", e.toString());
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
if (pDialog.isShowing())
pDialog.dismiss();
if (playersList.size() == 0) {
Toast.makeText(getActivity(), "No players in a list",
Toast.LENGTH_SHORT).show();
} else {
playerView.setAdapter(new PlayerListAdapter( // <<== EXCEPTION HERE
getActivity(), R.id.player_list_id,
playersList));
}
}
}
}
And off course a stacktrace from a LogCat which points on this line : playerView.setAdapter(new PlayerListAdapter(
12-18 11:34:30.181: E/AndroidRuntime(16436): FATAL EXCEPTION: main
12-18 11:34:30.181: E/AndroidRuntime(16436): java.lang.NullPointerException
12-18 11:34:30.181: E/AndroidRuntime(16436): at com.statsports.statisticalandroid.PlayersListFragment$PlayersLoadTask.onPostExecute(PlayersListFragment.java:199)
12-18 11:34:30.181: E/AndroidRuntime(16436): at com.statsports.statisticalandroid.PlayersListFragment$PlayersLoadTask.onPostExecute(PlayersListFragment.java:1)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.os.AsyncTask.finish(AsyncTask.java:631)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.os.Looper.loop(Looper.java:137)
12-18 11:34:30.181: E/AndroidRuntime(16436): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-18 11:34:30.181: E/AndroidRuntime(16436): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 11:34:30.181: E/AndroidRuntime(16436): at java.lang.reflect.Method.invoke(Method.java:525)
12-18 11:34:30.181: E/AndroidRuntime(16436): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-18 11:34:30.181: E/AndroidRuntime(16436): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-18 11:34:30.181: E/AndroidRuntime(16436): at dalvik.system.NativeStart.main(Native Method)
A:
That's how I solved my problem. Seem's you must include setListAdapter() in either onCreate() or onActivityCreated(). Code for future reference:
public class PlayersListFragment extends ListFragment {
OnPlayerSelectedListener mCallback;
// URL to make request
private static String URL = Utils.URL;
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
private ProgressDialog pDialog;
// The container Activity must implement this interface so the frag can
// deliver messages
public interface OnPlayerSelectedListener {
/** Called by HeadlinesFragment when a list item is selected */
public void onPlayerSelected(int position);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
initLayout();
new PlayersLoadTask().execute();
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
setListAdapter(new PlayerListAdapter(getActivity(), layout, playersList));
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
private void initLayout() {
if(getActivity().getIntent()!=null) {
userID = getActivity().getIntent().getIntExtra("id", 0);
} else {
return;
}
playerView = getListView();
playersList = new ArrayList<HashMap<String, Object>>();
}
@Override
public void onStart() {
super.onStart();
// When in two-pane layout, set the listview to highlight the selected
// list item
// (We do this during onStart because at the point the listview is
// available.)
if (getFragmentManager().findFragmentById(R.id.playerDetailFragment) != null) {
playerView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnPlayerSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnPlayerSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
mCallback.onPlayerSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
playerView.setItemChecked(position, true);
}
class PlayersLoadTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(getActivity(), "",
"Loading. Please wait...", true);
}
@Override
protected String doInBackground(String... params) {
try {
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("request", "getPlayers"));
parameters.add(new BasicNameValuePair("clubid", Integer
.toString(userID)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters,
("ISO-8859-1")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// if this is null the web service returned an empty page
if (httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(httpEntity);
if (jsonString != null && jsonString.length() != 0)
{
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
map.put("id", id);
map.put("name", name);
playersList.add(map);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e("ERROR SOMEWHERE!!!! ", e.toString());
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
if (pDialog.isShowing())
pDialog.dismiss();
if (playersList.size() == 0) {
Toast.makeText(getActivity(), "No players in a list",
Toast.LENGTH_SHORT).show();
} else if(playerView != null) {
setListAdapter(new PlayerListAdapter(getActivity(), R.id.player_list_id, playersList));
/*playerView.setAdapter(new PlayerListAdapter(
getActivity(), R.id.player_list_id,
playersList));*/
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding a delimiter under some condition
I want to add one more delimiter ';' at the beginning of the line if there is only one item. For example,
a;b
c
d;e
Output:
a;b
;;c
d;e
A:
This is just to give you a hint on how you could proceed with this, checking line by line if there is a delimiter found or not. I'll leave the rest to you :
while read line
do
if [ $(grep -c ';' <<< "$line") -eq 0 ]
then
echo delimiter not found
else
echo delimiter found
fi
done < your_file
| {
"pile_set_name": "StackExchange"
} |
Q:
Paraphrasing a sentence with post modifier
I wrote the sentence B for paraphrasing sentence A.
A: I feel scared, because my girlfriend is obsessive about me.
B: I'm afraid of my girlfriend being obsessive about me.
Having written B, I am suddenly confused whether sentence B really means sentence A or sentence C below, because be+being+adjective is used for temporal change of subject.
C: I feel scared, when my girlfriend becomes obsessive about me.
Can sentence B replace sentence A, C or neither?
A:
The three sentences mean different things.
The first explains why you feel scared - the reason for your fear. Your girlfriend is already obsessive about you.
The second expresses your concern about an undesired development - that your girlfriend may become obsessive about you. At present she is not obsessive about you.
The third states that your are fearful at such times as your girlfriend becomes obsessive about you. When she is not obsessive, you are not scared. This suggests that your girlfriend goes through phases of being obsessive.
(PS: None of your sentences requires a comma.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Dialogflow Google actions - Can I have slot in welcome intent?
I'm trying to build a simple voice app. I can do something like below with google actions SDK.
User : "Talk to Silly name maker"
Response : "Dom"
Can I build something like below:
User : "Ask to Silly name maker two names"
Response : "Dom and Bom"
Note:
I want the interaction in one shot, and for that I need to know the number of names slot in the welcome intent. I tried setting the slots in the welcome intent, but it does not recognize the number of names in the intent.
Any ideas on how to make the welcome intent recognize slots?
A:
The welcome intent doesn't support slots, but you can create a new intent with parameters and allow users to directly go to that intent if you configure it in your Integration settings.
| {
"pile_set_name": "StackExchange"
} |
Q:
What can I use to tunnel under a walkway or driveway?
I have seen Walkway Tunnel Kits being sold in the US, unfortunately I can't find a similar product in the UK. Are there alternative products or methods, that can be used when a product like this is not available?
A:
I have tunneled under a concrete pad using lengths of rigid pipe, a hose, and lots of dedication.
You dig a substantial hole on both sides, then you put the hose in the pipes with a pressure nozzle, then you hammer the pipes through the ground and put them together as you need length.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating Calendar With Task Scheduling Using PHP
I want to create a calendar with the following features in picture
I want to have the time in the left column and the task in the bottom area. I want to drag a task from the bottom list and schedule it in the specified time on specified day.
How can I do this?
A:
Check out http://arshaw.com/js/fullcalendar-1.5.3/demos/external-dragging.html .
| {
"pile_set_name": "StackExchange"
} |
Q:
Split path (String) in 3 pieces
I'm getting a String that represents a path. For testpurposes lets say i'm getting:
abc/def/ghi/jkl/....
I want to spit that string as follows (the 2 first seperated & the rest combined):
Items(0) = "abc"
Items(1) = "def"
Items(2) = "ghi/jkl/..."
I opted to use a regex as follows:
Dim someString = "abc/def/ghi/jkl/...."
Dim Items() As String = Regex.Split(someString, "([_0-9a-zA-Z-]+)/([0-9a-zA-Z]+)/(.*)")
But im getting the following output:
Items(0) = ""
Items(1) = "abc"
Items(2) = "def"
Items(3) = "ghi/jkl/..."
Items(4) = ""
Can someone explain what causes those empty string in the beginning and the end?
I thank you for your time and wish you a pleasant weekend
A:
String.Split in combination with the Skip method can be a readable and compact alternative to solve this:
Dim text = "abc/def/ghi/jkl/...."
Dim parts As String() = text.Split("/"c)
If parts.Count >= 2 Then
Dim items As String() = {parts.First, parts.Skip(1).First, String.Join("/", parts.Skip(2))}
End If
| {
"pile_set_name": "StackExchange"
} |
Q:
How to rename the files of different format from the same folder but different subfolder using python
I have one scenario where i have to rename the files in the folder. Please find the scenario,
Example :
Elements(Main Folder)<br/>
2(subfolder-1) <br/>
sample_2_description.txt(filename1)<br/>
sample_2_video.avi(filename2)<br/>
3(subfolder2)
sample_3_tag.jpg(filename1)<br/>
sample_3_analysis.GIF(filename2)<br/>
sample_3_word.docx(filename3)<br/>
I want to modify the names of the files as,
Elements(Main Folder)<br/>
2(subfolder1)<br/>
description.txt(filename1)<br/>
video.avi(filename2)<br/>
3(subfolder2)
tag.jpg(filename1)<br/>
analysis.GIF(filename2)<br/>
word.docx(filename3)<br/>
Could anyone guide on how to write the code?
A:
Recursive directory traversal to rename a file can be based on this answer. All we are required to do is to replace the file name instead of the extension in the accepted answer.
Here is one way - split the file name by _ and use the last index of the split list as the new name
import os
import sys
directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
os.rename(filePath, newFilePath) #rename your file
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display of en dashes in shiny apps
I am working on an application using the shiny package in R.
My application reads in a file (hierarchy.csv) and uses it as a lookup source to create two columns in a datatable.
This datatable is (i) rendered using the DT datatables function and (ii) exported it as results.csv
hierarchy.csv contains text with en dashes. When run locally these display correctly both in the rendered table and in results.csv.
However, when I publish the app to ShinyApps.io, the en dashes are replaced with < 96 >. (I am using the same browser, Firefox, throughout)
I can get the en dashes to display in the rendered table on shiny.io by replacing them in hierarchy.csv with
"–"
However, I then have this character code rather than en dashes in results.csv.
I suspect I need to specify encoding at some point but I am out of my depth in that regard.
How is the ShinyApps.io server set up to deal with special characters?
Any suggestions?
A:
There is an article dedicated to this topic on the shiny website. Basically you need the fileEncoding argument to specify the encoding explicitly when using read.csv() or write.csv() for the sake of portability between Windows (your local machine) and Linux (ShinyApps.io). For example, if you have encoded hierarchy.csv in UTF-8, you should read it via
read.csv('hierarchy.csv', fileEncoding = 'UTF-8')
Similarly, when writing out data,
write.csv(YOUR_DATA, 'results.csv', fileEncoding = 'UTF-8')
If you download the CSV file written out from shiny, and want to open it locally, you should make sure your application (e.g. LibreOffice) knows its encoding. In your same post in the shiny-discuss mailing list, you said the en-dash was not "displayed" correctly, and it is possible that your application was using a wrong encoding to open the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory allocation by threads in c
How could I reduce memory used by threads in C? Although a thread takes about 8 to 10 MB of memory, is there any way to reduce this memory?
A:
yes you can set the size of thread stack.
pthread_attr_t attribute;
pthread_t thread;
pthread_attr_init(&attribute);
pthread_attr_setstacksize(&attribute,size); // size may be defined by u as 1024,2048,etc
pthread_create(&thread,&attribute,fun,0);
................................................
void *fun(void *arg)
{
....
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Seaborn Plotting Multiple Plots for Groups
How do I plot multiple plots for each of the groups (each ID) below with Seaborn? I would like to plot two plots, one underneath the other, one line (ID) per plot.
ID Date Cum Value Daily Value
3306 2019-06-01 100.0 100.0
3306 2019-07-01 200.0 100.0
3306 2019-08-01 350.0 150.0
4408 2019-06-01 200.0 200.0
4408 2019-07-01 375.0 175.0
4408 2019-08-01 400.0 025.0
This only plots both lines together and can look messy if there are 200 unique IDs.
sns.lineplot(x="Date", y="Daily Value",
hue="ID", data=df)
A:
you can use
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({'id': [3306, 3306, 3306, 4408, 4408, 4408],
'date': ['2019-06-01', '2019-07-01', '2019-08-01', '2019-06-01', '2019-07-01', '2019-08-01'],
'cum': [100, 200, 350, 200, 375, 400],
'daily': [100, 100, 150, 200, 175, 25]
})
g = sns.FacetGrid(df, col = 'id')
g.map(plt.plot, 'date', 'daily')
which gives
but what happens if you have 200 ids?
| {
"pile_set_name": "StackExchange"
} |
Q:
What is $\mbox{Hom}(\mathbb{Z}/2,\mathbb{Z}/n)$?
Simple question (I seem have asked a few like this...)
What is $\mbox{Hom}(\mathbb{Z}/2,\mathbb{Z}/n)$? (for $n \ne 2$)
A:
More generally $\operatorname{Hom}{(\mathbb{Z}/m,\mathbb{Z}/n)}$ is cyclic of order $\operatorname{gcd}(m,n)$. I strongly recommend you to try to prove this on your own. In case of emergency, google for hom z nz z mz.
A:
Try to find the neccessary condition for such a homomorphism first.
If f is a homomorphism from Z/2 to Z/n then clearly f maps the zero element of Z/2 to the zero element of Z/n. Can it map 1 to an arbitrary element of Z/n? No, the mapping should be such that f is a homomorphism. Assuming it is, and $f(1) = x$, clearly $0 = f(0) = f(1+1) = f(1) + f(1) = x + x$ should hold, following which $2x = 0$ in Z/n. So this is a neccessary condition.
It is easy to see that this condition is sufficient as well. So the homomorphisms may be counted in number by counting all such x. This amounts to counting all solutions to the congruence $2x = 0$ in Z/n.
Clearly as $gcd(2,n)|0$ so solutions always exist and they will be gcd(2,n) (which may be either 1 or 2, depending upon whether n is odd or even repectively) in number. So Hom(Z/2,Z/n) will have either 1 or 2 elements. In either case, it will be cyclic because all groups of order 1 and 2 are.
A:
If $f:G\rightarrow H$ is a group homomorphism, then $\text{ord}(f(g))\mid\text{ord}(g)$ for all $g\in G$ because $g^n=e_G$ implies $f(g)^n=f(g^n)=f(e_G)=e_H$.
Thus, if $f:\mathbb{Z}/(2)\rightarrow H$ is a homomorphism, we know that $f(0+(2))=e_H$ because $f$ is a homomorphism, and $f(1+(2))$ must be an element of order dividing 2 in $H$. In fact, given any element $h\in H$ of order dividing 2, we can define a homomorphism $f:\mathbb{Z}/(2)\rightarrow H$ by $f(0+(2))=e_H$ and $f(1+(2))=h$.
Thus, for any group $H$, the homomorphisms $f:\mathbb{Z}/(2)\rightarrow H$ are in bijection with the elements of order dividing 2 in $H$. These are the elements of order 2, along with the identity $e_H$ (which is the only element of order 1, obviously). This explains Theo's suggestion above.
Hint: An element $a+(n)$ of $\mathbb{Z}/(n)$ is of order 2 when $a+(n)\neq 0+(n)$, but $$2(a+(n))=2a+(n)=0+(n),$$
or in other words, $a\not\equiv0\bmod n$ but
$$2a\equiv 0\bmod n.$$
For which $n$ does such an $a$ exist?
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop for pmax () for pairs of variables
I have the following dataframe:
varnames<-c( "aR.0", "aL.0", "aR.1", "aL.1", "aR.3", "aL.3")
a <-matrix (c(1,2,3,4, 5, 6), 2, 6)
colnames (a)<-varnames
df<-as.data.frame (a)
a
aR.0 aL.0 aR.1 aL.1 aR.3 aL.3
[1,] 1 3 5 1 3 5
[2,] 2 4 6 2 4 6
I need to add to the dataframe the vectors containing maximum values of pairs of variables, having:
similar bases ("a" and "a")
similar suffixes ("0" and "0", "1" and "1", "3" and "3")
but different last letters before suffix (R and L).
In several lines it looks like:
df$max.a.0 <- pmax(df [,"aR.0"], df[,"aL.0"])
df$max.a.1<-pmax(df [,"aR.1"], df[,"aL.1"])
df$max.a.3<- pmax(df [,"aR.3"], df[,"aL.3"])
df
aR.0 aL.0 aR.1 aL.1 aR.3 aL.3 max.a.0 max.a.1 max.a.3
1 1 3 5 1 3 5 3 5 5
2 2 4 6 2 4 6 4 6 6
How to perform this task automatically?
I racked my brain trying to write a loop without any success.
Thank you very much in advance
A:
Well, the specifics depend on the specific properties of your dataframe, which are not apparent from the example you give. For instance, you specify that bases should be similar, but there is just a single base "a". It is also unclear whether the order of those variables is always the same.
Anyway, for your current example the following approach might work:
df1 <- df[,grep("aR\\..",colnames(df))]
df2 <- df[,grep("aL\\..",colnames(df))]
pmax(df1,df2)
You could extend the same logic to the general case by (1) making the regular expressions more complex (e.g. to include other bases) and (2) by sorting the column vectors, if necessary, to achieve the identical order required for pmax() function.
| {
"pile_set_name": "StackExchange"
} |
Q:
err_cert_invalid at google chrome and opera
When I try to browse this site it always say connection is not private or certificate is unprotected:
A:
Using Google Chrome:
Put https://aclcdau.com:2083 in the address bar
You will see
Click on Advanced in the lower left corner
Click on Proceed to cloud01.jollyworkshosting.com
| {
"pile_set_name": "StackExchange"
} |
Q:
Найти первое слово строки
Получается задача в чём. Нужно найти первое слово строки, но при этом игнорируя запятые. точки и пробелы перед или после слова.
var string = "Hallo, World";
function firstWord(str) {
// returns the first word in a given text.
var SpaceCode = str.indexOf(" ")
if (str.indexOf === -1) {
return str;
} else if (str.charAt(0) === "," || str.charAt(0) === "" || str.charAt(0) === "." ) {
return str.substr(1, SpaceCode);
} else if(str.charAt(1) === ",") {
return str.substr(0, SpaceCode);
} else {
return str.substr(0, SpaceCode);
}
return 0;
}
console.log(firstWord(string));
Это мой код, немного криво написан. Но суть в чём он ищет первое слово, игнорирует перед словом точку но не игнорирует много торчек например если бы строка была такая (firstWord("... and so on ..."), "and") и почему-то не игнорирует пробел перед словом.
A:
Термин "слово" в контексте регулярных выражений обозначает буквы + цифры + нижнее подчеркивание. Если вам нужно это, тогда:
var matches = '... some_long_word another word ...'.match(/(\w+)/);
var firstWord = matches[1];
Если только слова (русские + английские):
var matches = '... some_long_word another word ...'.match(/([a-zа-яё]+)/i);
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding index to Mysql tables
Which fields should be indexed to speed up the following query?
SELECT *
FROM sms_report
WHERE R_uid = '159'
AND R_show = '1'
ORDER BY R_timestamp DESC , R_numbers
A:
Basing on this information, a composite index on (R_uid, R_show) should be good.
http://dev.mysql.com/doc/refman/5.5/en/multiple-column-indexes.html
To be able to tell anything more, you'd need to show us results of EXPLAIN
http://dev.mysql.com/doc/refman/5.5/en/explain.html
and tell which storage engine is being used.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with titlesec package
I'm helping my girlfriend with her thesis - she wants to eliminate the gap between section headings and the following text. I tried loading the titlesec package, but I get an error if I do:
Error: Entered in horizontal mode.
I've traced the error to the section heading definition in the custom class file we're using. It specifically seems to be the call to #1, but that is pretty crucial...!
MWE:
\documentclass[12pt]{mwe}
\setlength{\parskip}{2ex}
\usepackage{titlesec}
\titlespacing{\section}{0pt}{1.0ex plus -1ex minus -.2ex}{-\parskip}
\begin{document}
\section*{Abstract}
I want this text to be up against the section heading
\end{document}
And this is the problematic excerpt from the cls:
\newcommand{\sect@format}[1]{%
\noindent\protect{%
\@tempdima=\hsize
\parbox{0.99\@tempdima}{%
\smallskip\section@font%
\textcolor{\section@colour}{#1}\smallskip
}%
}%
}%
\sectionfont{\sect@format}
The class file is one I was given for own thesis some time ago, and not something that desperately needs to remain unaltered if there is a better way.
A:
Well, I haven't solved the conflict between the cls file and titlesec, per se - but I have managed to get what I want with the removal of the excerpt quoted above and the addition to the cls file of:
\usepackage{titlesec}
\titleformat{\section}{\normalfont\selectfont\large\color{CambridgeDeepBlue}}{\llap{\hspace* . {-\mylen}\thesection\hfill}}{0em}{}[]
\titlespacing{\section}{0pt}{1.0ex plus -1ex minus -.2ex}{-\parskip}
| {
"pile_set_name": "StackExchange"
} |
Q:
ActiveRecord - querying polymorphic associations
I am using polymorphic associations to track Comments in my project. All very straight forward stuff.
The problem I have is in querying based on the polymorphic association and joining from the Comment model back to it's owner.
So ...
I have a Comment model
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
And a ForumTopics mode:
class ForumTopic < ActiveRecord::Base
has_many :comments, :as => :commentable
end
I have several other "commentable" models that aren't important right now.
All of this works.
What I am trying to do is find all of the Comments that belong to a ForumTopic with a specified condition (in this case, 'featured' == true).
When I try and use a finder to join the models:
@comments = Comment.find(:all
:joins => :commentable
:conditions => ["forum_topics.featured = ? ", true]
)
I receive the following error:
Can not eagerly load the polymorphic association :commentable
Using the AR "include syntax":
@comments = Comment.find(:all
:include => :forum_topics
:conditions => ["forum_topics.featured = ? ", true]
)
returns:
Association named 'forum_topics' was not found; perhaps you misspelled it?
If I try and join with a table name instead of the association name (string instead of symbol):
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
I see:
Mysql::Error: Unknown table 'comments': SELECT comments. FROM comments forum_topics WHERE (forum_topics.featured = 1 )*
(You can see here that the syntax of the underlying query is totally off and the join is missing altogether).
Not sure if what I am doing is even possible, and there are other ways to achieve the required result but it seems like it should be doable.
Any ideas?
Anything I am missing?
A:
Argh!
I think I found the problem.
When joining via:
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
You need the whole join!
:joins => "INNER JOIN forum_topics ON forum_topics.id = comments.commentable_id",
See the ever-awesome:
http://guides.rubyonrails.org/active_record_querying.html#joining-tables
A:
An old question, but there is a cleaner way of achieving this by setting up a direct association for the specific type along with the polymorphic:
#comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :forum_topics, -> { where( comments: { commentable_type: 'ForumTopic' } ).includes( :comments ) }, foreign_key: 'commentable_id'
...
end
You are then able to pass :forum_topics to includes getting rid of the need for a messy join:
@comments = Comment
.includes( :forum_topics )
.where( :forum_topics => { featured: true } )
You could then further clean this up by moving the query into a scope:
#comment.rb
class Comment < ActiveRecord::Base
...
scope :featured_topics, -> {
includes( :forum_topics )
.where( :forum_topics => { featured: true } )
}
...
end
Leaving you to be able to simply do
@comments = Comment.featured_topics
A:
You Need a Conditional, Plus Rails 3+
A lot of people alluded to it in the answers and comments but I felt that people, including myself, would get tripped up if they landed here and didn't read thoroughly enough.
So, here's the proper answer, including the conditional that is absolutely necessary.
@comments = Comment.joins( "INNER JOIN forum_topics ON comments.commentable_id = forum_topics.id" )
.where( comments: { commentable_type: 'ForumTopic' } )
.where( forum_topics: { featured: true } )
Thanks to all, especially @Jits, @Peter, and @prograils for their comments.
| {
"pile_set_name": "StackExchange"
} |
Q:
Galois group of $(x^5-3)(x^5-7)$ over $\Bbb Q$
I am having some trouble with the following question:
Let $f(x)=(x^5-3)(x^5-7)\in\Bbb Q[x]$. Find the degree of the splitting field of $f$ over $\Bbb Q$, and determine the Galois group of $f$ over $\Bbb Q$.
I noticed that $x^5-3$ and $x^5-7$ are irreducible in $\Bbb Q[x]$, and so their Galois groups are isomorphic to a transitive subgroup of $S_5$. I also found that the splitting fields of these two quintics are $\Bbb Q(\sqrt[5] 3,\alpha)$ and $\Bbb Q(\sqrt[5] 7,\alpha)$ where $\alpha^5=1$. Since $\alpha$ has degree $4$ over $\Bbb Q$ and $\sqrt[5] 3,\sqrt[5] 7$ have degree $5$ over $\Bbb Q$, we have that the degrees of these splitting fields are $20$. Hence, we have $$\operatorname{Gal}(x^5-3/\Bbb Q)\cong F_{20}\cong \operatorname{Gal}(x^5-7/\Bbb Q) $$
But now I'm supposed to use a theorem we proved that $\operatorname{Gal}(f/\Bbb Q)$ is a subgroup of the direct product of the above Galois groups. I am not sure how to do this: i.e., $\color{red}{\text{how to determine which subgroup $\operatorname{Gal}(f/\Bbb Q)$ corresponds to}}$.
For the degree of the splitting field of $f$ over $\Bbb Q$, I argued that it is $100$ since the compositum $\Bbb Q(\sqrt[5] 7,\alpha)\Bbb Q(\sqrt[5] 3,\alpha)=\Bbb Q(\sqrt[5] 3,\sqrt[5] 7,\alpha)$ has degree $5\cdot 5\cdot 4=100$ over $\Bbb Q$. $\color{red}{\text{Does this make sense}}$?
I also had another question to determine the Galois group of $(x^3-2)(x^4-2)$ over $\Bbb Q$. I showed that $x^3-2$ has Galois group $S_3$ and $x^4-2$ has Galois group $D_4$. Then I argued that the intersection of the two splitting fields, $\Bbb Q(\sqrt[3]2,\omega)\cap\Bbb Q(\sqrt[4]2,i)$ is just $\Bbb Q$, so we have $\operatorname{Gal}((x^3-2)(x^4-2)/\Bbb Q)\cong S_3\times D_4$. $\color{red}{\text{Does this make sense}}$? In order to show $\Bbb Q(\sqrt[3]2,\omega)\cap\Bbb Q(\sqrt[4]2,i)=\Bbb Q$ I just argued that $\sqrt[4]2,i\notin\Bbb Q(\sqrt[3]2,\omega)$, $\color{red}{\text{is this sufficient}}$?
A:
On the first "Does this make sense?": Yes, it pretty much does. Using the tower law, we get that $$[\mathbb{Q}(\sqrt[5]3,\sqrt[5]7,\alpha):\mathbb{Q}]=[\mathbb{Q}(\sqrt[5]3,\sqrt[5]7,\alpha):\mathbb{Q}(\sqrt[5]7,\alpha)][\mathbb{Q}(\sqrt[5]7,\alpha):\mathbb{Q}(\alpha)][\mathbb{Q}(\alpha):\mathbb{Q}]=5*5*4=100.$$
On your second "Does this make sense?": Yes, it also does. If $K_1$ and $K_2$ are Galois extensions and $K_1 \cap K_2=F$, $$Gal(K_1K_2/F)\cong Gal(K_1/F)\times Gal(K_2/F).$$ So, if $K_1=\mathbb{Q}(\sqrt[3]2,\omega)$ and $K_2=\mathbb{Q}(\sqrt[4]2,i)$ and $Gal(K_1/\mathbb{Q})\cong S_3$ and $Gal(K_2/\mathbb{Q})\cong D_4$, we get the result you got. However, I think that you could be more complete when arguing that $K_1\cap K_2=\mathbb{Q}$, explaining it a bit more- even though you're not wrong.
On the first part, as we argued in the comment section, $Gal(\mathbb{Q}(\sqrt[5]3,\sqrt[5]7,\alpha)/\mathbb{Q})\cong C_5^2\times C_4$. This is due to the fact that, once $\mathbb{Q}(\sqrt[5]3,\sqrt[5]7)\cap \mathbb{Q}(\alpha)=\mathbb{Q},$
$$Gal(\mathbb{Q}(\sqrt[5]3,\sqrt[5]7,\alpha)/\mathbb{Q})\cong Gal(\mathbb{Q}(\sqrt[5]3,\sqrt[5]7)/\mathbb{Q})\times Gal(\mathbb{Q}(\alpha)/\mathbb{Q})\cong Gal(\mathbb{Q}(\sqrt[5]7)/\mathbb{Q})\times Gal(\mathbb{Q}(\sqrt[5]3)/\mathbb{Q})\times Gal(\mathbb{Q}(\alpha)/\mathbb{Q})\cong C_5\times C_5 \times C_4=C_5^2\times C_4 $$
| {
"pile_set_name": "StackExchange"
} |
Q:
ajax xhr lengthComputable return false with php file
i'm doing an ajax request with a XMLHttpRequest in order to show the progress of the request. It's working great with an html file but evt.lengthComputable return false with a php file.
My php file is encoded in utf-8 and contain nothing special.
xhr: function()
{
console.log('xhr');
var xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', uploadComplete, false);
function uploadComplete(event) {
console.log('uploadComplete');
//do stuff
}
//Download progress
xhr.addEventListener("progress", function(evt){
console.log([evt.lengthComputable, evt.loaded, evt.total]);
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
}
}, false);
return xhr;
}
Thanx for helping :) !
A:
Because php file are dynamic, you need to set a correct Content-Length header:
<?
ob_start();
/* your code here */
$length = ob_get_length();
header('Content-Length: '.$length."\r\n");
header('Accept-Ranges: bytes'."\r\n");
ob_end_flush();
| {
"pile_set_name": "StackExchange"
} |
Q:
Why warning sign when visiting https-website?
Sometimes when I visit a website using HTTPS, I get a warning sign next to the URL in my browser (see screenshot; look for yellow/orange arrow) and I wonder if this marks a potential threat or an attack:
The browser gives the reason "This website does not provide information about its owner" (I actually get this in German. The original is "Diese Website stellt keine Informationen über den Besitzer zur Verfügung.". I've marked this message on the screenshot for you. The screenshot also shows details about the certificate that I see there.
This also happens with renowned websites, e.g. it just happened for mail.google.com. Therefor, I'm absolutely sure that there is no problem with the HTTPS-certificates of these websites on the server side. So what's wrong here? Is there a man in the middle attack or did someone tinker with the CA certificates that my browser trusts?
I use MacOS 10.8.5 with Firefox 27.0.1.
A:
Look at the "Technische Details". It says that part of the site were not transferred with encryption, so called "mixed content". And that's the reason for the warnings sign. Maybe you find out where these unencrypted content comes from by looking at the media tab.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to put weight to views added dynamically on an Android layout?
I have the following Layout:
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cat_card_list_item_card"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:minHeight="118dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/effectContainer"
android:orientation="vertical"/>
</com.google.android.material.card.MaterialCardView>
which gets added dynamically with the objects as you see below:
Tremolo + button is one object, and the rest is 2 objects that have each one a vertical seekbar. I want the first object to have height wrap_content, which seems it does,a nd the rest to expand vertically as max as possible, so the seekbars grow. I've made their height "wrap_content":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/paramWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/paramLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle1" />
<TextView
android:id="@+id/curLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textAppearance="@style/TextAppearance.MaterialComponents.Subtitle2" />
<TextView
android:id="@+id/minLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="10"
android:rotation="270" />
<TextView
android:id="@+id/maxLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.25"
android:textAppearance="@style/TextAppearance.MaterialComponents.Caption" />
</LinearLayout>
but they still wont grow. How do I make them take the entire space they can?
A:
You can solve it out with this custom library... Just add this to your build.gradle
implementation 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:1.0.0'
And your XML should be like this:
<com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="10">
<com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar
android:id="@+id/mySeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:splitTrack="false"
app:seekBarRotation="CW90" /> <!-- Rotation: CW90 or CW270 -->
</com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper>
I have tested this, and it will give you exactly what you want
| {
"pile_set_name": "StackExchange"
} |
Q:
Preventing fixed footer from overlapping content
I've fixed my footer DIV to the bottom of the viewport as follows:
#Footer
{
position: fixed;
bottom: 0;
}
This works well if there isn't much content on the page. However, if the content fills the full height of the page (i.e. the vertical scroll bar is visible) the footer overlaps the content, which I don't wont.
How can I get the footer to stick to the bottom of the viewport, but never overlap the content?
A:
A modern "sticky footer" solution would use flexbox.
tl;dr:: set container (body) to display:flex;flex-direction:column and the child (footer) you want to move down to margin-top:auto.
First, we set the body to "flex" its items vertically, making sure that it is 100% height.
Then we set flex: 0 0 50px on the footer element, which means: "don't grow, don't shrink, and have a height of 50px". We could in fact, omit flex attribute entirely and just go with height:50px.
We can set display:flex on things like the <body> itself somewhat recklessly, because children of a flex container have a implicit value of flex: 0 1 auto (aka flex:initial) if omitted, which is (almost) equivalent to flex:none (which is shorthand for
flex:0 0 auto):
The item is sized according to its width and height properties. It
shrinks to its minimum size to fit the container, but does not grow to
absorb any extra free space in the flex container.(MDN)
As far as the sticky part, it's the margin-top:auto on the footer that gives us what we want. Applied within a flex container, auto margins take on a new meaning, instead of the usual "get equal amount of free space", they mean "absorb ALL available free space".
From the spec (8.1. Aligning with auto margins):
Prior to alignment via justify-content and align-self, any positive
free space is distributed to auto margins in that dimension.
Stated more simply:
If you apply auto margins to a flex item, that item will automatically
extend its specified margin to occupy the extra space in the flex
container
Aside: the "normal" flexbox layout approach would probably be to flex a middle section ala <div id="main>...</div> to 100% vertically, which also would make a footer "stick" to the bottom. This approach shows us the flexible box model is, in fact, flexible enough to let us resize/move isolated elements.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#footer {
background-color: #efefef;
flex: 0 0 50px;/*or just height:50px;*/
margin-top: auto;
}
<p>we've assumed only that there's random space-taking content above the footer...</p>
<p>lorem ipsum dolor flex...</p>
<div>
<p>random content.</p><p>random content.</p><p>random content.</p><p>random content.</p>
</div>
<div id="footer">FOOTER</div>
A:
The problem is that fixed position takes it out of document flow. You can add margin-bottom to the body content equal to the height of #Footer. This will ensure that there is always an empty space behind the footer equal to its height, preventing it from overlapping the content.
| {
"pile_set_name": "StackExchange"
} |
Q:
False warning of my past questions having not been well-received on UX
Today, I went to ask a question on UX and received the following warning:
Why am I getting this warning?
My questions have been well received and I've deleted none of my questions on UX. I have never answered any questions on UX. I've provided a screenshot of my questions on UX:
https://ux.stackexchange.com/users/81176/code-play
Is it triggering this message because my last question was a duplicate? The question was still well received. Is this an error with UX?
A:
Your last two questions (1, 2) were closed; this is what triggered the warning.
The threshold for this warning was based on an old, now-defunct system for question-bans. Given the warning no longer corresponds to anything you should be warned about, I've adjusted the parameters to eliminate it outside of extreme scenarios.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you travel in a circular orbit around a massive body?
I am trying to figure out how an object could achieve a perfectly circular orbit. Given a mass for the planet or other body the object is orbiting and a distance from the center of mass, how fast would the object have to be moving perpendicular to the center of mass?
My initial assumption was it would have to be travelling horizontally (relatively speaking) as fast as it was falling towards to center of mass. Is this a correct assumption? I guess I am confused because it is easy to calculate the acceleration towards the center of mass given the distance and mass of the body, but I have no idea how you would go about calculating the velocity necessary.
A:
The condition for staying in a circular orbit is the requirement for the centripetal force to be equal in magnitude to the gravitational pull. To be precise:
$$F_g=F_c,$$
$$mg=\frac{mv^2}{r},$$
where $F_g$ is the absolute value of gravitational force, $F_c$ the absolute value of centripetal force, $g$ the gravitational acceleration, $m$ the mass of the moving object, $v$ its tangential velocity and $r$ the distance from the center of the orbit. You can express the required velcocity from that equation, which yields:
$$v=\sqrt{rg},$$
which is independent of the mass of the object. Note that $g$ is not the gravitational acceleration near the earth's surface, but the acceleration the object experience due to the gravitational field at its current location. It is given by
$$g=G\frac{M}{r^2},$$
where $M$ is the mass of the body around which the moving object orbits and $G$ is Newton's gravitational constant.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add scrollbar to d3.layout.tree()
I am trying to make a tree like this
http://mbostock.github.io/d3/talk/20111018/tree.html
And have the scrollbar on the side. I have a large tree, and it fills up more than I need of the screen or the data is too scrunched up to see.
Is there a way to set a scroll bar for an SVG view coming from d3.js? I know the intent is that it resizes, but if it all fits on the screen the information is too desn
A:
Short answer may not be best but here you can see it done using your referenced repository I created this Gist
https://gist.github.com/CrandellWS/ca7e6626c9e6b1413963
which can be viewed at http://bl.ocks.org/CrandellWS/ca7e6626c9e6b1413963
Basically the answer comes from https://stackoverflow.com/a/11449016/1815624
Where it says to apply overflow:scoll to the containing div of the svg that is bigger.
Hope this helps, for a more robust solution checkout this Gist http://gist.github.com/robschmuecker/7880033 and here's that bl.ocks.org link http://bl.ocks.org/robschmuecker/7880033
| {
"pile_set_name": "StackExchange"
} |
Q:
Find all function $f:\mathbb{R}^+\to \mathbb{R}$ if $xf(xf(x)-4)-1=4x$
Find all function $f:\mathbb{R}^+\to \mathbb{R}$ such that for all $x\in\mathbb{R}^+$ the following is valid:
$$xf\big(xf(x)-4\big)-1=4x$$
All I could do is:
$f(x)> {4\over x}$ for all $x$ so $f(x)>0$ for all $x$.
$(4,\infty )\subseteq {\rm Range}(f)$, since $$f(xf(x)-4)={4x+1\over x} >4$$
Function $g(x)=xf(x)-4$ is injective:
$$ g(x_1)=g(x_2) \implies f(g(x_1))=f(g(x_2))\implies $$ $${4x_1+1\over x_1}={4x_2+1\over x_2} \implies x_1=x_2$$
A:
Partial answer:
Consider the equation $xf(xf(x)-a)-1=ax$ for $a>0$ so that $$f(xf(x)-a)=a+\frac1x.$$ This means that $\lim\limits_{x\to+\infty}f(xf(x)-a)=a$ so that $\lim\limits_{x\to+\infty}f(x)=a$. Further, we have $$\lim_{x\to0^+}f(xf(x)-a)=+\infty$$ and since $f(x)>a/x\implies\lim\limits_{x\to0^+}f(x)=+\infty$, it follows that $\lim\limits_{x\to0^+}xf(x)=a$.
Let $m,n$ be integers such that $m<-1$ and $n>0$. Notice that $$f(x)=\sum\limits_{k=m}^na_kx^k$$ implies $\lim\limits_{x\to0^+}xf(x)=a$ so $a_{-1}=a$ and $a_i=0$ for all $m\le i<-1$. Likewise we have $\lim\limits_{x\to+\infty}f(x)=a$ so $a_0=a$ and $a_j=0$ for all $0<j\le n$. Thus if $f$ is a finite Laurent polynomial then the only solution to the functional equation is $$f(x)=a+\frac ax.$$
A:
Partial answer
Let $g(x)=xf(x)-4$.
Our functional equation becomes
$$\frac{g\circ g(x)+4}{g(x)}=4+\frac1x$$
If there exists an invertible function $\phi(x):\mathbb R^+\to\mathbb R^+$ such that $g(x)=\phi(\phi^{-1}(x)+1)$, direct substitution gives
$$\frac{\phi(z+2)+4}{\phi(z+1)}=4+\frac1{\phi(z)}$$
or $$\phi(z+2)=\left[4+\frac1{\phi(z)}\right]\phi(z+1)-4$$
by substituting $z=\phi^{-1}(x)$.
Clearly, this recurrence relation extends a $\phi(x)$ defined arbitrarily on $(0,2)$ to the whole $\mathbb R^+$. By computing $\phi^{-1}(x)$ this method generates a large class of solution to the functional equation.
(Of course there are certain restrictions on $\phi(x)$ on $(0,2)$ so that $\phi(x)$ is invertible.)
The solution $f(x)=4+\frac4x$ corresponds to $g(x)=4x$ and $\phi(x)=k\cdot 4^x$ where $k$ is a positive constant.
A feature of this special solution is that $\phi(x)$ is continuous. In contrast, if rather arbitrary values are assigned to $\phi(x)$ on $(0,2)$, a discontinuous solution may yield. Below is the graph of $\phi(x)$ where $\phi(x) = x+1$ on $(0,2)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop thru object to output icons javascript
Sorry for the poor title–I didn't know what to put.
Anyways, I have this object I want to loop thru in order to dynamically output some icons onclick:
<button id="btn">hit me</button>
var socialMedia = {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com",
social: function() {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in arguments[0]) {
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social(socialMedia);
}, false);
I know I could remove the method and instantiate it while passing the object, but I was wondering how I could go about it this way. In other words, I want to leave the function as a method of the socialMedia {}. Any pointers?
A:
Just add a if (typeof obj[key] != "string") continue; test to your loop:
…
social: function(obj) {
var output = "<ul>";
var myList = document.querySelectorAll('.socialSpot');
for (var key in obj) {
if (typeof this[key] != "string") continue;
output += '<li><a href="' + this[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
Of course, simply using another object would be so much cleaner:
var socialMedia = {
data: {
facebook: "http://facebook.com",
twitter: "http://twitter.com",
instagram: "http://instagram.com",
dribbble: "http://dribbble.com"
},
social: function(obj) {
var data = obj || this.data;
var output = "<ul>";
for (var key in data) {
output += '<li><a href="' + data[key] + '"><img src="_assets/'
+ key + '.png" alt="' + key + 'icon"></a></li>';
}
output += '</ul>';
var myList = document.querySelectorAll('.socialSpot');
for (var i = myList.length - 1; i >= 0; i--) {
myList[i].innerHTML = output;
};
}
};
var theBtn = document.getElementById('btn');
theBtn.addEventListener('click', function() {
socialMedia.social();
}, false);
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving a 4th order polynomial
I have a fourth order polynomial of the form:
$$y = a_{0} + a_1 x + a_{2}x^{2} + a_{3}x^{3} + a_{4}x^{4}$$
Where the coefficients $a_{0}$, $a_{1}$, $a_{2}$, $a_{3}$ and $a_{4}$ are determined from the result of a fit, and are real numbers. How can I solve this equation in terms of x where $y$ is both real and positive? $x$ should be real, but not necessarily positive.
A:
Get some coefficients:
{a0, a1, a2, a3, a4} = RandomReal[1, 5]
(* {0.59997, 0.0773325, 0.466742, 0.106902, 0.227533} *)
Define a function:
x[y_] := x /. NSolve[y == a0 + a1 x + a2 x^2 + a3 x^3 + a4 x^4, Reals]
Try it:
x[5.5]
(* {-2.04995, 1.82863} *)
Two solutions at y==5.5 for these coefficients. Plot the first:
Plot[x[yy][[1]], {yy, 1, 10}]
To plot the second, change [[1]] to [[2]]. If the number of solutions changes, and you try to plot one this doesn't exist, it'll complain. You can get it to ignore these points by wrapping Plot[] in Quiet[].
A:
There's nothing wrong with the Solve::ratnz message per se. It's just notifying the user of how the solution was computed. Since Solve is purportedly an exact solver, it notifies the user that some rounding may have occurred in computing the solution, in case the user wishes to control the rounding themselves.
Here is a constructed example, which can be analyzed, since it is known what function is being approximated (Exp[x]):
p = InterpolatingPolynomial[{#, Exp@N@#} &[{-2., -1.5, 0., 1.5, 2.}] // Transpose, x];
datarange = {-2., 2.};
sols = x /. Solve[p == y && y > 0 && datarange[[1]] < x < datarange[[2]], x];
Plot[{Log[y], sols} // Flatten // Evaluate, {y, Exp[-2], Exp[2]}]
Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result.
Now a degree-4 equation $p(x) = y$ is going to have, generically, 0, 2, or 4 real roots, and never just 1 except at one value of y, namely an absolute extremum of $p(x)$. Hence, I used datarange[[1]] < x < datarange[[2]] to exclude a spurious solution. Here datarange is an interval of feasible values for x. Implicitly, I'm assuming that extrapolation is to be avoided, and datarange was chosen to be the range of the x coordinates in the data. If extrapolation is acceptable, then datarange may be set to an appropriate interval.
Depending on the fit of p to the data, it's possible for p not to be monotonic over the interval of interest, which presents problems since there will be more than one prediction for x given y. In such a case, the research may have to examine thoroughly the situation and determine any number of things, including the suitability of the fitted polynomial.
| {
"pile_set_name": "StackExchange"
} |
Q:
setOnActionExpandListener and OnActionExpandListener not working
Hi Stackoverflow team,
Below is the my code of search view:
private void setupSearchView(MenuItem searchItem) {
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
searchQuery = null;
updateData();
return true;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
});
SearchManager searchManager = (SearchManager) (getSystemService(Context.SEARCH_SERVICE));
searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
searchView.clearFocus();
searchView.setOnQueryTextListener(onQueryTextListener);
}
}
setOnActionExpandListener and OnActionExpandListener are deprecated and its not working. Can someone help me to fix it with the code?
Thanks in advance
A:
This method was deprecated in API level 26.1.0.
Instead of MenuItemCompat.OnActionExpandListener
Use MenuItem.OnActionExpandListener directly.
SAMPLE CODE
MenuItem item = menu.findItem(R.id.action_order);
item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
isSearch = true;
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
isSearch = false;
return true;
}
});
You can get help this too.
| {
"pile_set_name": "StackExchange"
} |
Q:
docker commit influxdb - no changes in result image
I have big problem with influxdb docker image. I want to save data, databases and tables to file, move file to another host and then restore container with full configuration and data. I tied:
1. docker save / load
2. docker export / import
3. docker commit / run
For influxdb official docker image commands above don't save changes... Everytime container was "clean" with only initial configuration. I have no idea what is wrong... command:
docker diff
only confirms that no changes was saved.
Thank You for Your time and answers.
A:
You need to mount volumes at database location:
docker run -p 8083:8083 -p 8086:8086 \
-v $PWD:/var/lib/influxdb \
influxdb
This will mount current location as bind mount to /var/lib/influxdbin the container (this is where influxdb stores databases.) Then you can tarball the bind mount on docker host and move it to the new host.
Now To the problem:
InfluxDB's Dockerfile declares /var/lib/influxdb as a volume. Volumes are not affected with docker commit.
VOLUME /var/lib/influxdb
| {
"pile_set_name": "StackExchange"
} |
Q:
Discord.js Deleting Command Messages
On my Discord bot (ran off of Node.js), I am having issues for it deleting message commands, so when a user sends a command, the bot replies. How do I make the bot delete the users message, but keep the bots command? Because this doesn't work:
let cnt = message.content
if (cnt !== " ") {
const cn = message.channel
let channel = message.channel.name
let guild = message.guild.name
message.id.delete
console.log(`${s(guild + ', ' + channel)} | ${w(cnt)}`)
cn.send(cnt);
}
(w and s are chalk commands.)
A:
Fixed.
let cnt = message.content
if (cnt !== " ") {
const cn = message.channel
message.delete(500) // ?
let channel = message.channel.name
let guild = message.guild.name
console.log(`${s(guild + ', ' + channel)} | ${w(cnt)}`)
cn.send(cnt);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Exception reading process info, via Process.GetProcesses(string), from Windows 7
I'm having trouble with an established production .NET2 service. The service collects process information and log files from various target computers. It runs at 80 sites without issue; mostly on Windows 2000, Windows XP, and Windows 2003.
Now, running against a Windows 7 target, an exception happens whenever the service attempts to read process information.
The code looks like:
Process[] procs = System.Diagnostics.Process.GetProcesses("10.11.12.13");
Info: The target computer responds to ping and the "adminUser" credentials exist on both the target computer and the service computer.
Exception information:
ex {"Couldn't connect to remote machine."} System.Exception {System.InvalidOperationException} [System.InvalidOperationException] {"Couldn't connect to remote machine."} System.InvalidOperationException
Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
InnerException {"Couldn't get process information from performance counter."} System.Exception {System.InvalidOperationException} [System.InvalidOperationException] {"Couldn't get process information from performance counter."} System.InvalidOperationException
Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
InnerException {"The network path was not found"} System.Exception {System.ComponentModel.Win32Exception}
Message "Couldn't get process information from performance counter." string
Source "System" string
StackTrace " at System.Diagnostics.NtProcessManager.GetProcessInfos(PerformanceCounterLiblibrary)\r\n at System.Diagnostics.NtProcessManager.GetProcessInfos(String machineName, Boolean isRemoteMachine)" string
TargetSite {System.Diagnostics.ProcessInfo[] GetProcessInfos(System.Diagnostics.PerformanceCounterLib)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
Message "Couldn't connect to remote machine." string
To troubleshoot this I disabled the Windows Firewall on the target computer, to no avail. Anyone have any ideas?
If anyone has any suggestions as to which steps and in what order I should be trying I am very appreciative for the assistance.
Update: I executed a "tasklist" command from the monitoring computer, passing the arguments to query the remote (target) computer and I was able to see the same type of process information that I am not able to get programmatically...
The command looked like:
tasklist /s 10.11.12.13
The returned information looked like:
...
notepad.exe 672 1 4,916 K
...
So, why can't .NET see the process information???
A:
Turns out the problem was that the "Remote Registry" service was not running on the target computer!
This explains why whacking the firewall had no effect. Thanks to everyone who offered assistance.
| {
"pile_set_name": "StackExchange"
} |
Q:
SSRS, SQL - Select multiple email addresses as [CC] in Data Driven Subscription
I'm looking to CC 2 people in a Data Driven Subscription
Here's what I currently have CC'ing one person
I've provided little detail I know, let me know if you need anything else
SELECT
eUserName as UserName,
er_EMailAddress as [TO],
er_FullName as FullName,
CONVERT(VARCHAR(10),GETDATE(),103) + ' - Outstanding Calls for ' + er_FullName as Subject,
'[email protected]' as [CC]
FROM
xxxxxx.xxxxxxxx
WHERE
er_status = 'Active' and eUserName in ('username1', 'username2')
A:
Simply make sure that the e-mail addresses are separated by ;, that is [space][semicolon][space].
So for example, if you want to send the report to [email protected] and [email protected], your CC string should look like this:
[email protected] ; [email protected]
A:
I've sorted it, thanks for your help
it should be:
‘[email protected]; [email protected]’ AS [CC]
| {
"pile_set_name": "StackExchange"
} |
Q:
Model update_attributes method returning 'true', but not actually updating the attribute
I have a Game model that has several params, among them: a integer parameter called 'turn' and an 'opponent' parameter. When a player joins a game, I want to update 2 attributes: (1) the attribute 'opponent', (2) the attribute 'turn').
I use the code below for this:
# in games_controller.rb
def update
@game = Game.find(params[:id])
owner = @game.owner.id.to_i
@game.update_attribute(:opponent, current_user)
@game.update_attribute(:turn, owner)
end
The problem is, while the opponent attribute does update, the turn attribute remains nil. When I play with this code in the console, @game.update_attribute(:turn, owner) returns true, but still doesn't update. Any idea why this is happening? Thanks.
Note: I do have turn in my game_params
A:
You are updating :turn and :opponent. In one case you use an id owner.id. In the other case you use the active record object current_user. I think :turn is not the id of the person but the associated model, so you should use owner = @game.owner.
You could also use a single update:
def update
@game = Game.find(params[:id])
@game.update_attributes(:opponent => current_user, :turn => @game.owner)
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does change in speed of a wave make it refract?
When a light wave enters a medium with a higher refractive index (e.g. from air to standard glass) and its speed decreases, why does that make it refract/bend?
I understand that wavelength decreases and frequency stays the same and therefore its speed decreases, but I can't find anywhere whatsoever why the speed decrease cause the wave to refract. So could someone please explain this?
A:
The wave only refracts if it enters the medium at an angle. Follow a single wavecrest; if the wave is entering the medium at an angle, then part of the wavecrest enters the medium first, and starts to slow down, while the other part of the wavecrest is still going fast, and therefore the wavecrest must bend. If the wave enters at a right angle, then the entire wavecrest is slowed down simultaneously and no refraction occurs.
A:
There are several ways to look at it. From what you have, the easiest is to understand it as deriving from Fermat’s principle:
the path taken between two points by a ray of light is the path that can be traversed in the least time
Because light travels slower in the medium of higer refractive index (as you stated), its course will be so that it travels a smaller distance in this medium than in the other. There's a commonly-used analogy for that (apparently from Feynman):
The rescuer wants to reach the drowning person as fast as possible. Because he runs faster than he swims, he won't take a straight path but his optimal path follows Snell's law.
| {
"pile_set_name": "StackExchange"
} |
Q:
ProcessOptions and ProcessKeyvalOptions
\ProcessOptions and \ProcessKeyvalOptions
Which comes first? Does it matter?
\ProcessOptions\relax or \ProcessOptions*
What's the difference? Apparently for keyval there is only the starred version. Which should I use? I looked at the docs and they were not extremely helpful.
I'm creating my own class based on article. I'm using kvoptions for the easy creation of boolean options (\DeclareBoolOption and \DeclareComplementaryOption).
A:
Without package kvoptions
An option is defined by
\DeclareOption{<option>}{<code>}
The star form defines the behavior for unknown options:
\DeclareOption*{<code>}
Options are processed by
\ProcessOptions\relax
that processes the options in the order of declaration in the package file
(seldom useful) or
\ProcessOptions*
that process the options in calling order (usually recommended).
With package kvoptions
With package kvoptions the replacement for \ProcessOptions*
is \ProcessKeyvalOptions. Neither \ProcessOptions nor \ProcessOptions* should be used together with \ProcessKeyvalOptions.
Package options are now interpreted as key value options.
They can be defined with \define@key of package keyval. But package kvoptions
provides some shortcuts: \DeclareBoolOption, \DeclareStringOption, ...
\DeclareOption is replaced by \DeclareVoidOption and \DeclareOption* is replaced by \DeclareDefaultOption.
For a more complete example, see section "3 Example" of package kvoptions.
A:
Testing this on examples, the order of \ProcessOptions and \ProcessKeyvalOptions does not seem to matter, unless of course the code of one set options directly affects that of the other.
For \ProcessOptions\relax vs. \ProcessOptions*, clsguide explains that the order the options is processed in is different:
\ProcessOptions*:
This is like \ProcessOptions but it
executes the options in the order specified in the calling commands,
rather than in the order of declaration in the class or package. For a
package this means that the global options are processed first.
As to which you should use, if you are writing the class completely from scratch, I would advise that you use just one style; either use kvoptions for all of your own options or use exclusively the classical style. If your are building your class on top of an existing one, then it depends on the details: if you are only adding new options then \LoadClassWithOptions may well be sufficient to deal with the old options of that class and you can stick to the kvoptions style for your own additions.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to extract a link from the embedded link with python?
I have a string like this:
<iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FDoctorTaniya%2Fposts%2F1906676949620646&width=500" width="500" height="482" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>
I want to extract link:
www.facebook.com/DoctorTaniya/posts/1906676949620646
How to write a python script to do this?
A:
I think it would be better to use beautiful soup instead.
The text to parse is an iframe tag with the src. You are trying the retrieve the url after href= and before &width in the src attribute.
After that, you would need to decode the url back to text.
First, you throw it into beautiful soup and get the attribute out of it:
text = '<iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FDoctorTaniya%2Fposts%2F1906676949620646&width=500" width="500" height="482" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>'
soup = BeautifulSoup(text)
src_attribute = soup.find("iframe")["src"]
And then there you could use regex here or use .split() (quite hacky):
# Regex
link = re.search('.*?href=(.*)?&', src_attribute).group(1)
# .split()
link = src_attribute.split("href=")[1].split("&")[0]
Lastly, you would need to decode the url using urllib2:
link = urllib2.unquote(link)
and you are done!
So the resulting code would be:
from bs4 import BeautifulSoup
import urllib2
import re
text = '<iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FDoctorTaniya%2Fposts%2F1906676949620646&width=500" width="500" height="482" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>'
soup = BeautifulSoup(text)
src_attribute = soup.find("iframe")["src"]
# Regex
link = re.findall('.*?href=(.*)?&', src_attribute)[0]
# .split()
link = src_attribute.split("href=")[1].split("&")[0]
link = urllib2.unquote(link)
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase undefined error
I'm having problem with sending null data to Firebase and I'm getting this error message:
Runtime Error
Reference.update failed: First argument contains undefined in property
I have:
public save(url: string, params: any) {
return this.af.database.ref('alunos').push().set(params);
}
as params i'm sending:
this.aluno = {
bairro: '',
celular: '',
cep: '',
cidade: '',
cpf: '',
dataNascimento: '',
email: '',
nome: '',
numero: null,
rg: '',
rua: '',
ativo: true,
genero: null,
telefone: '',
uf: ''
};
I already know that the Firebase does not accept undefined but i'm using null, so this shouldn't happen right ? Any way to resolve this without changing the data structure like to string?
A:
You can't pass null to a set command.
set will create a new object. It's not used for updating an existing object.
Therefore null isn't needed, as it's ignored when creating. You should remove numero and genero from your object.
this.aluno = {
bairro: '',
celular: '',
cep: '',
cidade: '',
cpf: '',
dataNascimento: '',
email: '',
nome: '',
rg: '',
rua: '',
ativo: true,
telefone: '',
uf: ''
};
If you want to update an existing object then null is accepted when you make the command this.af.database.ref('alunos').update(params);
Have a read of the docs for more information on the differences between set and update.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why having different version of IE is not triggered
I have the following script which checks for what version of IE I am running and use a stylesheet as well as show an alert statement:
var div = document.createElement("div");
div.innerHTML = "<!--[if lte IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
alert("<=9");
document.write('<link rel="stylesheet" href="theStyles/defaultStyle_ie.css" type="text/css" charset="utf-8" />');
document.write('<link rel="stylesheet" href="theStyles/captionStyle_ie.css" type="text/css" charset="utf-8" />');
}
if (!isIeLessThan9) {
alert(">9");
document.write('<link rel="stylesheet" href="theStyles/defaultStyle.css" type="text/css" charset="utf-8" />');
document.write('<link rel="stylesheet" href="theStyles/captionStyle.css" type="text/css" charset="utf-8" />');
}
What's happening is for IE version 10 and higher it shows >=10 and anything less than IE version 10 still shows >=10
How can I fix it?
EDIT:
This is the updated code which should fix the issue:
<script type="text/javascript">
var isMobile = {
Android: function () {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function () {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i);
},
any: function () {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
navigator.sayswho= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
return M.join(' ');
})();
var browserversion1 = navigator.sayswho.split(" ");
var browserversion2 = browserversion1[1].split(".")[0].split(",");
var isIeLessThan10 = browserversion1[0] == "IE" && browserversion2[0] < 10;
if (!isMobile.any()) {
if (isIeLessThan10) {
alert("IE<10");
document.write('<link rel="stylesheet" href="theStyles/defaultStyle_ie.css" type="text/css" charset="utf-8" />');
document.write('<link rel="stylesheet" href="theStyles/captionStyle_ie.css" type="text/css" charset="utf-8" />');
}
else {
alert("IE>=10 || !IE");
document.write('<link rel="stylesheet" href="theStyles/defaultStyle.css" type="text/css" charset="utf-8" />');
document.write('<link rel="stylesheet" href="theStyles/captionStyle.css" type="text/css" charset="utf-8" />');
}
}
else {
alert("mobile");
document.write('<link rel="stylesheet" href="theStyles/defaultStyle_mobile.css" type="text/css" charset="utf-8" />');
document.write('<link rel="stylesheet" href="theStyles/captionStyle_mobile.css" type="text/css" charset="utf-8" />');
}
</script>
Both IE8 and FF displays the alert, IE>=10 || !IE
A:
I'd rather use this functions to get browser and its version rather than relying on html tag counts, which can easily change with your content: JSFiddle
navigator.sayswho= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
return M.join(' ');
})();
var browserversion1 = navigator.sayswho.split(" ");
var browserversion2 = browserversion1[1].split(".")[0].split(",");
var isIeLessThan10 = (browserversion1[0] == "IE" || browserversion1[0] == "MSIE") && browserversion2[0] < 10;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to determine why a distributed transaction is timing out
I am using LINQ to SQL and a third party SDK that supports distributed transactions. When I realize that a pending update will be updating both SQL records and records in the third party SDK, I am creating a TransactionScope with a 0 (presumably infinite) timeout (although I've also tried 12 hours as a timespan parameter). Then I use GetDtcTransaction on the ambient transaction (created by transactionscope) to get a DTC transaction to link to the third party SDK. Things work nicely for about 10 minutes, but after 10 minutes, the transaction disappears and an error occurs. How do I determine why the transaction is disappearing. I suspect it's a timeout because it regularly occurs after 10 minutes even though slightly varying degrees of work have been done at that point. But I'm at a loss about how to determine what terminated the transaction, why, and how to extend its life.
I've tried tracingthe following events with SQL profiler:
All error and warning events
All Security events except "Audit Schema Object" events
All Transaction events except SQLTransaction and TransactionLog events
All I get around the time of the error are these events:
<Event id="19" name="DTCTransaction">
<Column id="3" name="DatabaseID">1</Column>
<Column id="11" name="LoginName">sa</Column>
<Column id="35" name="DatabaseName">master</Column>
<Column id="51" name="EventSequence">167065</Column>
<Column id="12" name="SPID">10</Column>
<Column id="60" name="IsSystem">1</Column>
<Column id="1" name="TextData">{D662BBC4-21EC-436D-991C-DCB061A34782}</Column>
<Column id="21" name="EventSubClass">16</Column>
<Column id="25" name="IntegerData">0</Column>
<Column id="41" name="LoginSid">01</Column>
<Column id="49" name="RequestID">0</Column>
<Column id="2" name="BinaryData">C4BB62D6EC216D43991CDCB061A34782</Column>
<Column id="14" name="StartTime">2009-11-11T13:55:32.82-06:00</Column>
<Column id="26" name="ServerName">.</Column>
<Column id="50" name="XactSequence">0</Column>
</Event>
<Event id="33" name="Exception">
<Column id="3" name="DatabaseID">9</Column>
<Column id="11" name="LoginName">sa</Column>
<Column id="31" name="Error">1222</Column>
<Column id="35" name="DatabaseName">ACS</Column>
<Column id="51" name="EventSequence">167066</Column>
<Column id="12" name="SPID">19</Column>
<Column id="20" name="Severity">16</Column>
<Column id="60" name="IsSystem">1</Column>
<Column id="1" name="TextData">Error: 1222, Severity: 16, State: 18</Column>
<Column id="41" name="LoginSid">01</Column>
<Column id="49" name="RequestID">0</Column>
<Column id="14" name="StartTime">2009-11-11T13:55:34.717-06:00</Column>
<Column id="26" name="ServerName">.</Column>
<Column id="30" name="State">18</Column>
<Column id="50" name="XactSequence">0</Column>
</Event>
<Event id="33" name="Exception">
<Column id="31" name="Error">8525</Column>
<Column id="8" name="HostName">MARTY755</Column>
<Column id="12" name="SPID">55</Column>
<Column id="20" name="Severity">16</Column>
<Column id="64" name="SessionLoginName">fse</Column>
<Column id="1" name="TextData">Error: 8525, Severity: 16, State: 1</Column>
<Column id="9" name="ClientProcessID">2516</Column>
<Column id="41" name="LoginSid">DB2744F54B5CDB4A8B9E5CA9C209A7AC</Column>
<Column id="49" name="RequestID">0</Column>
<Column id="10" name="ApplicationName">.Net SqlClient Data Provider</Column>
<Column id="14" name="StartTime">2009-11-11T13:55:37.54-06:00</Column>
<Column id="26" name="ServerName">.</Column>
<Column id="30" name="State">1</Column>
<Column id="50" name="XactSequence">236223201284</Column>
<Column id="3" name="DatabaseID">9</Column>
<Column id="11" name="LoginName">fse</Column>
<Column id="35" name="DatabaseName">ACS</Column>
<Column id="51" name="EventSequence">167067</Column>
</Event>
<Event id="162" name="User Error Message">
<Column id="31" name="Error">8525</Column>
<Column id="8" name="HostName">MARTY755</Column>
<Column id="12" name="SPID">55</Column>
<Column id="20" name="Severity">16</Column>
<Column id="64" name="SessionLoginName">fse</Column>
<Column id="1" name="TextData">Distributed transaction completed. Either enlist this session in a new transaction or the NULL transaction.</Column>
<Column id="9" name="ClientProcessID">2516</Column>
<Column id="41" name="LoginSid">DB2744F54B5CDB4A8B9E5CA9C209A7AC</Column>
<Column id="49" name="RequestID">0</Column>
<Column id="10" name="ApplicationName">.Net SqlClient Data Provider</Column>
<Column id="14" name="StartTime">2009-11-11T13:55:37.54-06:00</Column>
<Column id="26" name="ServerName">.</Column>
<Column id="30" name="State">1</Column>
<Column id="50" name="XactSequence">236223201284</Column>
<Column id="3" name="DatabaseID">9</Column>
<Column id="11" name="LoginName">fse</Column>
<Column id="35" name="DatabaseName">ACS</Column>
<Column id="51" name="EventSequence">167068</Column>
</Event>
EventSubClass 16 on the DTCTransaction event indicates "Transaction is aborting".
A:
To extend the timeout, which defaults to 10 minutes maximum when not specified, it's necessary to update C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\Machine.config on the target system (look under C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG if you're running 64-bit). Add this as the last item right under the root level:
<system.transactions>
<machineSettings maxTimeout="23:00:00"/>
</system.transactions>
This will (as an example) set the timeout to 23 hours.
The effective value is visible in System.Transactions.TransactionManager.MaximumTimeout
| {
"pile_set_name": "StackExchange"
} |
Q:
Code::Blocks build from bash
I'm developing a C++ application in Code::Blocks.
My program has a few dependencies and has to run under Linux and Windows, this is why
I use Code::Blocks.
Now I'd like to include Travis CI for testing the builds.
On the Travis server, where I have no X11, I won't be able to run Code::Blocks. How can I build my project without Code::Blocks. (Is there a possibility to create "a Makefile" out of the .cbp-file?
This page (Code::Blocks Wiki) mentions there is a --build flag, but you need Code::Blocks & X11. Is there a server way without X11?
A:
I used cbp2make (C::B Forum entry).
It is quite simple
cbp2make -in project.cbp -out Makefile
and it worked immediatly, even with a more complex configuration
than a simple command line project in Code::Blocks.
It also generates the same build targets as in Code::Blocks. For example make Release would work.
The debian package list shows only a few dependencies, so X11 is not required.
| {
"pile_set_name": "StackExchange"
} |
Q:
error while trying vaadin jpacontainer example
I'm getting
java.lang.NoClassDefFoundError: com/vaadin/data/util/converter/Converter$ConversionException
error. I have made Person class as entity, and my application class is like this:
public class SimplejpaApplication extends Application {
@Override
public void init() {
// TODO Auto-generated method stub
VerticalLayout layout = new VerticalLayout();
JPAContainer<Person> persons =
JPAContainerFactory.make(Person.class, "book-examples");
persons.addEntity(new Person("Marie-Louise Meilleur", 117));
Table personTable = new Table("The Persistent People",persons);
layout.addComponent(personTable);
setMainWindow(new Window("simple",layout));
}
I'm using vaadin-jpacontainer-agpl-3.0-3.0.0-alpha2.jar
Can someone tell why this error happening? thank you.
A:
Converter class is from Vaadin 7 but you are using Vaadin 6. You need to use vaadin-jpacontainer-agpl-3.0-2.1.0 for Vaadin 6.
Or you can upgrade your project to Vaadin 7 and use vaadin-jpacontainer-agpl-3.0-3.0.0-alpha2.jar.
Both jar files can be downloaded from Vaadin add-on page https://vaadin.com/directory#addon/vaadin-jpacontainer.
| {
"pile_set_name": "StackExchange"
} |
Q:
300 ms delay on three.js touch events
I'm working on a three.js project in which I am using TrackballControls to enable touch events. But I found that my code were not working properly. I also evaluated some working examples like http://threejs.org/examples/canvas_geometry_cube.html and found at start there is a small delay of 300 ms. But it do affect a lot in my project. How could I remove this 300 ms delay?
Note : I uses both single and multi touches in my project.
I went through the concept of fastclick ( https://github.com/ftlabs/fastclick ), but for me it doesn't seem to support multi touch. If I'm wrong, please correct me.
A:
Finally I found a way... I was using touch to drag and drop an object in the scene... The actual problem was as follows... The 300 ms delay of touch events get combined to form a large delay... In order to overcome this, I gave a condition so that touch move events are taken with a delay of 300 ms... i.e if one event is taken, the next event taken will be the event after 300 ms... and its working quite fine...
| {
"pile_set_name": "StackExchange"
} |
Q:
Tcl getting parts out of the string
I'm having troubles getting some parts out of a string.
Here is my code :
set top [layout peek $::openedFiles($key) -topcell]
set dim [layout peek $::openedFiles($key) -bbox $top]
# yields output "{name{x1 y1 x2 y2}}"
set coord [split $dim " "]
set x1 [lindex $coord 0]
set x2 [lindex $coord 2]
set y1 [lindex $coord 1]
set y2 [lindex $coord 3]
When I call the command set dim [layout peek $::openedFiles($key) -bbox $top], I get the dimensions back from the loaded file. These dimension are coordinates. The output is always like this: "{name {x1 y1 x2 y2}}".
For example : {test {0 0 100 100}}
I want to get the four coordinates out of the string so I can place them in an array.
I tried splitting the string based on a space, but without success. (keep getting this error: can't read "coord\{clock \{0 0 99960 99960\}\}": no such variable)
Anybody got some thougths?
A:
If you are using a sufficiently recent Tcl, or an older Tcl with the appropriate package - sorry I can't remember details; let me know if you want me to go and dig them out - then you can do
set dim [layout peek $::openedFiles($key) -bbox $top]
lassign $dim firstBit coords
lassign $coords x1 x2 y1 y2
with an older version, and without the extension,
set dim [layout peek $::openedFiles($key) -bbox $top]
set coords [lindex $dim 1]
set x1 [lindex $coords 0]
# etc.
Edit
It turns out that [layout peek...] works slightly differently, so the final working code was
set dim [layout peek $::openedFiles($key) -bbok $top]
set temp [lindex $dim 0]
set coords [lindex $temp 1]
set x1 [lindex $coords 0]
set x2 [lindex $coords 1]
set y1 [lindex $coords 2]
set y2 [lindex $coords 3]
The OP is using Tcl8.4, without TclX.
There's probably scope for improving the variable names, but...
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting MySQL datetime columns which are 0000-00-00 00:00:00
I'm looking for a simple way to select datetime columns which are 000-00-00 00:00:00 (basically the default unset value).
The following query seems to be working:
SELECT * FROM myTable WHERE datetimeCol < 1
But will this reliably work all the time and across different mysql versions?
A:
I would check for "zero" dates like this:
SELECT * FROM myTable WHERE datetimeCol = CONVERT(0,DATETIME)
I would prefer the equality predicate over an inequality predicate; it seems to convey my intentions more clearly. And if there are more predicates in the statement, and if the datetimeCol is a leading column in an index, it may help the optimizer make use of a multi-column index.
A:
Try this:
SELECT * FROM myTable WHERE datetimeCol = '0000-00-00 00:00:00'
Might seem obvious in hindsight ;)
A:
What about comparing to 0 value:
datetimeCol = 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Magic Square Mixups [Challenge]
This kind of puzzle is different than your normal magic square puzzles. Here are 3, in increasing difficulty. Some numbers have been switched, and you have to find them and swap them around to make the magic square valid again.
The zeros are for formatting placeholders.
The numbers in each of line of five squares across, down, and diagonally should add up to 58, but in every row across and column there is one number of out place. Swap these with one another to make the total correct.
16 16 11 09 14
17 09 29 13 01
15 05 06 16 15
07 03 17 11 12
14 17 03 08 06
The numbers in each of line of six squares across, down, and diagonally should add up to 122, but in every row across and column there is one number of out place. Swap these with one another to make the total correct.
21 05 14 31 44 15
30 29 21 09 22 20
36 29 20 10 06 22
06 30 22 30 13 17
10 26 23 17 12 22
27 12 20 13 21 27
The numbers in each of line of seven squares across, down, and diagonally should add up to 123, but in every row across and column there is one number of out place. Swap these with one another to make the total correct.
31 19 10 13 14 32 15
06 21 17 22 30 17 07
17 30 17 24 17 11 08
07 22 33 13 15 17 11
14 16 21 22 13 11 29
16 13 03 19 12 12 43
27 13 19 13 20 18 11
Have fun!!
A:
The answer to the first one is:
16 16 03 09 14
06 09 29 13 01
15 05 06 17 15
07 11 17 11 12
14 17 03 08 16
The answer to the second one is:
13 05 14 31 44 15
30 20 21 09 22 20
36 29 20 10 06 21
06 30 22 30 17 17
10 26 23 29 12 22
27 12 22 13 21 27
The answer to the last one is:
31 08 10 13 14 32 15
06 21 20 22 30 17 07
17 30 17 24 17 11 07
12 22 33 13 15 17 11
14 16 21 19 13 11 29
16 13 03 19 12 17 43
27 13 19 13 22 18 11
To solve these, the easiest way is to:
Calculate the sum of each row and column. Where the column and row sums are equal, the intersection is the number that needs to be swapped. For instance, in the first puzzle, the original puzzle has a total of 69 for the first row and also for the second column. This means that the number in the first row and second column will need to be swapped (17) As the total in these columns is 69 and should be 58, it means that it needs to be 11 less, so should be 6. Note that the value of 6 is located in two places, but the one we want is in row 5, column 5 because these rows both have the same total of 48. Continue in this manner until the whole puzzle is solved.
A:
Partial Answer, but I got the Easy puzzle:
Original
16 16 11 09 14 = 66
17 09 29 13 01 = 69
15 05 06 16 15 = 57
07 03 17 11 12 = 50
14 17 03 08 06 = 48
69 50 66 57 48
Solved:
16 16 03 09 14 = 58
06 09 29 13 01 = 58
15 05 06 17 15 = 58
07 11 17 11 12 = 58
14 17 03 08 16 = 58
58 58 58 58 58
Solution:
Switch 11 in the first row with 03 in the fourth. Take the 06 in the last row, 17 in the second row, and 16 in the third row, and cycle them each once (or backwards twice), in that order. Then, the 06 is in the second row, the 17 is in the third row, and the 16 is in the last row
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Angular Template-driven Forms for User Login/Sign Up
as the title says, I'm trying to use a template-driven Angular form for providing the user a way to sign up and login. I've read a lot about the disadvantages of using template-driven forms when complex validation is required. However, this is not the case here. My question is: are there other disadvantages (that are not instantly evident or that may appear later) in using template-driven forms for such functionality when one usually starts with a clean form and submits data once really?
A:
I've only been working with Angular (as opposed to AngularJS) for a couple of months, but for your simple scenario, I think that a Template-driven form is preferred.
You only need one-way data-binding, and you presumably only have two (or only a small handful of) entry fields, with simple validation requirements (do you need more than "required"?).
I think that Reactive Forms would be overkill here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Eclipse CDT: Stopping at Configuring GDT
I have followed this guide to config Eclipse CDT. guide for Eclipse CDT
After I follow, I can run program on C++. But, when I debug it. In progress windows, it always stop at: Configuring GDB (84%)
Please help me.
Thanks :)
A:
You might want to check out: http://www.eclipse.org/forums/index.php/m/831861/?srch=configuring+GDB#msg_831861
My solution was to install eclipse helios.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are MapViewOfFile memory mappings reused?
If I create 2 separate mappings of the same file in the same process will the pointers be shared?
in other words:
LPCTSTR filename = //...
HANDLE file1 = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0);
HANDLE fileMapping1 = CreateFileMapping(file1, NULL, PAGE_READONLY, 0, 0, 0);
void* pointer1 = MapViewOfFile(fileMapping1, FILE_MAP_READ, 0, 0, 0);
CloseHandle(fileMapping1);
CloseHandle(file1);
HANDLE file2 = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0);
HANDLE fileMapping2 = CreateFileMapping(file2, NULL, PAGE_READONLY, 0, 0, 0);
void* pointer2 = MapViewOfFile(fileMapping2, FILE_MAP_READ, 0, 0, 0);
CloseHandle(fileMapping2);
CloseHandle(file2);
Will pointer1 ever be equal to pointer2?
The reason I am asking is that I have several threads that need to search in a large (300+MB) file and I want to use memory mapping for that. However the process needs to be able to run on an old 32bit xp machine, so if each thread allocated their own copy in virtual memory then I could run out of memory.
A:
Will pointer1 ever be equal to pointer2?
The pointers might be the equal in case MapViewOfFile chooses the same address for the mapping. You don't control this with MapViewOfFile, and you have some control over this with MapViewOfFileEx (last argument lpBaseAddress there).
Each separate MapViewOfFile can create a new mapping over the same physical data, so OS does not need to map the file mapping into the same addresses even if you open two mappings simultaneously, preserving the coherence of data. It is easy to see this by modifying your code slightly:
HANDLE file1 = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
HANDLE fileMapping1 = CreateFileMapping(file1, NULL, PAGE_READWRITE, 0, 0, 0);
void* pointer1 = MapViewOfFile(fileMapping1, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
//CloseHandle(fileMapping1);
//CloseHandle(file1);
HANDLE file2 = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
HANDLE fileMapping2 = CreateFileMapping(file2, NULL, PAGE_READWRITE, 0, 0, 0);
void* pointer2 = MapViewOfFile(fileMapping2, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
INT& n1 = *((INT*) pointer1);
INT& n2 = *((INT*) pointer2);
ATLASSERT(&n1 != &n2); // The pointers are not equal even though they point
// the same data!
INT n3 = 0;
n1 = 2;
n3 += n2;
n1 = 3;
n3 += n2;
ATLASSERT(n3 == 5); // That's 2+3 we wrote through n1 and read through n2
//CloseHandle(fileMapping2);
//CloseHandle(file2);
That is, pointer equivalence is not something you should expect or rely on. Especially if your mapping is large, and reopening does not take place immediately.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does disabling a network protocol affect SQL server performance
The SQL server 2000 process info monitor displays about 100 processes that use a mix of Named Pipes/TCP-IP and (integrated authenticated) users. I was wondering if:
disabling Named pipes - or - TCP-IP (so that all applications are forced to use a single protocol) would affect SQL server performance in anyway
using a single SQL server login instead of multiple windows login would affect SQL server performance in anyway (there is no real need for separate logins)
What I am saying is that if I consolidate all connections into few possible combinations as possible, do I get some performance benefit?
A:
Yes, IMHO you should disable named pipes and use only TCP/IP for better performance. You can force this in the connection strings for your apps and change them one at a time, rather than just shutting off named pipes and then getting a bunch of complaints:
Data Source = tcp:IP-or-host-name[\instance-name]
Don't shut off named pipes until all your apps are using TCP/IP. You can check what your apps are using via sys.dm_exec_connections.net_transport - this will have values such as TCP or Shared Memory. You can check the program too via a query like this:
SELECT c.net_transport, s.program_name, c.client_net_address
FROM sys.dm_exec_sessions AS s
INNER JOIN sys.dm_exec_connections AS c
ON s.session_id = c.session_id;
However, for your second question, using one login or multiple logins won't affect performance much unless you're at the upper end and exceeding your pooled connections limit. In most cases consolidating into a single login will just make it much harder to later audit etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
replace '.' with ',' from a loaded xml
I am loading a xml file and I want to replace the dot with a comma from the xml price output.
$xml = simplexml_load_file($url);
foreach( $xml->product as $product ){
echo $product->manufacturerSKU;
echo $product-minPriceInfo->price;
}
I tried
$product = str_replace(',', '.', $product );
but I does not work on the xml output.
Thanks in advance.
Nils
A:
Have you tried something simple like this
$xml = simplexml_load_file($url);
foreach( $xml->product as $product ){
echo $product->manufacturerSKU;
echo str_replace('.', ',', $product->minPriceInfo->price);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't compile with most recent version of TeX Live (2013)
I have used a tex template for my CV for years. But I recently migrated everything to a new Mac running OS 10.8.4 and the document will no longer compile. I have confirmed that the file compiles fine on OS 10.7.5. I'm working with the latest MacTex distribution on both computers.
The error generated is:
! Incomplete \iffalse; all text was ignored after line 113.
Line 113 is the first usage:
/ressubheading
in this block:
\documentclass[letterpaper,10pt]{article}
\newlength{\outerbordwidth}
\pagestyle{empty}
\raggedbottom
\raggedright
\usepackage[svgnames]{xcolor}
\usepackage{hyperref}
\usepackage{framed}
\usepackage{tocloft}
\usepackage{textcomp}
\usepackage{hanging}
\usepackage{geometry}
\usepackage{url}
\usepackage{hyperref}
\usepackage{lastpage}
\usepackage{fancyhdr}
\usepackage{color,soul}
\usepackage{framed}
% settings for hyperlinks
\hypersetup{
bookmarks=true, % show bookmarks bar?
unicode=false, % non-Latin characters in AcrobatÕs bookmarks
pdftoolbar=true, % show AcrobatÕs toolbar?
pdfmenubar=true, % show AcrobatÕs menu?
pdffitwindow=false, % window fit to page when opened
pdfstartview={FitH}, % fits the width of the page to the window
pdftitle={My Title}, % title
pdfauthor={Me}, % author
pdfsubject={Subject}, % subject of the document
pdfcreator={Creator}, % creator of the document
pdfproducer={Producer}, % producer of the document
pdfkeywords={keywords}, % list of keywords
pdfnewwindow=true, % links in new window
colorlinks=true, % false: boxed links; true: colored links
linkcolor=red, % color of internal links
citecolor=green, % color of links to bibliography
filecolor=magenta, % color of file links
urlcolor=blue % color of external links
}
%-----------------------------------------------------------
%Edit these values as you see fit
\setlength{\outerbordwidth}{2.5pt} % Width of border outside of title bars
\definecolor{shadecolor}{gray}{0.75} % Outer background color of title bars (0 = black, 1 = white)
\definecolor{shadecolorB}{gray}{0.9} % Inner background color of title bars
%-----------------------------------------------------------
%Margin setup
\setlength{\evensidemargin}{-0.25in}
\setlength{\headheight}{0in}
\setlength{\headsep}{0in}
\setlength{\oddsidemargin}{-0.25in}
\setlength{\paperheight}{11in}
\setlength{\paperwidth}{8.5in}
\setlength{\tabcolsep}{0in}
\setlength{\textheight}{9.0in}
\setlength{\textwidth}{7in}
\setlength{\topmargin}{-0.3in}
\setlength{\topskip}{0in}
\setlength{\voffset}{0.1in}
%-----------------------------------------------------------
%Custom commands
\newcommand{\resitem}[1]{\item #1 \vspace{-2pt}}
\newcommand{\resheading}[1]{\vspace{8pt}
\parbox{\textwidth}{\setlength{\FrameSep}{\outerbordwidth}
\begin{shaded}
\setlength{\fboxsep}{0pt}\framebox[\textwidth][l]{\setlength{\fboxsep} {4pt}\fcolorbox{shadecolorB}{shadecolorB}{\textbf{\sffamily{\mbox{~}\makebox[6.762in][l]{\large #1} \vphantom{p\^{E}}}}}}
\end{shaded}
}\vspace{-7pt}
}
\newcommand{\ressubheading}[4]{
\begin{tabular*}{6.5in}{l@{\cftdotfill{\cftsecdotsep}\extracolsep{\fill}}r}
\textbf{#1} & #2 \\
\textit{#3} & \textit{#4} \\
\end{tabular*}\vspace{-6pt}}
%-----------------------------------------------------------
\begin{document}
%%%%%%%%%%%%%%%%%%footer settings
\pagestyle{fancy}
\fancyhf{} % clear all header and footer fields
\fancyfoot[L]{\footnotesize \hspace{0.5in}J. A. Smith}
\fancyfoot[C]{\footnotesize \textit{Curriculum Vitae}}
\fancyfoot[R]{\footnotesize Page \thepage\ of 1 \hspace{0.5in}}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
%%%%%%%%%%%%%%%%%%end footer settings
\begin{tabular*}{7in}{l@{\extracolsep{\fill}}r}
\textbf{\Large Joeseph A. Smith}\\
Assistant Professor -- Department of Biological Sciences\\
Curator of Mammals -- Museum of Natural Science\\
\url{http://www.foo.edu/Smith} & \href{mailto:[email protected]}{\nolinkurl{[email protected]}}
\end{tabular*}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\resheading{Education}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{itemize}
\item
\ressubheading{University of Foo}{Foo}{Ph.D. Ecology \& Evolutionary Biology}{2010}
\begin{itemize}
\resitem{Dissertation Title: blah blah}
\end{itemize}
\item
\ressubheading{Boo State University}{Boo}{B.S. Biology}{2000}
\end{itemize}
\end{document}
It's hard to believe this a problem with the code (even though that's what the error suggests), given that it compiles fine on the earlier OS, but I am not very experienced at customizing tex docs. Thanks in advance for any help!
A:
The most recent version of tocloft has redefined \cdotfill in a way that seems not to agree with your usage of it in \ressubheading.
I don't really know what you're using it for, but anyway here are two fixes:
\usepackage{array} in the preamble (which works because the table preamble is not subject to expansion any more)
\protect\cftdotfill in the definition of \ressubheading (which achieves the same result)
However, if I use
\begin{tabular*}{6.5in}{l@{\extracolsep{\fill}}r}
I get the same result.
| {
"pile_set_name": "StackExchange"
} |
Q:
Growth of ratio based on sum of squared binomial identity
It is a well-known identity that $$\binom{n}{0}^2+\binom{n}{1}^2+\cdots+\binom{n}{n}^2=\binom{2n}{n}.$$
By symmetry of the binomial coefficients, this means the ratio $$\dfrac{\binom{2n}{n}}{\binom{n}{0}^2+\binom{n}{1}^2+\cdots+\binom{n}{n/2}^2}$$ is approximately $2$.
What about if we take only the first half of the term in the denominator? How fast does the ratio $$\dfrac{\binom{2n}{n}}{\binom{n}{0}^2+\binom{n}{1}^2+\cdots+\binom{n}{n/4}^2}$$ grow, as $n\rightarrow\infty$?
A:
In the sum
$${\binom{n}{n/4}^2+\binom{n}{n/4-1}^2+\cdots+\binom{n}{0}^2}$$
the ratio of one term to the next is initially approximately $9$, and increases thereafter. However, it stays between $9$ and $9 + \varepsilon$ for an arbitrarily long time as $n$ gets larger.
Thus the expression is equivalent to $\binom{n}{n/4}^2(1 + 1/9 + 1/81 + \dots) = (9/8)\binom{n}{n/4}^2$ for large $n$.
By Stirling's formula then, the ratio in your problem is equivalent to
$\frac{1}{3}\sqrt{\pi n} \left(\frac{3\sqrt{3}}{4}\right)^n$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get JTextArea with word-wrap to shrink with FormLayout?
I need a non-editable word-wrappable text label/field/area without scrollbars that will resize with its parent without scrollbars. It will be used to display texts of various size, but there will "always" be enough space to display the full text. In the rare event that a user resizes the windows so small that it won't fit, I'd want it to truncate lines/vertically.
I've been searching quite a lot and read any relevant question I can find here without getting to the root of the problem. I've opted for JTextArea because of its word-wrapping capability. I've also tried custom extensions of JLabel but the problem remains the same, so I figure I can just as well stick to JTextArea. The HTML approach is something I'd really like to avoid for multiple reasons. This isn't the first time I've bumped into this problem, and I've solved it previously by compromising the layout (designing the form in a different way). It certainly won't be the last time I face this issue, so I figured I need to find a way instead of keep compromising.
The problem is that while this works as intended initially and when the window is resized to be horizontally larger, horizontally shrinking the window doesn't update the word-wrapping and thus the JTextArea is truncated horizontally.
My testing has shown that this is only true for some layout managers, but I'm not sure at "what level" the problem actually lies. I've also read somewhere that the problem only exists on Windows, but I haven't verified/tested that. I'm using Windows for development, so all I know is that the problem is here for me and exists both with Java 7 and Java 8.
Testing different layout managers has shown:
FormLayout: Doesn't re-wrap when shrinking.
MigLayout: Doesn't re-wrap when shrinking.
GridBagLayout: It does re-wrap when shrinking, but not correctly so some of the text is hidden.
BorderLayout: Works as expected.
BoxLayout: Works as expected if axis is set to Y_AXIS. When set to X_AXIS behaves like FormLayout or MigLayout.
GridLayout: Works as expected.
CardLayout: Works as expected.
The existing application uses FormLayout extensively, and I can't change that without doing a lot of rewriting if at all. Wrapping the JTextAreawith a JPanel with one of the working layouts, e.g BorderLayout doesn't help as long as one of the "broken" layouts are used further up in the hierarchy. It seems like there is some signal that is lost and doesn't reach the children, so I'm stuck as I can't realisticly get rid of FormLayout all the way to the top of the hierarchy.
There are several existing questions here that is very similar, but many are about JTextArea in combination with JScrollPane or some other slight variation and none has helped me find a working solution. By narrowing the issue down as much as possible and supplying a working SCCEE I'm hoping not to be rejected as a duplicate.
SCCEE:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JTextArea;
public class MainFrame {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame window = new MainFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainFrame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new FormLayout(
new ColumnSpec[] {ColumnSpec.decode("pref:grow"),},
new RowSpec[] {RowSpec.decode("pref:grow"),}
));
frame.getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea();
panel.add(textArea, "1, 1, fill, fill");
textArea.setLineWrap(true);
textArea.setText("Lorem ipsum dolor sit amet, ut eum assum debet tacimates, mei nisl electram moderatius ei, veri semper cotidieque eu pri. In quot noster vocent usu, ne augue voluptaria quo. Ex per malis vocibus. Consequat mediocritatem no vel.");
}
}
A:
You can maybe set the column size... but you can also set setPreferredSize of the text area to 0,0:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
public class Test extends JFrame {
final JPanel panel;
final JTextArea textArea;
final FormLayout fl;
public Test() {
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fl = new FormLayout(
new ColumnSpec[] {ColumnSpec.decode("pref:grow"),
// ColumnSpec.decode("pref:grow")
},
new RowSpec[] {RowSpec.decode("pref:grow"),
// RowSpec.decode("pref:grow")
}
);
panel = new JPanel(fl);
this.getContentPane().add(panel, BorderLayout.CENTER);
textArea = new JTextArea();
textArea.setPreferredSize(new Dimension());
panel.add(new JPanel().add(textArea), "1, 1, fill, fill");
// panel.add(new JPanel().add(new JLabel("test")), "1, 2, fill, fill");
// panel.add(new JPanel().add(new JLabel("test")), "2, 1, fill, fill");
textArea.setLineWrap(true);
// textArea.setWrapStyleWord(true);
textArea.setText("Lorem ipsum dolor sit amet, ut eum assum "
+ "debet tacimates, mei nisl electram moderatius ei, veri semper cotidieque eu pri. In quot noster vocent usu, "
+ "ne augue voluptaria quo. Ex per malis vocibus. Consequat mediocritatem no vel.");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test().setVisible(true);
}
});
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
**D/NetworkSecurityConfig: No Network Security Config specified, using platform default**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.example.kotlin">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
this is manifest .xml
and ı add an network security confıg at the xml folder
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config>
<trust-anchors>
<certificates src="system"/>
<certificates src="user"/>
</trust-anchors>
</base-config>
</network-security-config>
And my code
package com.example.kotlin
import android.app.DownloadManager
import android.content.Context
import android.net.ConnectivityManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.w3c.dom.Text
import android.os.StrictMode
import androidx.core.content.getSystemService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn_click_me = findViewById(R.id.button) as Button
btn_click_me.setOnClickListener {
request()
}
val cm= baseContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkinfo=cm.activeNetworkInfo
if (networkinfo != null && networkinfo.isConnected)
{
Toast.makeText(baseContext, "Connected",Toast.LENGTH_LONG).show()
}
}
fun request(){
val tw=findViewById(R.id.textView) as TextView
val queue = Volley.newRequestQueue(this)
val url = "https://www.google.com"
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
tw.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { tw.text = "That didn't work!" })
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
}
ı checked the ınternet connectıon of the emulator and ıt says there ıs a connectıon so emulator has connectıon but ı stıll had :
**D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true**
this error before ı take securıty confıg ıt has saıd that :
**D/NetworkSecurityConfig: No Network Security Config specified, using platform default**
What should ı do for take the request how can ı pass thıs ınternet permıssıon thıng.
ı looked the other entries of thıs title but they couldnt help me so ı make a new entry
support security android
A:
You have to reset your emulator after give permissons and set manifest xml.
| {
"pile_set_name": "StackExchange"
} |
Q:
Excluding names in one list from second list [r]
Let's say I have two lists:
ls1 = list("a","b","c","d","e")
ls2 = list("b","e")
How can I create a third list ls3 which will contain elements that are in ls1 but are not in ls2?
In this example ls3 should contain "a", "c" and "d".
Thanks!
A:
How about setdiff()?
ls1 = list("a","b","c","d","e")
ls2 = list("b","e")
setdiff(ls1, ls2)
That returns list("a","c","d") just as you desire.
| {
"pile_set_name": "StackExchange"
} |
Q:
Solr atomic updates
I have the following steps:
Update record in database
Add record to solr using json
Commit record in database
I insert the record using updatejson call with ?commit=true
But this step takes a long time. Is there a better way to keep thes in sync?
The record needs to be stored in solr. I don't mind it avilable for search immediate.
A:
I solved the issue by doing a ?commitWithin=15000
This persists the data, but does not merge the data with the index. It does this every 15 seconds. Enough to not block my process. Loading 100000 records goes from days to a few hours.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass opportunity's stage value when stage value is edited
I have a VF page that uses <apex:repeat> to show a List<Attachment>, and I want the list to return different attachments based on {!opportunity.stageName} .
VF Page code :
<apex:page standardController="Opportunity" extensions="QueryAttachments">
<apex:repeat value="{!attachmentList}" var="att">
<apex:image styleClass="bigImage" url="{!URLFOR($Action.Attachment.Download, att.id)}" rendered="true"/>
</apex:repeat>
</apex:page>
Controller code:
public class QueryAttachments {
public ApexPages.StandardController controller;
public String stageName{get;set;}
public List <Attachment> attachmentList {
get {
return getAttachmentId();
}
set;
}
public QueryAttachments(ApexPages.StandardController controller) {
this.controller= controller;
}
public List <Attachment> getAttachmentId () {
System.debug('stageName : ' + stageName);
return attachmentList = [Select Id,Name,ParentId,Parent.Name,CreatedDate from Attachment Where Description =: stageName ];
}
}
I can retrieve value="{!opportunity.stageName}" in VF, what I want is to pass it to QueryAttachments controller and query based on it's value.
I don't want to use apex:actionFunction or apex:commandButton, I only want to pass opportunity.stageName when the stage on opportunity sObject is saved and show the associated attachments.
A:
There's no need to explicitly pass anything between your visualforce and your controller extension here. The standardController, which you're placing into this.controller in your constructor has a copy of the same Opportunity that you have access to in the visualforce page through merge expressions like {!Opportunity.StageName}.
You can access this by using the getRecord() method of ApexPages.StandardController.
A brief example would be this
public class MyExtension{
private Opportunity theOpp;
public MyExtension(ApexPages.StandardController con){
// The getRecord() method returns a generic SObject.
// Typecasting is required if you want to store the record
// in a 'concrete' SObject like Opportunity
theOpp = (Opportunity)con.getRecord();
}
public List<Attachment> getAttachments(){
// Standard caveats apply here
// theOpp will only contain fields referenced on your visualforce page
return [SELECT Id FROM Attachment WHERE someField = :theOpp.StageName];
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I find the quadratic equation from highest point on parabola?
If I have a parabola, where the vertex is in $P=(2,0)$, and a point on the parabola is $Q=(-1,-6)$, how can I find the quadratic equation of the form:
$$f(x) = ax^2 + bx + c$$
A:
Vertex form of a quadratic is: $f(x)=a(x-h)^2+k$, where $(h,k)$ is the vertex. So, in our case the vertex is $(2,0)$ so $h=2$ and $k=0$. So we have, $f(x)=a(x-2)^2$. Now, find $a$ by using the point $(-1,-6$). So we have, $-6=a(-1-2)^2$ which gives us $-6=9a$ so $a=-\frac{2}{3}$. So our equation is $f(x)=-\frac{2}{3}(x-2)^2$. Now, multiply this out to get $$f(x)=-\frac{2}{3}x^2+\frac{8}{3}x-\frac{8}{3}$$
A:
Hint: solve $\,f(2)=0\,, \;f'(2)=0\,, \;f(-1)=-6\,$ for $\,a,b,c\,$.
A:
Here is another approach. Since the parabola is symmetric about the axis of symmetry, we know that $(5, -6)$ is another point on the parabola. Since $f(5)=-6=f(-1)$ and $f(2)=0$, it follows that
\begin{align}
4a + 2b + c &= 0\\
a-b+c &= -6\\
25a+5b+c&=0
\end{align}
which you can solve (for example by Gaussian elimination) to get $a=-2/3, b=8/3$ and $c=-8/3$.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access component property in Ember.computed.sort
In Ember 1.13 I have a component that uses Ember.computed.sort:
export default Ember.Component.extend({
sortedItems: Ember.computed.sort("allItems", function(a, b) {
//How to access columnList from here?
}
columnList: ["name","shortcode"]
})
I need to access columnList property of the component to customize the behaviour of comparison function provided to Ember.computed.sort. How to access the columnList inside comparison function in a place indicated in the code above?
A:
If the cloumnList property is under the same component where you use Ember.computed.sort, just use this.get('columnList'); to access the columnList property
...
sortedItems: Ember.computed.sort("allItems", function(a, b) {
this.get('columnList');
}),
...
ember-twiddle example.
| {
"pile_set_name": "StackExchange"
} |
Q:
What would be the php equivalent of this unix command
I need to get the difference of two csv files just like this
comm -13 <(sort file1.csv) <(sort file2.csv) > file3.csv
This works fine but how to achieve the same proces from PHP, some hints to point me in the right direction. (edited)
ABC, 12, 1
DEF, 10, 1
GHI, 0, 0
ABC, 8, 1
DEF, 10, 1
GHI, 2, 0
The final CSV should be like this :
ABC, 8, 1
GHI, 2, 0
No exec() can be used so how would you deal with this in an efficient way with PHP?
I tried the solution from Marc below:
<?php
$file1 = file('file1.csv');
$file2 = file('file2.csv');
sort($file1);
sort($file2);
var_dump($file1);
var_dump($file2);
$diff = array_diff($file2, $file1);
var_dump($diff);
?>
returns this
ABC, 8, 1
DEF, 10, 1
GHI, 2, 0
When I pre-sort them manually it works fine. Yet when I dump the arrays after applying sort they seem sorted?
The problems seems to have been that the last line wasn't followed by a newline character.
$file1 = file('file1.csv',FILE_IGNORE_NEW_LINES);
$file2 = file('file2.csv',FILE_IGNORE_NEW_LINES);
FILE_IGNORE_NEW_LINES seems to fix it.
So Marc's solution works great if you add FILE_IGNORE_NEW_LINES.
A:
$file1 = file('file1.csv');
$file2 = file('file2.csv');
$sorted1 = sort($file1);
$sorted2 = sort($file2);
/// mangle arrays to remove columns 1,3 here...
$diff = array_diff($mangled1, $mangled2);
file_put_contents('file3.csv', implode($diff));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ng-include at click on link
I'm new on AngularJS and I need to include another template by clicking on a link.
I have a nav.html and a header.html. Both included in the index.html.
In header.html I have
<li class="search-box visible-md visible-lg" data-ng-include=" 'views/calls/search.html' ">
calls/search.html
<div class="input-group" data-ng-controller="callSearchCtrl">
<span class="input-group-addon"><i class="fa fa-search text-muted"></i></span>
<input type="text" class="form-control" placeholder="Suchen..."></div>
And I have to include another template in the header by clicking on a menu point (i.e. Contacts) to load the contacts/search.html
<div class="input-group" data-ng-controller="contactsSearchCtrl">
<span class="input-group-addon"><i class="fa fa-search text-muted"></i></span>
<input type="text" class="form-control" placeholder="Suchen..."></div>
to get another search controller.
The case is, that I have a search bar in the header, where I want to search in the loaded content template.
Maybe I've got the wrong mindset to solve this...
Anyone knows a solution?
ADDITION:
Now I put different ng-clicks in my nav like:
<a href="#/contacts/contacts" data-ng-click="selectType('contacts')"><i class="fa fa-users"></i><span>Kontakte</span></a>
But do I have to put the scope function in my HeaderCtrl or in my NavCtrl?
P.S. Sorry for my bad english :-)
Cheers
bambamboole
A:
The simplest and probably most idiomatic is as @coder-john suggests.
data-ng-include="search.option"
In your controller,
$scope.search = {};
$scope.selectType = function (type) {
$scope.search.option = 'views/'+type+'/search.html';
};
$scope.selectType('calls');
where your menu options should invoke the proper handlers, such as
data-ng-click="selectType('calls')"
or
data-ng-click="selectType('contacts')"
as appropriate.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove word from substring
I've got a list of links that looks like this
Item 1
Item 2 (foo)
Item 3
How do I get jQuery to remove the string " (foo)" from the link text?
A:
$('a:contains(foo)').text(function(_, currentText){
return currentText.replace('foo', '');
});
http://jsfiddle.net/EgHkr/
| {
"pile_set_name": "StackExchange"
} |
Q:
No horizontal scrolling in Grails scaffolded views
I have a table with relatively long values in some columns and have dynamic scaffolding turned on for it in my Grails application (I'm using Grails 3.3.8). Thus, on some screen resolutions, they don't fit on the screen and the rightmost columns end up outside of the screen - thing is, the horizontal scrolling bar does not appear then and so the user doesn't even know they're there. The only way to bring them back in is to zoom out - you can't scroll with either the bar (cause it's not there) or the mouse wheel; arrows aren't working either.
How can I fix this so that the horizontal scrolling bar appears like on a "regular" webpage on which content exceeds the size of the screen?
A:
OK, figured this out! So the trick is to edit the assets/stylesheets/main.css file in the app folder, specifically this bit:
body {
background-color: #F5F5F5;
color: #333333;
overflow-x: hidden; /* <<<< */
-moz-box-shadow: 0 0 0.3em #424649;
-webkit-box-shadow: 0 0 0.3em #424649;
box-shadow: 0 0 0.3em #424649;
}
We edit the overflow-x from hidden to auto and voila! :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Jetty mac encoding to UTF-8
I'm running Jetty on OSX on my dev environment. Currently character encoding seems to be faulti (probably mac-roman), overriding Jetty default. How can I force the encoding to be UTF-8? This problem seems to appear only on OSX, linux/windows works fine.
I'm running Jetty from terminal so eclipse-specific solutions aren't of help.
A:
Apparently I was wrong in blaming Jetty for this problem. The reason was maven and how maven brings in the default encoding java-settings.
Setting this env-variable seemed to solve the problem:
export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
Answer found from here.
A:
No problem here however we start Jetty from the javaWrapper (and which should not make a difference).
The only parameter I can see making an impact is setting the file.encoding System Property e.g. -Dfile.encoding=UTF-8
EDIT
( our macs locale are set to utf-8 )
| {
"pile_set_name": "StackExchange"
} |
Q:
When i run the code of curve matching,error comes
I run the code on this page,enter link description here
some error comes.
First,"#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen"
" is necesary in the file std.h?I can not find these included file.
Second,when i comment out the code lines "#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen",then i run the code,many error comes,as follow
I tried,but failed,can someone help me?Thanks in advands!
A:
Eigen is a C++ library for linear algebra that you need to install and include the correct headers.
The source code seems to target Linux. /usr/local/include/eigen3/Eigen/Eigen implies a unix path.
You are on Windows, that won't work. you have to modify the code to work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating, Signing and Verifying Digital Signature
So here's a question from my project.
In this task, we will use OpenSSL to generate digital signatures. Please prepare a file (example.txt) of any size. Also prepare an RSA public/private key pair. Then do the following:
Sign the SHA256 hash of example.txt; save the output in example.sha256.
Verify the digital signature in example.sha256.
Slightly modify example.txt, and verify the digital signature again.
Please describe how you performed the above three operations (e.g., the exact commands that you used, etc.). Describe what you observed and explain your observations. Please also explain why digital signatures are useful in general.
So, I do the following.
1.Create private/public key pair
openssl genrsa -out private.pem 1024
2. Extracting Public key.
openssl rsa -in private.pem -out public.pem -outform PEM -pubout
3. Create hash of the data.
echo 'data to sign' > example.txt
openssl dgst -sha256 < example.txt > hash
4. Sign the hash using Private key to a file called example.sha256
openssl rsautl -sign -inkey private.pem -keyform PEM -in hash > example.sha256
5. Verify the file (example.txt)and the digital signature (example.sha256)
openssl dgst -sha256 -verify public.pem -signature example.sha256 example.txt
After doing all this, I get an error message saying "Verification Failure"
Please correct me if I went wrong somewhere.
A:
Don’t use rsautl for this.
According to PKCS1.5, when signing the format of the data that goes into the RSA operation looks something like this:
<padding><metadata><hash of input>
(The metadata specifies which hash function has been used.)
This format is what openssl dgst -verify is looking for when you try to verify the signature. However this is not what you create in your steps.
First of all the default output of openssl dgst is the hex encoding of the resulting hash, not the raw bytes.
Secondly, rsautl is fairly “low level”, and when signing doesn’t add the metadata that openssl dgst -verify is expecting, although it does add the padding.
These two things together mean that the data you are using looks like this:
<padding><hex digits of hash of input>
Obviously this doesn’t match what openssl dgst -verify is expecting, so the verification fails.
It would be possible to create a correctly formatted input for rsautl, but it would be awkward and involve dealing with ASN.1 details. You could also use rsautl -verify instead of dgst -verify, but that would also require a few more details and would mean you are using a non-standard signature format.
The simplest solution is to use openssl dgst for both the creation and verification of the signature. Replace your steps 3 and 4 (except for creating the example.txt file) with the single command:
$ openssl dgst -sha256 -sign private.pem -out example.sha256 example.txt
This hashes the data, correctly formats the hash and performs the RSA operation it. The resulting file should correctly verify with the openssl dgst -verify command.
| {
"pile_set_name": "StackExchange"
} |
Q:
Image outside post content Wordpress Post
I try to fix so that the images I upload in posts, are positioned outside of the post content width.
Actually I don't know if there is a solution for it, but I have seen several wordpress blogs having it.
Here is a example of how I want it: http://demo.themefuse.com/aesthetic/garance-dore-is-launching-a-podcast-in-partnership-with-the-outnet/
If you see the first image in the post, its wider than the post content.
Is there any solution for this?
A:
I don't think this is a particularly a WP question, but it may affect finer details of the solution. The method in the example you provided uses left and right padding on non image areas. The default WP editor doesn't split up the areas into multiple div's like in the example, though.
You didn't provide your HTML, but, I would approach with something like...
.post-content {
box-sizing: border-box; // so that padding is part of the box area.
}
.post-content > * { // select all elements within your content area, or specifically things like p, h1, h2, etc.
display: block;
padding: 0 150px; // you could use padding using px, vw, etc.
width: 70%; // OR use width. compare this with to the image below
}
.post-content > img:first-of-type { // this might need to change to something to select the first image, or all images
width: 100%; // unlike the other elements, the image goes full width
height: auto;
padding: 0;
}
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.