text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Display message that content depends on variable value
I start external process and after its completion print a message to the user. The message content depends on exit code that this process returns.
I have defined this codes in enum:
public enum ExitCode {
Success = 0,
Warning = 1,
Error = 2
}
I call some method only if the process exited with success.
I have 2 approaches.
First is to use switch statement
switch (process.ExitCode)
{
case ExitCode.Success:
Console.WriteLine("Success message.");
CallSomeMethod();
break;
case ExitCode.Warning:
Console.WriteLine("Warning message.");
break;
case ExitCode.Error:
Console.WriteLine("Error message.");
break;
default:
Console.WriteLine("Unknown exit code.");
break;
}
Second way is to create dictionary with (StatusCode, messageContent) pairs
if (dictionary.TryGetValue(process.ExitCode, out msg))
{
Console.WriteLine(msg);
if (process.ExitCode == ExitCode.Success)
{
CallSomeMethod();
}
}
else
{
Console.WriteLine("Unknown exit code.");
}
Which version is more elegant? Feel free to reject both and propose better solution.
A:
This answer applies only when you want to have well defined messages across whole application.
I would use neither.
Let me first explain why and then my proposition.
Critique
Assuming you are going to use your enum elsewhere some duplication might occur. Imagine souch example: you decided to use switch in some method in catch closure and this looks good because it is clean enough. However since you built an entire enum for simply displaying the message to the user you probably would want to use it in other method or class which is very handy.
What do I propose ?
I propose something what I like to call "descriptors", it is somewhat between dictionary and switch.
What would you do is create attributes over each enum with it's description :
public enum ExitCode {
[Description("Success message")]
Success = 0,
[Description("Warning message")]
Warning = 1,
[Description("Error message")]
Error = 2
}
and then add an extension method to your application (Source)
public static class EnumHelper
{
public static string GetDesc(this ExitCode enumVal)
{
var type = typeof(ExitCode);
var memInfo = type.GetMember(enumVal.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
return ((DescriptionAttribute)attributes[0]).Description;
}
}
or similar. Hence you have beautiful alternative to your switch:
if(process.ExitCode == ExitCode.Success){
CallSomeMethod();
}
Console.WriteLine(process.ExitCode.GetDesc());
Code is untested but you might get the idea. Furthermore, if you want to have more freedom with messages you can add second argument to extension method:public static string GetDesc(this ExitCode enumVal, string additionalComment)
and use it as such:
Console.WriteLine(process.ExitCode.GetDesc("More comment needed");
A:
The Problem I have with your switch example is that it isn't immediately apparent that there is extra logic being applied to the case where the exit code is Success and the problem with your dictionary approach is that is a lot of code for a something simple like showing a message.
So I would've used a switch or if() Console.WriteLine(...)
and then an extra
if (process.ExitCode == ExitCode.Success) SomeOtherMethod();
afterwards to make it clear that logic is happening on success.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I allow regular non-admin users to view other users' emails?
Email is now an included field in core, but the stock email for users seems to be set to private; only users with administrator privileges or the user themselves can see.
I'd like to allow other users to see this basic field, without having to create yet another email field where someone has to copy the information over from the other other simply for the ability for it to be visible.
This should be a fairly easy/common practice, but I can't find anything yet.
How do I allow regular non-admin users to view other users' emails?
A:
One route you can take is to allow users the View user information permission and display this information on the user profile page.
To do so, override user.html.twig in your theme (copy it from core/modules/user/templates/user.html.twig to your theme's template directory) then inject the email into the template via hook_preprocess_user() in your mytheme.theme file:
/**
* Implements hook_preprocess_user()
*/
function mytheme_preprocess_user(&$variables) {
$variables['mail'] = $variables['user']->getEmail();
}
In this example, you'll be able to user {{ mail }} to insert the email variable into your user profile template.
A:
I had a similar use case. Here's another solution:
I added a new email field to users' profiles, and in a custom module (I did this is Drupal v8.1), use hook_user_presaveSee Drupal Api:
function MYMODULE_user_presave(User $user){
$user->set('field_profile_email', $user->getEmail());
}
Then you can use this new field in Views, for example, in a department contact list, as was mentioned in a comment to the question. You could use Field Permissions to further enhance this as well.
This does have the downside of creating a second field, but the function avoids having to manually copy it, and it's now available anywhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как отследить открытие нового приложения либо смену активного окна?
Как отследить открытие нового приложения либо смену активного окна?
A:
Средствами .NET нельзя получить информацию о смене активного окна или создании нового окна - нужно использовать глобальные хуки. Отслеживание активаций идет через хук CBTProc (устанавливается SetWindowsHookEx). В этом хуке нужно смотреть на события:
HCBT_ACTIVATE
HCBT_CREATEWND
Нужно будет создать библиотеку для хуков, установить ее в систему и по активации хука слать сообщение в приложение на .NET. Ну, а чтобы отлавливать свои сообщения в .NET, нужно переопределить WndProc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending SMS through Twilio using PHP
Hi Twilio and PHP dev,
I am newbie to PHP. Can anyone show me a simple sample code of php that accepts sms from twilio.
I mean I need a simple phph code that I can include in my site which accepts a sms message from twilio.
I need one way communication only as of now!
Plz, somebody give a example with few lines of code. I am struggling with php from long back.
Thanks,
Kris.
A:
Twilio has some sample code on how to send SMS messages through their API:
http://www.twilio.com/docs/howto/sms-notifications-and-alerts
http://www.twilio.com/resources/tarball/sms-notification.zip
| {
"pile_set_name": "StackExchange"
} |
Q:
Should implicit conversion work in the context of a template argument?
To be more explicit, should a compiler treat a true_type value as true in the first argument of enable_if, because true_type is really std::integral_constant<bool, true>, and integral_constant defines the type conversion function operator value_type?
The following is the simplest test code:
#include <type_traits>
template <typename T>
std::enable_if_t<std::is_pod<T>{}>
test(T)
{
}
int main()
{
test(true);
}
It is accepted by GCC and Clang, but rejected by MSVC (up to Visual Studio 2019 v16.3.1).
A:
Your code is well-formed, converted constant expression should be considered for non-type template parameter.
The template argument that can be used with a non-type template parameter can be any converted constant expression of the type of the template parameter.
A converted constant expression of type T is an expression
implicitly converted to type T, where the converted expression is a
constant expression, and the implicit conversion sequence contains
only:
constexpr user-defined conversions (so a class can be used where integral type is expected)
The conversion operator of std::is_pod inherited from std::integral_constant is constexpr user-defined conversions, then the converted bool from std::is_pod is converted constant expression and could be applied.
As the workaround (I suppose you've realized) you can use std::is_pod_v<T> (since C++17) or std::is_pod_v<T>::value instead.
A:
To answer the more general question, yes it should be accepted. MSVC defaults to C++14, so I'll be basing the answer on that standard.
[temp.arg.nontype]
1 A template-argument for a non-type, non-template template-parameter
shall be one of:
1.1 - for a non-type template-parameter of integral or enumeration
type, a converted constant expression ([expr.const]) of the type of
the template-parameter; or
[expr.const]
3 An integral constant expression is an expression of integral or
unscoped enumeration type, implicitly converted to a prvalue, where
the converted expression is a core constant expression. A converted
constant expression of type T is an expression, implicitly converted
to a prvalue of type T, where the converted expression is a core
constant expression and the implicit conversion sequence contains only
user-defined conversions, lvalue-to-rvalue conversions ([conv.lval]),
integral promotions ([conv.prom]), and integral conversions
([conv.integral]) other than narrowing conversions ([dcl.init.list]).
Since integral_constant supports a constexpr operator T() and this user defined conversion may appear in a converted constant expression, your code is perfectly valid. What MSVC seems to get hung up on is its parsing. For when I tried your example, it spat this out
<source>(4): error C2059: syntax error: '<end Parse>'
<source>(4): error C2143: syntax error: missing ';' before '{'
<source>(4): error C2143: syntax error: missing '>' before ';'
<source>(4): error C2988: unrecognizable template declaration/definition
<source>(4): error C2059: syntax error: ';'
<source>(4): error C2447: '{': missing function header (old-style formal list?)
<source>(4): error C2988: unrecognizable template declaration/definition
<source>(4): error C2059: syntax error: '>'
<source>(6): error C2143: syntax error: missing ';' before '{'
<source>(6): error C2447: '{': missing function header (old-style formal list?)
<source>(11): error C3861: 'test': identifier not found
Microsoft's handling of templates is historically different to GCC's or Clang's, and that could account for this problem in parsing.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you force Linux to detect a PS/2 device (e.g. mouse) on demand?
I plugged in a PS/2 mouse while inside my Gnome desktop, but Linux doesn't recognize it.
Linux will only recognize the PS/2 mouse if it is plugged in before booting the machine (like a normal scenario).
In this case, I forgot to plug in the mouse, plugged it in when I got to the desktop, but realized that it doesn't work.
How do I detect PS/2 devices (my mouse) in real time so I don't have to reboot just to use a mouse?
A:
That's just the way that the PS/2 port works. Unlike the USB, the PS/2 was not designed to be hot-plugged. If you need the hot-plugging capability, use a USB mouse. Otherwise, there is no guarantee that any solution will work consistently.
A:
There is anecdotal evidence that restarting the X Server or switching to a a different virtual terminal and back will cause PS/2 devices to be re-detected. I don't have a PS/2 device to test with at the moment though but it may just work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Generate SSH Keypairs (private/public) without ssh-keygen
I'm working on a Ruby/Rack application that needs to generate SSH keypairs. As much as I'd like to call ssh-keygen from the application, I can't because it's designed to run on Heroku and they don't support calling that command.
I've been able to get private/public RSA keys using OpenSSL in the Ruby standard library doing the following:
key = OpenSSL::PKey::RSA.generate(2048)
# => -----BEGIN RSA PRIVATE KEY----- ....
key.public_key
# => -----BEGIN RSA PUBLIC KEY----- ....
Unfortunately an RSA public key and an SSH public key is not the same thing, even though they can be generated from the same RSA key. An SSH public key looks something like the following:
ssh-rsa AAAAB3NzaC1yc2EAAAABIwA.....
Is it possible to generate SSH keys or convert RSA keys to SSH in Ruby without using ssh-keygen?
A:
It may not have been the case when you had the problem, but the net-ssh library patches OpenSSL::PKey::RSA and ::DSA with two methods:
#ssh_type - returns "ssh-rsa" or "ssh-dss" as appropriate
and #to_blob - returns the public key in OpenSSH binary-blob format. If you base64-encode it, it's the format you're looking for.
require 'net/ssh'
key = OpenSSL::PKey::RSA.new 2048
type = key.ssh_type
data = [ key.to_blob ].pack('m0')
openssh_format = "#{type} #{data}"
A:
Turns out this was much more complicated than I anticipated. I ended up writing the SSHKey gem to pull it off (source code on GitHub). SSH Public keys are encoded totally differently from the RSA public key provided. Data type encoding for SSH keys are defined in section #5 of RFC #4251.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I make a simple user profile URL with Express and Node?
I want to make URL for users profiles similar to Twitter or Facebook:
https://twitter.com/<id_or_something>
https://www.facebook.com/<id_or_something>
With something like this routes:
router.get("/:id", (req, res, next) => {
// Code...
});
And the Id has to be something that I can make with MongoDB like some custom ID by the user itself or some ID generated by MongoDB.
A:
So I did this and worked:
const User = require('../models/user');
router.get('/:id', (req, res, next) => {
const userUD = req.params.id
User.findOne({'nickname: userID'})
.exec()
.then(doc => {
res.render('user.hbs', {
name: doc.name,
nick: doc.nickname
});
})
.catch(err => {
console.log(err);
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
socket() function from nacl sdk returns -1
I have build chrome app with nacl module which calls socket() function, but the function returns -1. I have compiled the module with -lnacl_io linker option. Also I have tried to run Goolgle Chrome with --allow-nacl-socket-api=localhost. I call this function with the next arguments:
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
Why is this function failed?
A:
Don't forget to call nacl_io_init_ppapi function
| {
"pile_set_name": "StackExchange"
} |
Q:
Repeat javascript function at **:**:00
I can run a function every 60 seconds doing this:
Timer: function() {
setInterval(fxn, 60000)
},
But is there a way to run a function at the turn of every minute? IE at 11:20:00, 11:21:00, etc?
A:
You can do it with setTimeout():
function onTheMinute(fn) {
function ms() {
var now = new Date();
return (60 - now.getSeconds()) * 1000;
}
function timer() {
fn();
setTimeout(timer, ms());
}
setTimeout(timer, ms());
}
That sets a timeout to happen on the next minute boundary and call a function when that happens. Each time, a new timer is set for the subsequent minute.
It'd make it slightly more accurate to check milliseconds too, but the timer isn't that accurate anyway.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I drop a column from multiple dataframes stored in a list?
Apologies as I'm new to all this.
I'm playing around with pandas at the moment. I want to drop one particular column across two dataframes stored within a list. This is what I've written.
combine = [train, test]
for dataset in combine:
dataset = dataset.drop('Id', axis=1)
However, this doesn't work. If I do this explicitly, such as train = train.drop('Id', axis=1), this works fine.
I appreciate in this case it's two lines either way, but is there some way I can use the list of dataframes to drop the column from both?
A:
The reason why your solution didn't work is because dataset is a name that points to the item in the list combine. You had the right idea to reassign it with dataset = dataset.drop('Id', axis=1) but all you did was overwrite the name dataset and not really place a new dataframe in the list combine
Option 1
Create a new list
combine = [d.drop('Id', axis=1) for d in combine]
Option 2
Or alter each dataframe in place with inplace=True
for d in combine:
d.drop('Id', axis=1, inplace=True)
| {
"pile_set_name": "StackExchange"
} |
Q:
AdMob new policy starts implementing support for app-ads.text
I received a mail two days ago titled "AdMob starts implementing support for app-ads.txt files". My problem is that I am app developer and I don't have any domain. What should do for this purpose? Secondly, I have lots of app on the Play Store; do I need to buy new domain for every app?
A:
Well, I found the easiest way to let users use app-ads.txt. I think we cannot use it without having a domain. So, I have a solution, Go to https://www.freenom.com and you can get a domain there for free! But only with extensions: .tk, .ml, .gq, .ca, .ga.
After registering a domain there, you can use it as you like.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problems with open panel
I try to open a panel with jQuery Mobile.
The panel should come from the left and push the page, but it seems like the panel overlay the whole side.
In the console i get the error:
Uncaught Error: cannot call methods on panel prior to initialization; attempted to call method 'open'
My HTML:
<div data-role="page">
<div data-role="header">
<header>
<div id="header">
<a href="#menue_panel" id="menu-btn" class="ui-btn ui-btn-icon-notext ui-corner-all ui-icon-bars ui-nodisc-icon ui-alt-icon ui-btn-left">Menu</a>
<h1 id="headline">Text</h1>
<div class="clean"></div>
</div>
</header>
</div>
</div>
<footer>
</footer>
<div data-role="panel" id="menue_panel" data-position="left" data-display="push">
<ul class="ui-alt-icon ui-nodisc-icon">
<li><a href="start.html" data-ajax="false">Startseite</a></li>
<li><a href="medis.html" data-ajax="false">Medikamente</a></li>
</ul>
</div>
My JS
$( document ).ready(function() {
$( "#menu-btn" ).on( "click", function() {
$( "#menue_panel" ).panel( "open" );
});
});
I don't know why it doesnt work.
A:
The panel should be inside the page DIV.
see docs here http://demos.jquerymobile.com/1.3.0-beta.1/docs/panels/
| {
"pile_set_name": "StackExchange"
} |
Q:
Structuring MVC Routes
I have the following url structure, and just trying to figure out the best Routes to configure.
EDIT: Added more url's
/cars/{name} (shows general information about a car)
/cars/{name}/models (shows a list of models for a particular car)
/cars/{name}/models/{id} (shows a specific model for a particular car)
/cars/{name}/models/edit (add a new model which would be an action)
/cars/{name}/models/{id}/owners (a list of owners for a particular model)
/cars/{name}/models/{id}/owners/create (add a new owner)
So far, I have
routes.MapRoute(
name: "CarReleases",
url: "cars/{name}/models/{id}",
defaults:
new
{
controller = "Releases",
action = "Index",
id = UrlParameter.Optional
}
);
This works if I use /cars/{name}/models, but obviously, I don't have the action available for the models page. Do I have to create a new route map for this situation?
I also have the CarController, which is mapped as follows:
routes.MapRoute(
name: "Cars",
url: "cars/{name}/{action}",
defaults: new { controller = "Cars", action = "Details", id = UrlParameter.Optional }
);
As you can see, I have a general mixture of actions and dynamic requests. Bit confused the best way to put this into maproutes.
A:
Order your routes from the most specific to the least specific. In my example all actions are mapped to the controller Cars; however, you may separate them. For example:
Owners:
routes.MapRoute(
name: "owners",
url: "cars/{name}/models/{id}/owners/{action}/{ownerId} ",
defaults: new { controller = "Cars", action = "OwnerIndex", id = UrlParameter.Optional, ownerId = UrlParameter.Optional }
);
Models:
routes.MapRoute(
name: "models",
url: "cars/{name}/models/{action}/{id}",
defaults: new { controller = "Cars", action = "ModelIndex", id = UrlParameter.Optional }
);
Cars:
routes.MapRoute(
name: "Cars",
url: "/cars/{name}/{action}/{id}",
defaults: new { controller = "Cars", action = "Index", id = UrlParameter.Optional }
);
Notice the default action was changed to Index so it lists all when you omit the action and Id (you may need to change it if you decide to keep them all in one controller)
Regarding your question whether you should keep them in one single controller, I think that's fine unless you would like to separate admin functions (edit, delete, etc) from viewing. In any case you can still have them in one controller and just add the Authorize attribute.
[Authorize(Roles = "admin")]
public ViewResult Delete(int id){}
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery pass parameter to called function
I want to pass this:
$('.info-top').css({position:'absolute'});
to the called thumbHover function on the window resize. Can anyone show me how to do this?
function thumbHover() {
$('.thumb').hover(function () {
$('.info-top').text('Hover Text');
},
function () {
if (!$('.info-top').hasClass('active')) {
$('.info-top').text('');
}
});
}
thumbHover();
window.onresize = function () {
thumbHover();
if ($(".thumb").css("margin-bottom") === "1px") {
$('.info-top').appendTo('#Grid');
} else {
$('.info-top').appendTo('#middle');
}
};
A:
Pass the position value as a string parameter to the thumbHover function. Check if the parameter exists and do your thing.
window.onresize = function () {
thumbHover("absolute");
if ($(".thumb").css("margin-bottom") === "1px") {
$('.info-top').appendTo('#Grid');
} else {
$('.info-top').appendTo('#middle');
}
};
function thumbHover(positionVal) {
if (positionVal.length) {
$('.info-top').css({
position: positionVal
});
}
$('.thumb').hover(function () {
$('.info-top').text('Hover Text');
},
function () {
if (!$('.info-top').hasClass('active')) {
$('.info-top').text('');
}
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to construct a URI with username password for mongo C driver.
I am using mongo 3.0.8. I have an authenticated user admin with password admin. I am able to connect to the mongo shell as follows.
mongo admin -u amdin -p amdin
However, i tried to connect to using the following C code. This gives me an error
WARNING: client: Failed to connect to: ipv4 127.0.0.1:27017,
error: 111, Connection refused
char URI[256];
snprintf(URI,256,"mongodb://admin:[email protected]:27017/?authSource=admin");
mongoc_client_t *client = mongoc_client_new(URI);
A:
The error error: 111, Connection refused is a networking error.
Your URI expecting to find the server listening on port 27017 of the same machine (127.0.0.1). Possible issues:
Server not running
Server not on that port
Server is bound to the "real ip address" of the machine.
There is local firewall (e.g. iptables) blocking access
Maybe an SELinux problem?
If this is a Linux box, these commands might help diagnose:
netstat -an -A inet | grep LISTEN
/sbin/iptables -L
| {
"pile_set_name": "StackExchange"
} |
Q:
DRF-Haystack SearchIndex returning from ALL index classes?
I'm using haystack with elasticsearch backend in django, and drf-haystack to implement serializers for results.
I first created a StudentIndex, which indexes over StudentProfiles to use in searches for students in search_indexes.py
class StudentIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(
document=True,
use_template=True,
template_name="search/indexes/user_search_text.txt")
//other indexes or indices or whatever
def get_model(self):
return StudentProfile
def index_queryset(self, using=None):
return StudentProfile.objects.filter(user__is_active=True)
Which is passed to the serializer and viewset in views.py:
class StudentSerializer(HaystackSerializer):
class Meta:
index_classes = [StudentIndex]
class StudentSearchView(ListModelMixin, HaystackGenericAPIView):
index_models = [StudentProfile]
serializer_class = StudentSerializer
pagination_class = None
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
and everything was fine and dandy....UNTIL I added two more indexes over other profiles and a single view/serializer to handle them. All exist in the same respective files:
search_indexes.py
class TeacherIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(
document=True,
use_template=True,
template_name="search/indexes/user_search_text.txt")
//other indexes or indices or whatever
def get_model(self):
return TeacherProfile
def index_queryset(self, using=None):
return TeacherProfile.objects.filter(user__is_active=True)
class StaffIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(
document=True,
use_template=True,
template_name="search/indexes/user_search_text.txt")
//other indexes or indices or whatever
def get_model(self):
return StaffProfile
def index_queryset(self, using=None):
return StaffProfile.objects.filter(user__is_active=True)
and added to views.py:
class StaffSerializer(HaystackSerializer):
class Meta:
index_classes = [StaffIndex, TeacherIndex]
class StaffSearchView(ListModelMixin, HaystackGenericAPIView):
index_models = [StaffProfile, TeacherProfile]
serializer_class = StaffSerializer
pagination_class = None
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
NOW....each view goes to its own url endpoint (/student-search and /staff-search respectively), but ONLY the staff-search endpoint properly returns Staff and TeacherProfile results, while the student-search, in a seperate endpoint with seperate view and models and indexes all explicitly stated, is return StudentProfiles AND Teacher and StaffProfiles and I can not for the life of me figure out why.
If anyone has run into this before, I'd really appreciate help solving, and more importantly, understanding, this issue.
Thanks in advance!
A:
Well, for future people with the same issues, here's all i needed to do to solve it.
I'm using the DRF-Haystack genericviewapi, and on the view, I simply defined the filter_queryset to use the proper haystack connection (which ignored other indices). So for example:
class StudentSearchView(ListModelMixin, HaystackGenericAPIView):
index_models = [StudentProfile]
serializer_class = StudentSerializer
pagination_class = None
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def filter_queryset(self, queryset):
queryset = super(HaystackGenericAPIView, self).filter_queryset(queryset)
return queryset.using('student')
Everything now works properly :)
| {
"pile_set_name": "StackExchange"
} |
Q:
android customize tablerow with imageview overflow tablerow
i am trying to create a tablelayout to show one user's profile picture and his name.Everything works fine except the layout is wired. the image view overflow the tablerow. i set the tablerow layout_height="70dp" and iamgeview layout_height ="50dp" and layout_margin="10dp" in order to vertically centrallize the image.
tablerow xml:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="70dp"
android:orientation="horizontal"
android:layout_marginBottom="1dp"
android:background="#fff">
<ImageView
android:layout_height="50dp"
android:layout_width="50dp"
android:id="@+id/pic"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:background="#f00"/>
<TextView
android:layout_height="20dp"
android:layout_width="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginRight="25dp"
android:id="@+id/value"
android:textColor="#000"
android:layout_alignParentRight="true"
android:layout_weight="3.0"
android:textAlignment="gravity"
android:gravity="right"
/>
</TableRow>
tablelayout xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff">
<TableLayout android:id="@+id/contact_table"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#aaa">
</TableLayout>
</ScrollView>
java code:
table =(TableLayout)findViewById(R.id.contact_table);
LayoutInflater inflater = getLayoutInflater();
TableRow row = (TableRow)inflater.inflate(R.layout.profilerow, table, false);
ImageView tag = (ImageView)row.findViewById(R.id.pic);
new DownloadImageTask(tag).execute(me.getDp_address());
TextView value = (TextView)row.findViewById(R.id.value);
value.setText(me.getFirst_name()+" "+me.getLast_name());
table.addView(row);
TableRow row2 = (TableRow)inflater.inflate(R.layout.centertextrow,table ,false);
table.addView(row2);
private class DownloadImageTask extends AsyncTask<String,Void,Bitmap>{
ImageView img;
public DownloadImageTask(ImageView bmImage){
this.img = bmImage;
}
@Override
protected Bitmap doInBackground(String... urls) {
String url_string = urls[0];
Bitmap micoin = null;
try {
InputStream in = new java.net.URL(url_string).openStream();
micoin = BitmapFactory.decodeStream(in);
} catch (IOException e) {
Log.i("michaellog","error a");
//Log.e("michaellog",e.getMessage());
e.printStackTrace();
}
return micoin;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
img.setImageBitmap(bitmap);
}
}
here is an image of how it looks like:link
the image shift down.
A:
Aloha!
I ran into the same type of problem when creating a list of youtube feeds that was put into a table view for our university app. The only difference I see from my layout and yours is I have added a android:scaleType="centerCrop" to the tableview cell that is created. This should scale your image to fit in the correct area. I am also using a linear layout instead of the tableRow type for each cell in the table that gets populated. I would also check out the answer here as well. https://stackoverflow.com/a/15832564/877568
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/semesterButtonLL"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:layout_width="50dip"
android:id="@+id/image"
android:src="@drawable/icon72"
android:layout_height="50dip"
android:scaleType="centerCrop">
</ImageView>
<TextView android:text="TextView"
android:id="@+id/text"
android:textColor="@color/usu_blue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip">
</TextView>
</LinearLayout>
As for the code you provided everything looks ok on how you are bringing the data in and if it is displaying the image on the link you provided then it may be as simple as adding the centerCrop to the line in your xml. I hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
include multiple parts using ngInclude
I am making a WebApp with angularJS and I have something that irritates me.
<!doctype html>
<html>
<head>
<title>webapp</title>
<link href="css/angular-bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="app">
<div class="container">
<h1>WebApp</h1>
<div ng-controller="home as homeCtrl" ng-cloak class="ng-cloak" class="wrapper">
<div ng-include="'blocks/item.html'"></div>
<div ng-include="'blocks/something.html'"></div>
<div ng-include="'blocks/health.html'"></div>
<div ng-include="'blocks/mana.html'"></div>
<div ng-include="'blocks/running.html'"></div>
<div ng-include="'blocks/out.html'"></div>
<div ng-include="'blocks/of.html'"></div>
<div ng-include="'blocks/ideas.html'"></div>
</div>
</div>
</body>
</html>
Every item, i have to write another include. is there a way to include these and any additions in the future with one command?
A:
Firstly, in your controller create the alphabet array (as shown here)
function genCharArray(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
}
$scope.charArray = genCharArray('a', 'z'); // ["a", ..., "z"]
Then, in your template:
<div ng-controller="home as homeCtrl" ng-cloak class="ng-cloak" class="wrapper">
<div ng-repeat="letter in charArray" ng-include="'blocks/' + letter + '.html'"></div>
</div>
[edit]
If you want to work with any generic list and not specifically the alphabet as in the original post, just use an array and initialize it with whatever.
$scope.charArray = ['lemon', 'tree', 'apple'];
The point here is using ng-repeat to iterate over any number of objects you like, and dynamically create the ng-include elements appropriately.
| {
"pile_set_name": "StackExchange"
} |
Q:
Assign evil-mode keys dependent on major-mode
I would like to assign evil-mode normal-state key bindings dependent on what major mode I am currently working in.
E.g. I am using org-mode and I want a set of keys and if I use AucTeX I want a different set of keys.
Potentially there are keys that behave differently under different major modes because I want to keep a certain naming logic.
I tried assigning keys using different minor-modes, however the last loaded minor-mode overwrites the previously assigned key bindings. Switching to a different window with a different major mode does not switch the key bindings back.
A:
You can use evil-define-key.
For example to bind "a" in normal-state to different commands in org-mode and emacs-lisp-mode, you would do:
(evil-define-key 'normal org-mode-map "a" 'bar)
(evil-define-key 'normal emacs-lisp-mode-map "a" 'foo)
Now "a" in normal state is bound to command bar in org-mode and command foo in emacs-lisp-mode.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to set data attribute using jQuery Data() API
I've got the following field on an MVC view:
@Html.TextBoxFor(model => model.Course.Title, new { data_helptext = "Old Text" })</span>
In a seperate js file, I want to set the data-helptext attribute to a string value. Here's my code:
alert($(targetField).data("helptext"));
$(targetField).data("helptext", "Testing 123");
The alert() call works fine, it shows the text "Old Text" in an alert dialog. However, the call to set the data-helptext attribute to "Testing 123" does not work. "Old Text" is still the attribute's current value.
Am I using the call to data() incorrectly? I've looked this up on the web, and I can't see what I'm doing wrong.
Here's the HTML markup:
<input data-helptext="Old Text" id="Course_Title" name="Course.Title" type="text" value="" />
A:
It is mentioned in the .data() documentation
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)
This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
The demo on my original answer below doesn't seem to work any more.
Updated answer
Again, from the .data() documentation
The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'
I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.
Updated demo (2015-07-25)
Also see jQuery Data vs Attr?
HTML
<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
<tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>
JavaScript (jQuery 1.6.2+)
var $changeMe = $('#changeMe');
var $log = $('#log');
var logger;
(logger = function(setter, getter, note) {
note = note || '';
eval('$changeMe' + setter);
var result = eval('$changeMe' + getter);
$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");
$('#changeData').click(function() {
// set data-key to new value
logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
// try and set data-key via .attr and get via some methods
logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");
// bonus points
logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");
return false;
});
$('#changeData').click();
Older demo
Original answer
For this HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
and this JavaScript (with jQuery 1.6.2)
console.log($('#foo').data('helptext'));
$('#changeData').click(function() {
$('#foo').data('helptext', 'Testing 123');
// $('#foo').attr('data-helptext', 'Testing 123');
console.log($('#foo').data('data-helptext'));
return false;
});
See demo
Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.
A:
I was having serious problems with
.data('property', value);
It was not setting the data-property attribute.
Started using jQuery's .attr():
Get the value of an attribute for the first element in the set of
matched elements or set one or more attributes for every matched
element.
.attr('property', value)
to set the value and
.attr('property')
to retrieve the value.
Now it just works!
A:
@andyb's accepted answer has a small bug. Further to my comment on his post above...
For this HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
You need to access the attribute like this:
$('#foo').attr('data-helptext', 'Testing 123');
but the data method like this:
$('#foo').data('helptext', 'Testing 123');
The fix above for the .data() method will prevent "undefined" and the data value will be updated (while the HTML will not)
The point of the "data" attribute is to bind (or "link") a value with the element. Very similar to the onclick="alert('do_something')" attribute, which binds an action to the element... the text is useless you just want the action to work when they click the element.
Once the data or action is bound to the element, there is usually* no need to update the HTML, only the data or method, since that is what your application (JavaScript) would use. Performance wise, I don't see why you would want to also update the HTML anyway, no one sees the html attribute (except in Firebug or other consoles).
One way you might want to think about it:
The HTML (along with attributes) are just text. The data, functions, objects, etc that are used by JavaScript exist on a separate plane. Only when JavaScript is instructed to do so, it will read or update the HTML text, but all the data and functionality you create with JavaScript are acting completely separate from the HTML text/attributes you see in your Firebug (or other) console.
*I put emphasis on usually because if you have a case where you need to preserve and export HTML (e.g. some kind of micro format/data aware text editor) where the HTML will load fresh on another page, then maybe you need the HTML updated too.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# ASP.NET Core building dynamic forms
I want to implement something similar like SharePoint online does and that is the list functionality. I want to create dynamic lists add new columns, etc. The user can fill in the form and save the data.
The bottle neck is the database, I have some hard time understand how this should be built.
I was thinking to create dynamic SQL Server tables, columns, etc, but maybe this is not the good approach. Can somebody advise on how the database should look like?
I was thinking about creating one table called Lists and there store List properties. Then a many to many relation to another table called Fields where I can store all fields related to a specific form. Many to many relation because some fields are common for all forms like: Id, CreatedBy, Created, Modified, ModifiedBy, etc. Now comes the difficult part. Where should I store the actual data? Should I create another table called FormData and store in there the data? And what relation should it have with Lists and Fields tables?
A:
NoSql approach seems to be a simple one. If you think about databases only as IO devices, which shouldn't contain any "business" logic, the fact that memory cost and memory reading/writng time(SSD) become lower - you will have little bid more options for your issue.
For example you can save field's collection in one object
{
"key": "form1",
"fields" : [ "Id", "CreatedAt" ]
}
Based on that object you can generate view with list or form of created fields.
You can introduce own "object" for field with more data you need for view generation and for data processing.
{
"key": "form1",
"fields" : [
{ "Name": "Id", "Type": "string" },
{ "Name" "CreatedAt", "Type": "DateTime" }
]
}
The actual data can be saved in one object too
{
"formKey": "form1",
"Name": "FirstName LastName",
"CreatedAt": "2017-04-23T18:25:43.511Z"
}
On client side this data can be easily saved as json object and sended to the server.
On server side you can deserialize that object as Dictionary<string, object> and handle it in dynamic way
var formEntity = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestBody);
var name = formEntity["Name"].ToString();
If you tightly attached to the relational database, you can save "raw json" in NVARCHAR column and one identity column.
For processing data you will be able to deserialize it to the Dictionary<string, object>.
With field object { "Name" "CreatedAt", "Type": "DateTime" } you can convert values to the expected types for correct validation and processing.
You will be able to search for data based on dynamic fields ro create dynamic reports, where user can create his own reports.
Because structure of fields not dynamic you can save forms and fields structure in relational way. Below is my suggestion for sql server database.
CREATE TABLE Forms (
Id INT IDENTITY(1,1) NOT NULL
)
CREATE TABLE Field(
Id INT IDENTITY(1,1) NOT NULL,
Name NVARCHAR(30) NOT NULL,
TypeName NVARCHAR(30) NOT NULL, -- Or INT -> can represent SqlDbType enum in c#
)
-- many to many relation of Form and Fields
CREATE TABLE FormFields (
FormId INT NOT NULL,
FieldId INT NOT NULL,
PRIMARY KEY (FormId, FieldId)
)
-- because data is "dynamic" it should be saved as string (json format)
CREATE TABLE FormData(
Id INT IDENTITY(1,1) NOT NULL,
FormId INT NOT NULL,
Data NVARCHAR(MAX) NOT NULL, -- json format
)
And consider to use Microsoft version of NoSql - DocumentDB
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX closing application modal dialog
I'm using this example to create application modal dialog. When I click exit button on my dialog (red one in top right corner) everything works fine. Dialog gets closed and then I can open it normaly. But when I try to add a Button which closes my dialog, everything works fine until I try to reopen it. After that, it throws me a IllegalStateException (I'll update answer with this exception if needed).
This is an event handler which demonstrates how I close a dialog:
btnClose.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dialog.close();
}
});
Can someone tell me how to properly close application modal dialog? Thanks in advance.
A:
Edit
I see you found your issue, guess I just keep my answer with the sample code in case somebody else has a similar issue.
Your btnClose action works for me, so the issue is probably in some code which you have not posted.
Here is a sample I created to test it:
import javafx.application.Application;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class DialogClosing extends Application {
@Override public void start(final Stage stage) {
final Button showDialog = new Button("Show Dialog");
showDialog.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
showDialog(stage, showDialog);
}
});
StackPane layout = new StackPane();
layout.getChildren().setAll(
showDialog
);
layout.setStyle("-fx-padding: 10px;");
stage.setScene(
new Scene(
layout
)
);
stage.show();
}
private Stage showDialog(Window parent, final Node showControlNode) {
showControlNode.setDisable(true);
final Stage dialog = new Stage();
dialog.initOwner(parent);
dialog.initStyle(StageStyle.UTILITY);
dialog.setX(parent.getX());
dialog.setY(parent.getY() + parent.getHeight());
Button closeDialog = new Button("Close Dialog");
closeDialog.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
dialog.close();
}
});
dialog.setOnHidden(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent windowEvent) {
showControlNode.setDisable(false);
}
});
VBox layout = new VBox(10);
layout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(
new Label("Hello World!"),
closeDialog
);
layout.setStyle("-fx-padding: 10px;");
Scene scene = new Scene(
layout,
125,
100
);
dialog.setScene(scene);
dialog.show();
return dialog;
}
public static void main(String[] args) { launch(args); }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding custom view in a loop cause out of memory error
I am trying to add a custom view multiple times from xml to another view in an android activity. But it causes out of memory error after opening and closing that activity few times. Here is the code:
ImageLoader imageLoader = new ImageLoader(currentActivity.getApplicationContext());
FlowLayout postsLayout = (FlowLayout) findViewById(R.id.tab_posts);
postsLayout.removeAllViews();
for (final Post post : postsData) {
RelativeLayout profilePostItem = (RelativeLayout) View.inflate(this, R.layout.drawer_item, null);
ImageView postPic = (ImageView) profilePostItem.findViewById(R.id.post_pic);
String picUrl = post.getSingleImageURL();
if(picUrl != null && !picUrl.equals("null"))
{
postPic.setTag(picUrl);
imageLoader.DisplayImage(picUrl, currentActivity, postPic, R.drawable.default_item);
}
profilePostItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(currentActivity, PostDetailsActivity.class);
intent.putExtra("postID", Integer.toString(post.getPostId()));
currentActivity.startActivity(intent);
}
});
postsLayout.addView(profilePostItem);
}
and here is the drawer_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/post_pic"
android:layout_width="140dp"
android:layout_height="140dp"
android:background="#FFFFFF"
android:src="@drawable/default_user_pic"
/>
</RelativeLayout>
Here is the LogCat output:
09-06 22:32:45.566: D/dalvikvm(11857): GC_BEFORE_OOM freed <1K, 6% free 46549K/49095K, paused 67ms, total 67ms
09-06 22:32:45.566: E/dalvikvm-heap(11857): Out of memory on a 67816-byte allocation.
09-06 22:32:45.566: I/dalvikvm(11857): "Thread-15875" prio=4 tid=53 RUNNABLE
09-06 22:32:45.566: I/dalvikvm(11857): | group="main" sCount=0 dsCount=0 obj=0x4325e6d8 self=0x53269790
09-06 22:32:45.566: I/dalvikvm(11857): | sysTid=12239 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=1395039200
09-06 22:32:45.566: I/dalvikvm(11857): | schedstat=( 124808833 28013003 46 ) utm=10 stm=1 core=1
09-06 22:32:45.566: I/dalvikvm(11857): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
09-06 22:32:45.566: I/dalvikvm(11857): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652)
09-06 22:32:45.566: I/dalvikvm(11857): at com.company.testapp.utils.ImageLoader.decodeFile(ImageLoader.java:139)
09-06 22:32:45.566: I/dalvikvm(11857): at com.company.testapp.utils.ImageLoader.getBitmap(ImageLoader.java:81)
09-06 22:32:45.566: I/dalvikvm(11857): at com.company.testapp.utils.ImageLoader.access$0(ImageLoader.java:73)
09-06 22:32:45.566: I/dalvikvm(11857): at com.company.testapp.utils.ImageLoader$PhotosLoader.run(ImageLoader.java:196)
09-06 22:32:45.566: D/skia(11857): --- decoder->decode returned false
09-06 22:32:45.566: W/dalvikvm(11857): threadid=53: thread exiting with uncaught exception (group=0x41aee2a0)
09-06 22:32:45.566: E/AndroidRuntime(11857): FATAL EXCEPTION: Thread-15875
09-06 22:32:45.566: E/AndroidRuntime(11857): java.lang.OutOfMemoryError
09-06 22:32:45.566: E/AndroidRuntime(11857): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
09-06 22:32:45.566: E/AndroidRuntime(11857): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652)
09-06 22:32:45.566: E/AndroidRuntime(11857): at com.company.testapp.utils.ImageLoader.decodeFile(ImageLoader.java:139)
09-06 22:32:45.566: E/AndroidRuntime(11857): at com.company.testapp.utils.ImageLoader.getBitmap(ImageLoader.java:81)
09-06 22:32:45.566: E/AndroidRuntime(11857): at com.company.testapp.utils.ImageLoader.access$0(ImageLoader.java:73)
09-06 22:32:45.566: E/AndroidRuntime(11857): at com.company.testapp.utils.ImageLoader$PhotosLoader.run(ImageLoader.java:196)
09-06 22:32:45.651: I/dalvikvm-heap(11857): Clamp target GC heap from 48.757MB to 48.000MB
09-06 22:32:45.651: D/dalvikvm(11857): GC_FOR_ALLOC freed 180K, 6% free 46583K/49159K, paused 68ms, total 68ms
09-06 22:32:45.651: I/dalvikvm-heap(11857): Forcing collection of SoftReferences for 63616-byte allocation
09-06 22:32:45.736: I/dalvikvm-heap(11857): Clamp target GC heap from 48.757MB to 48.000MB
09-06 22:32:45.736: D/dalvikvm(11857): GC_BEFORE_OOM freed 0K, 6% free 46583K/49159K, paused 82ms, total 82ms
09-06 22:32:45.736: E/dalvikvm-heap(11857): Out of memory on a 63616-byte allocation.
09-06 22:32:45.736: I/dalvikvm(11857): "Thread-15874" prio=4 tid=49 RUNNABLE
Can anyone tell why it is leaking memory?
A:
I have solved this issue by replacing my ImageLoader with Universal Image Loader.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to catch exception of Gradle task of type Exec
I've created a gradle task to check if a program is installed, it works fine but I discovered that it can throw an exception on environments where the command I am executing does not exist. I've tried to catch the exception that is thrown but no luck. How can I gracefully handle the exception and continue the build process if my task fails due to the command not existing?
Error:
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':isGitLFSInstalled'.
A problem occurred starting process 'command 'command''
Code:
task isGitLFSInstalled(type: Exec) {
commandLine 'command', '-v', 'git-lfs' // Fails here on environments that dont have "command"
ignoreExitValue true
standardOutput = new ByteArrayOutputStream()
ext.output = {
return standardOutput.toString()
}
doLast {
if (execResult.exitValue != 0) {
throw new GradleException("Git LFS is not installed, please build project after installing Git LFS.\n" +
"Refer to the following URL to setup Git LFS: https://git-lfs.github.com/")
}
}
}
A:
The problem you're facing is described here. Surrounding commandLine with try/catch doesn't work for a simple reason: commandLine doesn't execute your command, it just sets the command to be executed by the Exec task when it will be run.
One way would be not to use tasks to execute the command. For example, you could use ProcessBuilder wrapped in try/catch in finalizedBy, which will only be run during the execution phase:
task myTask {
finalizedBy {
try {
def proc = new ProcessBuilder("command", "-v", "git-lfs")
proc.start().waitFor()
// Do something with stdout or whatever.
} catch (Exception e) {
println("Couldn't find git-lfs.")
}
}
}
I don't have much time right now, but I hope that helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
List of UAC prompt triggers?
I just ran an old program I had written years ago, several years before Vista was released. Windows (7) gave me the UAC prompt and asked for permission to run it. I was surprised because it is a relatively simple program which does nothing too fancy and certainly nothing that should require elevated privileges. I then checked the directory and sure enough, Windows is overlaying the shield icon on the program.
I did a quick scan of the code and do not see anything that would obviously trigger a UAC prompt. Moreover, the program shares a framework with several other programs I had written, none of which have the UAC requirement. The program in question, as well as the others which don’t trigger the UAC prompt are all stored in the same directory on a (FAT32) flash-drive.
The only really unique thing about this program that differs from the other, nearly-identical programs is that it uses ShellExecute to allow the user to launch the default web-browser to open selected URLs, but I can’t imagine if/why that would actually require elevated permissions.
Now I am trying to find some sort of information about what kind of heuristics Windows uses to determine whether it should use the UAC prompt or not. I know that old installers usually trigger the prompt, but those are usually called setup.exe or install.exe, while this has a pretty innocuous name (udb.exe). I suspect that it is detecting certain function calls or some such (of course, that would mean that Windows Explorer reads and disassembles the of all executable files which seems doubtful).
I assumed that there would exist some information on this, but the research I did only found a few off-site discussions (no mentions in the “similar question” lists above or to the right), which listed a few causes, none of which seem to apply:
A specific request of the program (which is not possible since it was written before UAC existed),
Lack of manifest (which it does have and would not explain why the other programs don’t trigger it)
An internal list of filenames/paths (not applicable here)
Source (again, that doesn’t explain the other programs being okay)
Access to restricted files/registry keys (not applicable here either)
Resource entries (again, the other programs share common resource data)
Other system-related activities (again, not applicable to the program)
I eventually found a few related questions like one that asked what I am, but that ended up with a completely different outcome which is of no help here, or another one which asked a similar, yet opposite question of equally no help. Unfortunatly, the best question I found was about an installer/updater (which of course, does not apply here), and was also no help because the answers were just the same old information I had found on other sites and listed above.
Does anybody know of a list of UAC triggers or some other way to figure out why Windows would think that some programs would needs elevation? Is there a list of restricted API functions or something?
To be clear, I am trying to find out why Windows is flagging one program for UAC, but not another, similar one.
A:
Original Answer (2014 July 04)
A search for UAC heuristics yields this blog entry: Identification of Administrative Applications. On that page:
The O/S makes a decision that the application looks like an installer or updater and will automatically invoke elevation to run the program with administrative permissions/privileges when a user runs it.This decision is based on a heuristic. Here are some of the heuristic detection points, although this list is not exhaustive:
File name detection – looks for the words “setup”, “update”, “install” in the filename
SxS Manifest word detection – looks for well-known values in the assembly name attribute program’s SxS Manifest
String table detection – looks for well known values in the string table within the resource section of an executable
Thus Xearinox is simply not correct that it is completely based on permissions.
One way you may be able to find out why your program is triggering the UAC prompt is to use Process Monitor and check for permission errors.
Update (2020 July 29)
Searching yields an updated documentation page:
How User Account Control Works
There is an Installer detection technology section at the bottom of that page that contains the following information (similar to the list above):
Before a 32-bit process is created, the following attributes are checked to determine whether it is an installer:
The file name includes keywords such as "install," "setup," or "update."
Versioning Resource fields contain the following keywords: Vendor, Company Name, Product Name, File Description, Original Filename, Internal Name, and Export Name.
Keywords in the side-by-side manifest are embedded in the executable file.
Keywords in specific StringTable entries are linked in the executable file.
Key attributes in the resource script data are linked in the executable file.
There are targeted sequences of bytes within the executable file.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# WF prevent trackbar from getting mouse wheel event
I have a WindowsForms UI in C#. i have a Panel and a PictureBox in it.
I simply get Mouse Wheel event by form and then zoom PictureBox in panel
public MainWindow()
{
InitializeComponent();
this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.zoom_handler);// Capture Mouse wheel event
}
the problem is that when i use a Trackbar, Trackbar gets the mouseWheel event and i can't zoom image anymore. I can't release it by click on PictureBox or Panel. Now what i must do?
A:
Finally i found the answer.
public MainWindow()
{
InitializeComponent();
this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.zoom_handler);// Capture Mouse wheel event
mytrackbar.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.zoom_handler);// Capture Mouse wheel event
mytrackbar.MouseWheel += (sender, e) => ((HandledMouseEventArgs)e).Handled = true;
}
if you like to disable trackbar scroll with mousewheel, last line is enough. but with that line you disable mousewheel event until you focus on other control that has mousewheel event. if you use mousewheel event on some control (or probably form) that can't simply get focus, you must call your function on trackbar mousewheel event.
| {
"pile_set_name": "StackExchange"
} |
Q:
java.io.IOException: Could not delete path 'C:\Users\nirma\Language\app\build\generated\source\r\debug\android\support\coreui'
I am having this issue in the android studio. The app runs fine 1 or 2 times but then it starts giving this error. How can I solve this problem?
Error:Execution failed for task ':app:processDebugResources'.
java.io.IOException: Could not delete path 'C:\Users\nirma\Language\app\build\generated\source\r\debug\android\support\coreui'.
A:
Your install of Android Studio is unable to delete that temporary folder, likely due to a permissions issue. You will need to delete that folder manually via Windows Explorer, using admin privileges if required. Your builds should complete properly again after that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Rails view/controller has_many through
I have this relations:
class Community < ApplicationRecord
has_many :community_people
has_many :people, :through => :community_people
end
class CommunityPerson < ApplicationRecord
belongs_to :community
belongs_to :person
end
class Person < ApplicationRecord
has_many :community_persons
has_many :communities, :through => :community_persons
end
I can CRUD communities, but i've been searching how to in the controller/view add many people to that community, then show them but i can't find and answer.
I'll really appreciate your help!
A:
The simplest way is by using the Rails form options helpers:
<%= form_for(@community) do |f| %>
...
<div class="field">
<%= f.label :person_ids %>
<%= f.collection_select :person_ids, multiple: true %>
</div>
<% end %>
class CommunityControllers
...
def community_attributes
params.permit(:foo, :bar, person_ids: [])
end
end
But I would try to go with a less awkward and more descriptive naming scheme like:
class Community < ApplicationRecord
has_many :citizenships
has_many :citizens, through: :citizenships
end
class Citizenship < ApplicationRecord
belongs_to :community
belongs_to :citizen, class_name: "Person"
end
class Person < ApplicationRecord
has_many :citizenships, foreign_key: 'citizen_id'
has_many :communities, through: :citizenships
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Playing, Opening and Pausing VLC command line executed from Python scripts
I am trying to create an small python app that syncs up 2 computers via tcp socket and when I send a command play or pause. Both scripts will/should execute a command line to pause or play or open vlc wit file. Both computers are MacOSX latest with a VLC installed within the past 3 weeks.
I have been reading the documentation using .../vlc -H for the long help but I still don't seem to --global-key-play-pauses or plays. I got it to open a video but I wasn't able to send any commands while it's running.
I tried some examples I saw online with no avail. I have the 2 scripts ready just not the VLC commands.
c-mbp:~ c$ /Applications/VLC.app/Contents/MacOS/VLC -I --global-key-play-pauses
VLC media player 2.2.2 Weatherwax (revision 2.2.2-3-gf8c9253)
[0000000100604a58] core interface error: no suitable interface module
[000000010050d928] core libvlc error: interface "default" initialization failed
A:
I suspect the best way to do this on MacOS would be to use the VLC remote control interface.
This allows you to control the behavior of a launched VLC instance using commands which you send to the process' stdin.
You could then use the Python subprocess module to launch VLC and then send the appropriate commands to the stdin of this process.
If you were using Linux this could likely be more simply achieved through the VLC DBUS interface however the remote control through stdin should still give you sufficient control for what you are doing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Displaying part of JSON data using javascript
I'm trying to use JSON to print content to the screen. I'm trying to print out as two different sections so the "albumData" displays as columns in the "albumData" div and the audio equipment goes in a div further down the page. I have tried having {audio: [ ...]} in the JSON array but that never seems to work. The issue right now is the JS file is outputting too munch data and is not stopping when the the object is not in the array. Ideally, it would put out a 4x4 layout for the albums, and a 4x3 layout for devices but instead both sections are outputting 4x7 and many of the text is 'undefined'.
Do you guys have any tips on targeting specific JSON data? Thanks for your help
HTML Code:
<h1 class="headText">Wall of Fame</h1>
<hr class="style14"></hr>
</br></br>
<h2>Albums: </h2>
<div id="albumData" class="row"></div>
</br></br>
<h2>Equipment: </h2>
<div id="deviceData" class="row"></div>
<script src="js/wall.js"></script>
JS Code:
$.getJSON("jsonDatabase/wall.json",function(data){
console.dir(data);
var html = "";
$.each(data, function(index, item){
html += '<div class="col-md-3">'+
'<img class="albumImage" src=""' + item.albumImage + '"/>' + "<br>" +
'<div class="albumArtist">' + "<strong>Artist: </strong>" + item.artist + '</div>'+
'<div class="albumTitle">' + "<strong>Album: </strong>" + item.albumTitle + '</div>'+
'<div class="albumYear">' + "<strong>Year: </strong>" + item.year + '</div>'+
'<div class="albumGenre">' + "<strong>Genre: </strong>" + item.genre + '</div>'
html += '</div>'; //col-md-3
})//each album
$("#albumData").append(html);
//end record data
var device = "";
$.each(data, function(ind, item){
device += '<div class="col-md-3">'+
'<img class="deviceImage" src=""' + item.deviceImage + '"/>' + "<br>" +
'<div class="deviceName">' + "<strong>Name: </strong>" + item.device + '</div>'+
'<div class="deviceType">' + "<strong>Device: </strong>" + item.type + '</div>'+
'<div class="deviceCompany">' + "<strong>Company: </strong>" + item.comapny + '</div>'+
'<div class="devicePrice">' + "<strong>Price: </strong>" + item.price + '</div>'
device += '</div>'; //col-md-3
})//each device
$("#deviceData").append(device);
})
// closes getJSON
})
JSON Array:
[{"albumImage":"","artist":"Bruce","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"Tom Waits","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"Alison Krauss","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"Pink Floyd","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"Rage Against the Machine","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"albumImage":"","artist":"","albumTitle":"","year":"","genre":""},
{"deviceImage":"","device":"E12","type":"Portable amp","company":"FiiO","price":"$130"},
{"deviceImage":"","device":"GS1000e","type":"Headphone","company":"Grado","price":"$1300"},
{"deviceImage":"","device":"RS1i","type":"Headphone","company":"Grado","price":"$850"},
{"deviceImage":"","device":"SR60e","type":"Headphone","company":"Grado","price":"$80"},
{"deviceImage":"","device":"HD 650","type":"Headphone","company":"Sennheiser","price":"$500"},
{"deviceImage":"","device":"SRH 860","type":"Headphones","company":"Samson","price":"$60"},
{"deviceImage":"","device":"MA750i","type":"In-ear monitors","company":"RHA","price":"$130"},
{"deviceImage":"","device":"Play: 1","type":"WiFi connected speaker","company":"Sonos","price":"$229"},
{"deviceImage":"","device":"Walsh 3","type":"Speakers (passive)","company":"Ohm","price":"$2,000"},
{"deviceImage":"","device":"Evo 2/8","type":"Speakers (passive)","company":"Wharfedale","price":"$400"},
{"deviceImage":"","device":"Asgard 2","type":"Amplifier","company":"Schiit","price":"$299"},
{"deviceImage":"","device":"Modi","type":"DAC","company":"Schiit","price":"$99"}]
A:
Since it's one array don't parse it 2x, use variables instead.
var deviceHtml = "";
var albumHtml = "";
$.each(data, function(index, item){
if(typeof(item.albumImage) != "undefined" && typeof(item.deviceImage == 'undefined')
{
albumHtml += '<div class="col-md-3">'+
'<img class="albumImage" src=""' + item.albumImage + '"/>' + "<br>" +
'<div class="albumArtist">' + "<strong>Artist: </strong>" + item.artist + '</div>'+
'<div class="albumTitle">' + "<strong>Album: </strong>" + item.albumTitle + '</div>'+
'<div class="albumYear">' + "<strong>Year: </strong>" + item.year + '</div>'+
'<div class="albumGenre">' + "<strong>Genre: </strong>" + item.genre + '</div></div>';
}
else if(typeof(item.deviceImage) != "undefined" && typeof(item.albumImage) == 'undefined')
{
deviceHtml += '<div class="col-md-3">'+
'<img class="deviceImage" src=""' + item.deviceImage + '"/>' + "<br>" +
'<div class="deviceName">' + "<strong>Name: </strong>" + item.device + '</div>'+
'<div class="deviceType">' + "<strong>Device: </strong>" + item.type + '</div>'+
'<div class="deviceCompany">' + "<strong>Company: </strong>" + item.comapny + '</div>'+
'<div class="devicePrice">' + "<strong>Price: </strong>" + item.price + '</div>';
deviceHtml += '</div>'; //col-md-3
}
})//each album
$("#albumData").append(albumHtml);
$("#deviceData").append(device);
You will also want to skip records that have no values for any of them so you will need to add an additional if block in there to test that the string isn't empty, else skip that iteration of the loop.
If, as in your comments you change the format of your object to {albums:[ { } ], devices:[ { }] } you can then just use dot notation to access the key you wish to loop through.
$.each(data.albums,function(index, item){})
and
$.each(data.devices,function(index, item){})
| {
"pile_set_name": "StackExchange"
} |
Q:
RecyclerView Empty
My recycler view is empty, I can tell its there because I can scroll left and right(indicators on the edges of the screen tells me so) but my individual lists item is not showing up.
Here is my code for main activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_split_order);
android.support.v7.app.ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
setTitle("Split Order");
//Code to get Screen Width and Height
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int onequaterscreen = width / 4;
int onefifthheight = height/ 5;
recList = (RecyclerView) findViewById(R.id.rv_bill_list);
recList.setHasFixedSize(true);
createData();
adapter = new BillListAdapter(this,data);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.HORIZONTAL);
recList.setLayoutManager(llm);
recList.setAdapter(adapter);
}
public void createData(){
data = new ArrayList<>();
BillItem dummy = new BillItem();
dummy.setDiscountAmt(0.0);
dummy.setOrderNum(44);
dummy.setSubtotal(0.0);
data.add(dummy);
}
Adapter
private LayoutInflater inflator;
List<BillItem> billItemList = Collections.emptyList();
public BillListAdapter(Context context,List<BillItem> billItemList) {
inflator = LayoutInflater.from(context);
this.billItemList = billItemList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.bill_list_item,parent,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BillItem current = billItemList.get(position);
holder.tv_bill_subtotal.setText(String.valueOf(current.subtotal));
holder.tv_bill_discount_amt.setText(String.valueOf(current.discountAmt));
holder.tv_bill_num.setText(String.valueOf(current.orderNum));
}
@Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_bill_subtotal;
TextView tv_bill_discount_amt;
TextView tv_bill_num;
RelativeLayout rl_bill_discount;
ListView lv_orderItemList;
public MyViewHolder(View itemView) {
super(itemView);
tv_bill_num = (TextView) itemView.findViewById(R.id.tv_bill_num);
tv_bill_subtotal = (TextView) itemView.findViewById(R.id.tv_bill_subtotal);
rl_bill_discount = (RelativeLayout) itemView.findViewById(R.id.rl_bill_discount);
lv_orderItemList = (ListView) itemView.findViewById(R.id.lv_orderitemlist);
tv_bill_discount_amt = (TextView) itemView.findViewById(R.id.tv_bill_discount_amt);
}
}
The layout file is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/rl_bill_sidemenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="@color/colorWhiteBrighter">
<TextView
android:paddingLeft="@dimen/sidemenu_horizontal_margin"
android:paddingRight="@dimen/sidemenu_horizontal_margin"
android:paddingTop="@dimen/sidemenu_vertical_margin"
android:id="@+id/tv_bill_num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ordermenunum"
android:textSize="20sp"
/>
<!--
Order List Header
-->
<RelativeLayout
android:id="@+id/rl_billitemlistheader"
android:orientation="horizontal"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="@dimen/sidemenu_horizontal_margin"
android:paddingRight="@dimen/sidemenu_horizontal_margin"
android:layout_marginTop="@dimen/sidemenu_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_bill_num"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@color/colorWhiteHighlight">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ordermenuqty"
android:textSize="14sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="@string/ordermenuname"
android:textSize="14sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="@string/ordermenuprice"
android:textSize="14sp"/>
</RelativeLayout>
<ListView
android:layout_below="@id/rl_billitemlistheader"
android:id="@+id/lv_orderitemlist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/rl_subtotal">
</ListView>
<!--
Pay Button
-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:padding="@dimen/sidemenu_vertical_margin"
android:background="@drawable/greenbutton_selector"
android:id="@+id/rl_bill_pay"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp"
android:textColor="@color/colorPrimaryDark"
android:text=">>"/>
<TextView
android:id="@+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="28sp"
android:textColor="@color/colorWhiteBrighter"
android:text="@string/zerodollars"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<!--
Subtotal Field
-->
<RelativeLayout
android:id="@+id/rl_subtotal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:paddingLeft="@dimen/sidemenu_horizontal_margin"
android:paddingRight="@dimen/sidemenu_horizontal_margin"
android:background="@drawable/submenu_selector"
android:layout_above="@+id/rl_bill_discount">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Subtotal:"/>
<TextView
android:id="@+id/tv_bill_subtotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="@string/zerodollars"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<View android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@color/colorWhiteDarker"
android:layout_below="@+id/rl_subtotal"
/>
<!--
Discount Field
-->
<RelativeLayout
android:id="@+id/rl_bill_discount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:paddingLeft="@dimen/sidemenu_horizontal_margin"
android:paddingRight="@dimen/sidemenu_horizontal_margin"
android:background="@drawable/submenu_selector"
android:layout_above="@+id/rl_bill_pay">
<TextView
android:id="@+id/tv_discount_lbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="Discount($):"/>
<TextView
android:id="@+id/tv_bill_discount_amt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="@string/zerodollars"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<View android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@color/colorWhiteDarker"
android:layout_below="@+id/rl_subtotal"
/>
</RelativeLayout>
I used the debugger to check the values, nothing is null. Is just not inflating the view I guess cause there no list item.
A:
The getItemCount method is returning 0
@Override
public int getItemCount() {
return yourArraylist.size();
}
Return the Size of the Arraylist which you pass to the adapter class
| {
"pile_set_name": "StackExchange"
} |
Q:
Why FHE takes modulo space $\Bbb Z_p$ as $[−p/2,p/2)$ rather than $[0,p)$?
Why doesn't FHE scheme see a modulus space $\Bbb Z_p$ as $[0,p)$ ?
Instead, it consider $\Bbb Z_p$ as $\left[-\frac{p}{2},\frac{p}{2}\right)$.
What's the concrete reason?
What happens if I use $[0,p)$?
A:
The notation
Many works on FHE use a function of $a$ and $p$ giving how far above or below the nearest multiple of $p$ the quantity $a$ is. Craig Gentry and Shai Halevi note that quantity as $[a]_p$ in Implementing Gentry's Fully-Homomorphic Encryption Scheme (extended abstract in proceedings of Eurocrypt 2011). It replaces $((a+\lfloor p/2\rfloor)\bmod p)-\lfloor p/2\rfloor$. This $[a]_p$ belongs to $[−p/2,p/2)$.
Nathanael Black in Homomorphic Encryption and the Approximate GCD Problem (page vii) go as far as using $a\bmod p$ rather than $[a]_p$:
$a\bmod p\;\;$ Denotes reducing $a$ modulo $p$ into the interval $(-p/2, p/2]$
which is equivalent to
$$(a\bmod p)=r\;\iff\;p\text{ divides }a-r\;\text{ and }\;r\in(-p/2, p/2]$$
(the difference in interval boundaries is immaterial for odd $p$).
Alternatively, that variant $[a]_p$ of $a\bmod p$ could be defined as $a-p\cdot\lceil a/p\rfloor$, where $\lceil x\rfloor$ denotes rational $x$ rounded to the nearest integer (rounding up for Gentry et al.). This is similar to the standard $a\bmod p\;=\;a-p\cdot\lfloor a/p\rfloor$.
For both the standard and alternate definitions of operator $\bmod$, it holds that:
$$\begin{align}
((a+b)\bmod p)&=(((a\bmod p)+b)\bmod p)\\
&=(((a\bmod p)+(b\bmod p))\bmod p)\\
\end{align}$$
$$\begin{align}
((a\cdot b)\bmod p)&=(((a\bmod p)\cdot b)\bmod p)\\
&=(((a\bmod p)\cdot(b\bmod p))\bmod p)\\
\end{align}$$
$$\begin{align}
(a\bmod p)&\equiv a&\pmod p\\
((a+b)\bmod p)&\equiv a+b&\pmod p\\
((a\cdot b)\bmod p)&\equiv a\cdot b&\pmod p\\
\end{align}$$
Note: In the above the notation $r\equiv a\pmod p$ means that $p$ divides $a-r$, and needs no adaptation. It is recognizable from operator $\bmod$ by the use of an opening parenthesis immediately on the left of $\bmod$, and (sometime: or) the use of an $\equiv$ sign somewhere on the left of and paired with $\bmod$.
Why it is useful
With the alternate definition $[a]_p$ of $a\bmod p$ comes an additional useful property, that does not hold for the standard $\bmod$: when $p$ is odd, for all $a$, it holds that $[-a]_p=-[a]_p$. That also holds for large even $p$ and most $a$.
The concept allows an easy extension to signed numbers and subtraction of one of the simplest (partially) homomorphic encryption system: Paillier's encryption. All it takes is defining a modified decryption as $D'(c)=[D(c)]_n$ and restriction of plaintext range; see this.
In some FHE systems, $[a]_p$ matches a signed noise term algebraically added to a signal aligned to multiples of $p$, and $a-[a]_p$ is the pristine signal recovered from the noisy $a$, minimizing the absolute value of noise $[a]_p$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Smoothing a hand-drawn free shape
I am creating an app that allows the user to do some hand-drawing. The problem is I draw lines between the points where the user moved his finger so the resulting shape is somewhat jagged.
My question is how can I smooth the drawing? What is the best algorithm for dealing with this kind of situation?
A:
You could use some kind of curve fitting (maybe Bezier curve) to do it for you.
There is also this very nice example of how it could work. I could not find source code for it but i think that creator of this one has used algorithm from Graphics Gems 1. You could find c code for it here and i have found on SO also this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding bounds to google maps search string causes nil results
I added a search box to my mapping app a little while back which was doing very simple address searching with minimal options.
http://maps.googleapis.com/maps/api/geocode/json?address=sydney+grove&sensor=true
I've just added bounds parameters using the current screen viewport like this
http://maps.googleapis.com/maps/api/geocode/json?address=sydney+grove&bounds=51.198083,-0.830125|51.799930,0.576125&sensor=true
it returns a result when pasted into a browser but always a nil result if entered in code (jsonResponse always equals nil)
-(void) doGeocodingBasedOnStringUsingGoogle:(NSString*) searchString {
GMSCoordinateBounds* bounds=[[self datasource] searchBounds];
//CREATE LOOKUP STRING
NSString *lookUpString = [NSString
stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?
address=%@&bounds=%f,%f|%f,%f&sensor=true",
searchString,
bounds.southWest.latitude,
bounds.southWest.longitude,
bounds.northEast.latitude,
bounds.northEast.longitude];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:@" "
withString:@"+"];
//SEARCH FOR RESULTS
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
if (jsonResponse) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.searchResults = [jsonDict valueForKey:@"results"];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableview reloadData];
});
});
}
This code was fine before I added the bounds condition and is fine if I remove so I'm really out of ideas
A:
I think you need to replace the | with a %7C, for example see here:
How to make an NSURL that contains a | (pipe character)?
As mentioned in the comments on the answer, you could look into using stringByAddingPercentEscapesUsingEncoding for a method to escape the URL for you (so eg you wouldn't need to replace spaces with a +, etc).
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access user data with Google Webmaster Tools API
I'm just starting to use the api libraries from google and I'm having some trouble accessing to user data. For experimentation I used code from a previos question in this field.
My code executes a petition for the google search console api but it returns an empty array. I autorized the service account from the admin console (https://developers.google.com/identity/protocols/OAuth2ServiceAccount) so I don't know why doesn't it return anything.
set_include_path(get_include_path() . PATH_SEPARATOR . '$path/google-api-php-client-master/src');
require_once realpath('$path/google-api-php-client-master/src/Google/autoload.php');
$client_id = "my-client-id";
$service_account_name = "[email protected]";
$key_file_location = "privatekey.p12";
$client = new Google_Client();
$client->setApplicationName("WMtools_application");
$service = new Google_Service_Webmasters($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
try{
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
}catch(Exception $e){
echo "Exception captured", $e->getMessage(), "\n";
}
try{
$results = $service->sites->listSites();
$siteList = $results->siteEntry;
var_dump($siteList);
}catch(Exception $e2){
echo "No results", $e2->getMessage(), "\n";
}
A:
I solved the problem. The case is that i have delegated domain-wide authority to my service account and I didn't include in my petition to the API the user email from whom I want to access the data. To solve It just need to add it to the google_Auth_AssertionCredentials this way:
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/webmasters.readonly'),
$key
);
$cred->sub = $service_account_user_email; //[email protected]
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Basic don't see application.evtx
I have a problem with "Application.evtx" file. Everytime I run my script I get the message box with "File not found" information and I don't know why. I ran Visual Studio as administrator. Help me with this one, please.
Imports System.IO
Module Module1
Sub Main()
Dim pathReadFile As String = "c:\Windows\System32\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "%windir%\Sysnative\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "D:\Dokumenty\MyTest.txt"
Try
If File.Exists(pathReadFile) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
Catch ex As Exception
End Try
End Sub
End Module
A:
Don't use File.Exists(). Ever.
There are many reasons for this, but the one that impacts you right now is that it lies to you and tells you the file does not exist, even if the file actually does exist and the real problem is that you don't have permissions to use it. From the docs:
Return Value
Type: System.Boolean
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false
Remember that normal users have extremely limited file system permissions outside of their own home folders, and even Administrator users need to explicitly run a process as elevated or UAC will just give them normal user permissions.
You have to handle the exception anyway if reading the file fails. Put your development effort into the exception handler.
While I'm here, you may also want to build your path like this:
Dim pathReadFile As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "winevt\Logs\Application.evtx")
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Cloud Message or XMPP
I have a project that requires communication between Android Clients and a Server.
The communication flow is:
Clients send their location to the server periodically (every 10s)
Server is a Desktop application (C# or Java). Usually the server does its own work, but sometimes it needs to send a command to a number of specific clients (real-time is required)
For the direction from clients to the server, there is no problem. But in the reverse direction, from the server to clients, I have some issues. I'm using Google cloud messaging, but I realized there is some delay or loss of commands. I also considered XMPP technique. If I use XMPP, the server and clients will become users of XMPP server (like chat users). It's quite good except the case of losing internet connection.
Anyone, who has experience in XMPP server or/and GCM, kindly give me some recommendations.
A:
XMPP / Jabber is used for real time communication . If you want to develop a chat app like 'whatsapp' then you should go with XMPP.
GCM is a cloud which stores your messages prior sending even if your app is not running cloud saves your messages and send them as soon as your device got connected to internet.
Your requirement is real time chat , so you must go with XMPP.
| {
"pile_set_name": "StackExchange"
} |
Q:
Situation of HTML mails today - bad idea or accepted?
I'm starting up an online business and through php mail() I'll let the customer receive confirmation emails of their order, as well as a payment link. I'd like to be able to put in some eye candy to make it look more professional - an image and perhaps a colored header background - perhaps even display the order as a <table>.
Are HTML mails acceptable? Will they reach all of my customers? What are the best practices to assure arrival of the mails?
A:
The Email Standards Project tracks which HTML is supported by which email clients, so technically speaking that's a start. They also have some good information on HTML email in general. The major takeaway may be: be careful with Gmail.
I can't speak to whether HTML emails will please all of your clients. Personally, I request plain text versions if they're available.
A:
take a look a this post, here you have an explanation of best practices and the way to ensure the mail delivering.
http://thinkvitamin.com/design/ensuring-your-html-emails-look-great-and-get-delivered/
| {
"pile_set_name": "StackExchange"
} |
Q:
Run Jar file on startup?
I have a Java application that lives in the system tray that I compile to a executable jar file. I would like to add the option within my program to add to the system startup items.
As I do not know of any uniform way to do this for all operating systems I assumed I would have to write code to do it for each one I intend to support so I started with Windows.
When I attempted to add it to the registry at [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] using the code available here I discovered that under Windows 7 and 8 unless I have administrator privileges (by running from an elevated command prompt) my edits to the registry do not apply.
Then I spent a day trying to figure out how to get the Jar to relaunch itself with admin privileges before I gave up on that hacky workaround.
Can the task I'm trying to achieve even be accomplished and if so how?
A:
For the most part, you're actually looking to add the feature of auto starting on user login, rather than on system startup. For windows, if you add the registry entry under:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
This location does not suffer from permissions issues when run as an ordinary user, and has been supported for a long time under Windows (I'm thinking Windows 95 time frame here), so should be a safe change across all systems.
For Linux, assuming that the operating system is following the Open Desktop AutoStart specification, then you need to create the appropriate .desktop file in $HOME/.config/autostart/ and it should autostart on login in that case.
For Mac OS X, you need to create a launch agent plist in $HOME/Library/LaunchAgents. The Daemons and services documentation details how to construct this file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't I diagonalize the antiferromagnetic Heisenberg Hamiltonian?
So I am working on an Heisenberg model in a 2x2 grid where qbit 1 interacts with 2, 2 with 3, 3 with 4 and 4 with 1.
I wrote the Heisenberg Hamiltonian in a Matrix (for 16x16 it is still okay imho)
and diagonalized it.
I get as the minimal eigenvalue - 8. But I know that this is not the Groundstate.
Why?/ What did I wrong?
Edit: So I started with the antiferromagnetic Heisenberg Hamiltonian with $J =-1 $: $H = -(-1) \sum_{NN}\sigma_i\cdot\sigma_j$.
I wrote the Pauli-matrices as their matrix-representation and got for eg. the first NN-interaction: $\sigma_x\otimes \sigma_x \otimes \mathbb{1}\otimes \mathbb{1} + \sigma_y\otimes \sigma_y \otimes \mathbb{1}\otimes \mathbb{1} + \sigma_z\otimes \sigma_z \otimes \mathbb{1}\otimes \mathbb{1}$ (but as a 16x16 matrix now. I wont write it here it is just too big).
Then I diagonalized the matrix or calculated its eigenvalues, latter I dit with numpy .
For the ferromagnetic case($J=1$) I get the correct groundstate but for the antiferromagnetic case($J=-1$) I get as the minimal eigenvalue -8.
A:
There is no mistake. The ground state energy is -8.
S={[0 1;1 0],[0 i;-i 0],[1 0;0 -1]};
kk=@(a,b,c,d)(kron(kron(a,b),kron(c,d)));
H=0;
for p=1:3
s=S{p};e=eye(2);
H=H+kk(s,s,e,e)+kk(e,s,s,e)+kk(e,e,s,s)+kk(s,e,e,s);
end;
eig(H)
returns (in matlab!)
-8.0000
-4.0000
-4.0000
-4.0000
-0.0000
-0.0000
0
0
0.0000
0.0000
0.0000
4.0000
4.0000
4.0000
4.0000
4.0000
I'd say this can be derived by hand, since the ground state is a spin singlet, and the singlet space is spanned by two basis states (singlets in two different pairings), and the Hamiltonian acts by swapping them - so there should be an easy way to see this result. I might add a discussion later.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как создать новый столбец в DF по категории?
Есть исходный DF:
dD
0,05
0,15
0,25
0,95
И второй DF с категориями значений:
Ot Do SP
0 0,1 0,6
0,1 0,2 0,6
0,2 0,3 0,8
0,3 0,4 1,25
0,4 0,5 1,6
0,5 0,6 2,5
0,6 0,7 4,5
0,7 0,8 5,5
0,8 0,9 6,5
0,9 1 8
Правая граница нестрогая!
Нужно в соответствии со значением в первом DF поставить значение SP.
То есть, на выходе нужно получить нечто такое:
dD SP
0,05 0,6
0,15 0,6
0,25 0,8
0,95 8
A:
Сначала избавимся от дупликатов в первом DF (данный шаг можно пропустить если все значения в столбце d2['SP'] уникальные):
In [161]: t = d2.groupby('SP')[['Ot','Do']].agg({'Ot':'min', 'Do':'max'}).reset_index()
In [162]: t
Out[162]:
SP Ot Do
0 0.60 0.0 0.2
1 0.80 0.2 0.3
2 1.25 0.3 0.4
3 1.60 0.4 0.5
4 2.50 0.5 0.6
5 4.50 0.6 0.7
6 5.50 0.7 0.8
7 6.50 0.8 0.9
8 8.00 0.9 1.0
теперь подготовим границы интервалов:
In [163]: bins = t[['Ot','Do']].stack().drop_duplicates()
In [164]: bins
Out[164]:
0 Ot 0.0
Do 0.2
1 Do 0.3
2 Do 0.4
3 Do 0.5
4 Do 0.6
5 Do 0.7
6 Do 0.8
7 Do 0.9
8 Do 1.0
dtype: float64
и соответствующие категории:
In [165]: labels = t['SP']
In [166]: labels
Out[166]:
0 0.60
1 0.80
2 1.25
3 1.60
4 2.50
5 4.50
6 5.50
7 6.50
8 8.00
Name: SP, dtype: float64
наконец воспользуемся функцией pd.cut() для категоризации значений:
In [180]: d1['SP'] = pd.cut(d1['dD'], bins=bins, labels=labels, right=False)
In [181]: d1
Out[181]:
dD SP
0 0.05 0.6
1 0.15 0.6
2 0.25 0.8
3 0.95 8.0
4 0.00 0.6
PS: для отладки бывает полезным не указывать категории (labels), чтобы увидеть получившиеся интервалы:
In [182]: pd.cut(d1['dD'], bins=bins, right=False)
Out[182]:
0 [0.0, 0.2)
1 [0.0, 0.2)
2 [0.2, 0.3)
3 [0.9, 1.0)
4 [0.0, 0.2)
Name: dD, dtype: category
Categories (9, interval[float64]): [[0.0, 0.2) < [0.2, 0.3) < [0.3, 0.4) < [0.4, 0.5) ... [0.6, 0.7) < [0.7, 0.8) < [0.8, 0.9) < [0.9, 1.0)]
| {
"pile_set_name": "StackExchange"
} |
Q:
Arc Menu GNOME extension won't install in Ubuntu 17.10
I'm trying to install a GNOME shell extension called Arc Menu on my Ubuntu 17.10 machine. I do that through https://extensions.gnome.org/extension/1228/arc-menu/.
When trying to install I get the ERROR red button.
How can I check what the error is and fix this?
A:
Arc Menu depends on gir1.2-gmenu-3.0 package. Install it first by running the following command in Terminal
sudo apt install gir1.2-gmenu-3.0
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass an argument between sessions in Spring Security
I'm working on application that allows user to perform some actions as guest. Results are stored in the session. I would like to inject data from guest session to authenticated user session. E.g.:
Guest user adds something to cart, etc
User decides to authenticate
After authentication cart is restored from the previous session (i.e. passed between them)
Is there a place where I can get both old and new user session to copy attributes from one to another?
A:
This can be achieved by using:
<security:session-management session-fixation-protection="none"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I know if the prepared statements are cached?
I am using Hikari with SQL Server 2016 and sqljdbc4-2.0.jar in the tomcat lib folder.
My configuration for db resource is as follows:
<Resource name="jdbc/SQLServerDS" auth="Container" type="javax.sql.DataSource"
username="uname"
password="pwd"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://server:port;DatabaseName=dbName"
maxActive="20"
maxIdle="10"
validationQuery="select 1" />
My Datasource configuration is as follows:
@Bean(name = "dataSource")
public DataSource getDataSource() throws NamingException {
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(20);
config.setDataSourceJNDI("java:comp/env/jdbc/SQLServerDS");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("useServerPrepStmts", "true");
config.addDataSourceProperty("cacheResultSetMetadata", "true");
config.addDataSourceProperty("useLocalSessionState", "true");
config.addDataSourceProperty("cacheServerConfiguration", "true");
config.addDataSourceProperty("elideSetAutoCommits", "true");
config.addDataSourceProperty("maintainTimeStats", "false");
return new TransactionAwareDataSourceProxy(
new LazyConnectionDataSourceProxy(new HikariDataSource(config)));
}
How do I know if the preparedstatement caching is working for different connections?
I am using spring container managed transactions with hibernate v4.3.10.Final.
Also, for the caching to work, do I need to have second-level cache enabled?
A:
HikariCP actually doesn't support PreparedStatement caching
others offer PreparedStatement caching. HikariCP does not. Why?
It's considered wrong implementation
Using a statement cache at the pooling layer is an anti-pattern, and will negatively impact your application performance compared to driver-provided caches.
Explanation:
At the connection pool layer PreparedStatements can only be cached per connection. If your application has 250 commonly executed queries and a pool of 20 connections you are asking your database to hold on to 5000 query execution plans -- and similarly the pool must cache this many PreparedStatements and their related graph of objects.
Most major database JDBC drivers already have a Statement cache that can be configured, including PostgreSQL, Oracle, Derby, MySQL, DB2, and many others. JDBC drivers are in a unique position to exploit database specific features, and nearly all of the caching implementations are capable of sharing execution plans across connections. This means that instead of 5000 statements in memory and associated execution plans, your 250 commonly executed queries result in exactly 250 execution plans in the database. Clever implementations do not even retain PreparedStatement objects in memory at the driver-level but instead merely attach new instances to existing plan IDs.
If you accept it, you shouldn't try\expect to cache PreparedStatement
If you reject it, you can use C3P0 as connection pool
About Second level cache in hibernate, it's mostly not defined in connection pool, but use relevant connection provider:
HikariCP now has a ConnectionProvider for Hibernate 4.x called HikariConnectionProvider
In order to use the HikariConnectionProvider in Hibernate 4.x add the following property to your hibernate.properties configuration file:
hibernate.connection.provider_class=com.zaxxer.hikari.hibernate.HikariConnectionProvider
As of Hibernate 4.3.6 there is an official ConnectionProvider class from Hibernate, which should be used instead of the HikariCP implementation. The class is called org.hibernate.hikaricp.internal.HikariCPConnectionProvider
| {
"pile_set_name": "StackExchange"
} |
Q:
Mule ESB JDK 1.8 memory tweaks
We are planning on using JDK 1.8 for Mule 3.7 CE.
In the past we edited wrapper.conf to tweak the memory JDK 1.6/1.7 uses. We did this by editing:
wrapper.java.initmemory=256m
wrapper.java.maxmemory=512
wrapper.java.additional.7=-XX:PermSize=256m
wrapper.java.additional.8=-XX:MaxPermSize=512m
Looking into the processes that are running in linux we see that Mule still uses xmx settings. If not mistaken, this no longer works in java 1.8 because it has been removed. Instead JDK 1.8 uses metaspace.
Now my question is, how/where to we make memory tweaks for Mule 3.7 using JDK 1.8? Or does Mule 3.7 CE not support this yet?
Do we simply add to wrapper.conf the following settings?:
wrapper.java.additional.16=-XX:MetaspaceSize=100M
wrapper.java.additional.17=-XX:MaxMetaspaceSize=2024m
And remove:
wrapper.java.initmemory=1024
wrapper.java.maxmemory=1024
Or we do still use the following settings?
wrapper.java.initmemory
wrapper.java.maxmemory?
Thanks!
A:
You can keep using the initmemory and maxmemory.
Changing to Java 1.8 doesn't impact this.
We use Java 1.8 with Mule 3.7 in Linux and we are able to successfully control the heap allocation with the current setting of initmemory and maxmemory.
You might want to use Metaspace configuration only to replace PermGen settings.
wrapper.java.additional.16=-XX:MetaspaceSize=100M
wrapper.java.additional.17=-XX:MaxMetaspaceSize=2024m
Go through the following link for more understanding.
http://www.infoq.com/articles/Java-PERMGEN-Removed
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Youtube .NET Data API: Retrieve only videoID?
I am using youtube's .NET API to retrieve video feeds, here is the code:
String[] ids;
YouTubeRequestSettings settings = new YouTubeRequestSettings("My App Name", "My App Key");
YouTubeRequest request = new YouTubeRequest(settings);
Uri uri =
new Uri("http://gdata.youtube.com/feeds/api/users/nptelhrd/uploads?max-results=50");//Change "GoogleDevelopers" to "default"
Google.GData.Client.Feed<Video> videoFeed = request.Get<Video>(uri);
ids = new String[videoFeed.TotalResults];
int count = 0;
for (int i = 0; i < 50; i++)
ids[i] = videoFeed.Entries.ElementAt(i).VideoId;
for (int i = 50; i < ids.Length-50; i+=50)
{
Uri uri2 =
new Uri("http://gdata.youtube.com/feeds/api/users/nptelhrd/uploads?max-results=50&start-index=" + i.ToString());//Change "GoogleDevelopers" to "default"
Google.GData.Client.Feed<Video> videoFeed2 = request.Get<Video>(uri);
for (int j = 0; j < 50; j++)
{
ids[i+j] = videoFeed2.Entries.ElementAt(j).VideoId;
count++;
}
}
The above code returns every information(Title, Description, ViewCount, Rating....etc.) for each video uploaded by the user "nptelhrd". There are 6950 videos uploaded by this particular user.
THE ABOVE CODE TAKES 15 MINUTES TO EXECUTE on a 512Kbps connection, because it retrieves all information of each and every video, its painfully slow, wastes a lot of server resources. Can't the above code be modified so that it only retrieve videoId's? How can I only retrieve videoId's of all videos?
A:
With the present limitations of .NET YOUTUBE API, its not possible to retrieve only VIDEOID.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearsch Java API has_child
I'm looking for how to build a query to fetch/search by children of parent document and I see that in QueryBuilders class up to ver. 1.7 there was hasChildQuery method (documentation link)
// Has Child
QueryBuilder qb = hasChildQuery("blog_tag", termQuery("tag","something"));
but since 1.7 there is nothing like this
How to query for children then in Elasticsearch Java client? Why it was removed?
I'm using Elasticsearch in version 5.5.0
A:
I've found that there is JoinQueryBuilders class that contains methods
public static HasChildQueryBuilder hasChildQuery(String type, QueryBuilder query, ScoreMode scoreMode)
public static HasParentQueryBuilder hasParentQuery(String type, QueryBuilder query, boolean score)
that allow you to query for a child/parent
| {
"pile_set_name": "StackExchange"
} |
Q:
How to parallelize function that takes multiple constants?
I am trying to parallelize a function that takes multiple constant arguments. So far I have been able to run it, but it is not parallelizing the process. How should I approach it?
I tried to do the following:
import numpy as np
import multiprocessing
def optm(hstep,astep,time_ERA):
#this is a secondary function where I get arrays from a dataset
data = checkdate(time_ERA,2,4)
zlevels=data[0]
pottemp=data[1]
for z1 in np.linspace(0,zlevels[-1],hstep):
for z2 in np.linspace(0,zlevels[-1],hstep):
for a1 in np.linspace(0,0.01,astep): # max angle
for a2 in np.linspace(0,0.01,astep):
for a3 in np.linspace(0,0.01,astep):
result_array=another_function(zlevels,pottemp,z1,z2,a1,a2,a3) # this function is the one that does all the math in the code. Therefore, it take a lot of time to compute it.
return result_array
Then I parallelized the function this way:
input_list = [(hstep,astep,time_ERA)] #creat a tuple for the necessary startmap
pool = multiprocessing.Pool()
result = pool.starmap(optm, input_list)
pool.close()
When I run it, it takes longer than without the parallelization. It is my first time trying to parallelize a code so I am still not sure if I should use map or starmap and how to parallelize it.
A:
Using the minimal example from my comment adapted to your problem:
import multiprocessing
import time
import numpy as np
def optm(hstep,astep,time_ERA):
values = []
#this is a secondary function where I get arrays from a dataset
data = checkdate(time_ERA,2,4)
zlevels=data[0]
pottemp=data[1]
for z1 in np.linspace(0,zlevels[-1],hstep):
for z2 in np.linspace(0,zlevels[-1],hstep):
for a1 in np.linspace(0,0.01,astep): # max angle
for a2 in np.linspace(0,0.01,astep):
for a3 in np.linspace(0,0.01,astep):
values.append([zlevels,pottemp,z1,z2,a1,a2,a3])
return values
def mp_worker((zlevels,pottempt,z1,z2,a1,a2,a3)):
temp = another_function(zlevels,pottemp,z1,z2,a1,a2,a3)
# do something with the result
def mp_handler(data):
p = multiprocessing.Pool(2) # Change 2 to your cpu count
p.map(mp_worker, data)
if __name__ == '__main__':
data = optm(hstep,astep,time_ERA)
mp_handler(data)
Instead of mapping, you could do pool.apply_async() with each set of parameters, or use a multiprocessing queue to feed jobs to subprocesses. I assume, that the output needs to be stored in one single array, so Queues will make that a lot easier. You could feed jobs to a queue and push the results to another queue and when all processes are done collect the results from the result queue in the main thread and store them to an array.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I set up MongoDB so that it is exposed to my local windows network?
I just need to expose one windows computer's MongoDB database to all the others on the same Windows network.
I searched stack overflow but nobody seems to be specifically addressing this issue. What I've done so far is gone to the mongoDB Windows computer and exposed port 27017. I also went to the config file of mongoDB and set it to [ 0.0.0.0, ::]. Then I went to computer number two and was unable to get the database from computer number one.
I want to do this because I have code that I wrote which pulls data from the database but I can't until I figure out how to do this.
A:
In your mongod.cfg file, replace "bindIp: 127.0.0.1" with "bindIpAll: true
# network interfaces
net:
port: 27017
bindIpAll: true
Ensure your firewall allows traffic on port 27017, and then restart your MongoDB server in Windows Service Manager.
You can test remote connectity just by typing:
mongo <hostname>
on a remote machine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Defining a global namespace with RequireJS
I am new to RequireJS. Until now, when I am developing apps, I find it very useful to create a global namespace in order to be able to test and debug my app from the chrome web inspector or the like.
For example (using knockout.js), I could define my view model somewhere in the global namspace and then just inspect it with:
ko.toJSON(viewModel);
Or Using backbone.js:
var App = {};
App.Model = Backbone.Model.extend({...});
//(Lets say I want to start my app with jQuery ready function)
$(function(){
App.model = new App.Model();
});
And then from the console to test that my model is working properly:
App.model.fetch();
Is there a way to accomplish this while using RequireJS?
A:
The way I do it is that for the modules for which it makes sense I purposely leak some values into the global space only if the code detects that it is running in a test environment.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to develop for multiple websites in parallel?
If it makes any difference, I am using Xampp on windows for my web server & PHP (all web pages are PHP based, some include JS, all include CSS file).
The point is that I have a local directory which represents http://localhost and if I want to develop multiple websites I have to copy them all under that directory.
And since most of them have CSS, images and many have JS, I end up with the images/JS/CSS for all websites mixed in to http://localhost/images, http://localhost/css, etc.
And when I come to upload them it's a nightmare. I am worried that I might forget to upload some vital files, or to upload files that do not belong to the site.
What's the solution?
In my case, all files are PHP, so should I tweak $_SERVER['DOCUMENT_ROOT'] but I wonder what the general approach by professional web designers is.
A:
If you want to set up VirtualHosts, so you can visit http://foo.local or http://bar.local (example names of websites/projects you're working on) on your local machine, find your Apache configuration file (named httpd.conf in Apache1.X or apache2.conf in Apache2.X). This file tells you where your virtual hosts live (usually with an Include directive on the bottom of the file).
Let's assume the project you're working on is foo.com. You'll need to add this to either the bottom of your httpd.conf/apache2.conf files or as a new file in your virtual hosts directory (just name it something appropriate like foo.com.conf or foo.local.conf or something).
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName foo.local
DocumentRoot /where/your/website/files/are
ErrorLog /where/your/logs/go/foo.local-error_log
<Directory /where/your/website/files/are>
Options FollowSymLinks
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
(where "/where/your/website/files/are" is the directory where your current project is, where "/where/your/logs/go/foo.local-error_log" is any directory/file that you'd like to store your logs in, where the location in your <Directory> directive is the same as the location of your DocumentRoot)
Then you need to restart Apache. If it complains, look at the error and try to fix it based on what it says.
Then you need to add a fake host to your hosts file so that when you visit http://foo.local in your browser it points to your local computer. The hosts file is /etc/hosts in Linux/BSD/OS X/Solaris or C:\WINDOWS\system32\drivers\etc\hosts in Windows. You'll need to edit this file as root / with sudo or pfexec (in BSD/Linux/Solaris/OS X) or as an Administrator in Windows.
Add the following line:
127.0.0.1 foo.local
To the bottom of this file (or anywhere that makes sense, as long as it's on it's own line).
Here's some more info to get you going:
http://httpd.apache.org/docs/2.0/mod/core.html#virtualhost
| {
"pile_set_name": "StackExchange"
} |
Q:
Position of hyperlinked text after scaling in a tikzpicture
I am using the scale option of a node inside of a tikzpicture in which a text with \href{}{} is hyperlinked. The hyperlinks are shown for the unscaled version of the text. This means they are at the wrong positions. How can I circumvent this problem (or what did I do wrong)? Thanks!
\documentclass{standalone}
\usepackage{tikz}
\usepackage{hyperref}
\begin{document}
\begin{tikzpicture}
\node[scale=.2,text width=1cm] {\href{https://www.google.de}{test test test est set}};
\end{tikzpicture}
\end{document}
A:
One way to go is to use \scalebox, which is part of graphicx that gets autoloaded by tikz.
\documentclass[tikz]{standalone}
\usepackage{hyperref}
\begin{document}
\begin{tikzpicture}
\node {\scalebox{0.2}{\begin{minipage}{1cm}\href{https://www.google.de}{test test test
est set}\end{minipage}}};
\end{tikzpicture}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run alias in background?
Is it possible to run this u2be2mp3(){ youtube2mp3 "$@" > /dev/null;} in background?
It's part of the .bashrc, and if I use it this way:
"u2be2mp3(){ youtube2mp3 "$@" > /dev/null &;}"
I'll get a syntax error.
A:
It should work if you use the & instead of the ;, not both at the same time:
u2be2mp3() { youtube2mp3 "$@" > /dev/null & }
Also, to be exact, that's a shell function, not an alias, and the above line runs the youtube2mp3 command in the background, not the function. You could also keep your original shell function and run the shell function in the background:
u2be2mp3() { youtube2mp3 "$@" > /dev/null; }
And to start it in the background:
u2be2mp3 &
| {
"pile_set_name": "StackExchange"
} |
Q:
Redirect from apache rewrite
I want to redirect
/na to /na.php
Now, I'm using wordpress and I don't want to create page from wordpress. So, I add
RewriteRule ^na$ /na.php
but it's not working. How should I write it ?
I updated like following but still no luck
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^na$ /na.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
A:
RewriteRule ^na$ /na.php [L]
The first argument for the RewriteRule omits the leading slash, and if you don’t check for the exact string you’ll run into an infinite loop. The [L] prevents further processing of the request.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional delete and insert in postgres
I have two tables Table_A and Table_B. How can I write a conditional SQL that does the following logic
If table A records match table B records on id
then
delete records from table A and Insert records into Table B
How can I do this with SQL most likely using with
delete from Table_A where Exists (select a.id from TABLE_A
join TABLE_B as b on a.id = b.id)
The Insert is:Insert into Table_A (id) select id from TABLE_B
A:
Use a CTE to catch the ids of the deleted records, and re-join these with the b records:
WITH del AS (
DELETE FROM a
WHERE EXISTS ( SELECT *
FROM b
WHERE b.id = a.id
)
returning *
)
INSERT INTO a (id, x, y, z)
SELECT id, x, y, z
FROM b
WHERE EXISTS (
SELECT *
FROM del
WHERE del.id = b.id
);
BTW: you should have very good reasons (such as wanting to activate the triggers) to prefer delete+insert to a update.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to access smarty's foreach iteration from php function? (Smarty 2.6)
Question
Say I have
{php}
function hello(){
{/php}
<div class="hello">{$smarty.foreach.panellist.iteration}</div>
{php}
}
{/php}
Then down below I call:
{foreach from=$channelObj->get_panellist_primary('','','pan_ptyid,pan_label1,pan_label2') item=panelObj name=panellist}
{php}hello(){/php}
{/foreach}
I'm getting this error:
PHP Fatal error: Using $this when not in object context in /var/www.app1/theURL/otherthings/channel.tpl.php on line 197
Why doesn't this work? How can I access the iteration of this foreach from inside the function, preferably without passing a parameter?
More Details
Since I know you'll tell me {php} is deprecated...the reason I am using it is because I'm being asked to make a really complicated template, so I need complicated functions to build it without it becoming a mess, and I've never used smarty before. I'm on a deadline and I'm already late, so I can't learn the correct methodology of smarty. The only way I would know how to manage this code is with regular PHP, but my boss is insisting I make the whole thing with smarty...no PHP or Javascript allowed.
Thanks!
A:
scope=global
is required for access variable from foreach!
{assign var=SenderID value=$Nachricht.sender_id scope=global}
{php} echo $smarty->getTemplateVars('SenderID'); {/php}
or
{assign var="edit_ticket_id"
value=$ticket.ticketRaw['edit_old_ticket_id'] scope=global}
{php}
global $smarty;
var_dump($smarty->get_template_vars('edit_ticket_id'));
{/php}
| {
"pile_set_name": "StackExchange"
} |
Q:
DAX: Is the value in one column the same this month as it was last?
I need to create a calculated column. I have a list of items with serial #s, and those items are assigned to someone each month. I need to know (0/1) whether the owner of that item this month is the same as the owner of that item last month. (So I can create a measure to average how many are changing owners month-to-month.)
Basically, I'm trying to achieve the last column:
Month ItemID Owner Same Owner as Prev Mth
2015/01/31 A1 Al
2015/01/31 A2 Bob
2015/01/31 A3 Carl
2015/02/28 A1 Al 1
2015/02/28 A2 Carl 0
2015/02/28 A3 Carl 1
2015/03/31 A1 Bob 0
2015/03/31 A2 Bob 0
2015/03/31 A3 Bob 0
2015/04/30 A1 Bob 1
2015/04/30 A2 Bob 1
2015/04/30 A3 Al 0
I tried a CALCULATE(Max([Owner]), FILTER(tbl, DATEADD([Month],-1,MONTH)=EARLIER([Month]), FILTER(tbl, [ItemID] = EARLIER([ItemID]))
But Max doesn't work on text fields. So I am kind of stumped. I know this shouldn't be that hard...
A:
Date logic is almost always an issue of modeling rather than clever functions.
You will need a date table with a monotonically incremented integer id for months. I typically refer to this as MonthSequential or MonthIndex depending on the intended audience for the model. This field simply increments by 1 for each month in the date table without wrapping at year boundaries. Thus if the first month in your model is January, 2014, that month will have MonthSequential=1. February, 2014 has MonthSequential=2, and so on to December, 2014 with MonthSequential=12. January, 2015 has MonthSequential=13.
This allows very simple arithmetic to identify any month or range of months an arbitrary amount of time from the current month. Once you have this field in your date dimension (and your Items[Month] field related to your DimDate[Date] field), life gets pretty easy:
SameOwnerPreviousMonth=
IF(
CALCULATE(
VALUES(Items[Owner])
,FILTER(
ALLEXCEPT(Items, Items[ItemID])
,RELATED(DimDate[MonthSequential]) =
EARLIER(RELATED(DimDate[MonthSequential])) - 1
)
) = Items[Owner]
,1
,0
)
There's some funkiness here with row context, which I will explain.
Any calculated column is defined by some formula. That formula is evaluated in the row context of the table. What happens is a row-by-row iteration through the table. The formula you provide is evaluated once per row and that creates the value for that calculated column.
This being said, the storage engine and formula engine behind DAX have no concept of a row ordering. This means that any formula we define for a calculated column must provide its own ordering or reference to another row if we need to do that.
So, what do we do to find the owner in the previous month? Well, we need to look through the entire Items table and find the row which has the same [ItemId] and falls in the month immediately prior to the month on the current row. Our [MonthSequential] makes finding a date in the previous month trivial, and DAX offers many context-manipulating functions to preserve or eliminate context.
Note: I will refer to function arguments positionally, with the first argument to a function indicated by (1).
Let's step through the solution. We'll ignore the IF() because that is trivial. The meat of the formula lies in the CALCULATE() which identifies the [Owner] in the previous month:
CALCULATE(
VALUES(Items[Owner])
,FILTER(
ALLEXCEPT(Items, Items[ItemID])
,RELATED(DimDate[MonthSequential]) =
EARLIER(RELATED(DimDate[MonthSequential])) - 1
)
)
CALCULATE() evaluates arguments (2)-(n) first, to create a new filter context. That filter context is then used to evaluate the expression in (1).
FILTER() iterates row-by-row through the table provided in (1) and evaluates the boolean expression in (2) for each row in (1). It returns a table made up of the subset of rows of (1) for which (2) evaluates to true. Since we are already iterating through the entire Items table in evaluating our calculated column, we end up with two sets of row context. The outer row context is the iteration through the whole table. The inner row context is the iteration through (1) of our filter. The outer row context affects the inner, and we must modify/remove select portions of the outer context as needed.
The table we iterate over is ALLEXCEPT(Items, Items[ItemId]). ALLEXCEPT() strips out all context, except for the fields named. On any given row in our outer context, we preserve the value of Items[ItemId] and strip all other context ([Month] and [Owner], along with any other fields you've not named in your sample data). This gives us a table for our FILTER() made up of every row in Items which shares the [ItemId] of the current row in the outer filter context. This subset table becomes the generator of our inner row context.
Now we're iterating over FILTER()'s (1), explained above. RELATED() allows us to call out to get a value from another table related to the current one. We grab the [MonthSequential] value that is tied to the current row in our inner row context. We want to find the month that is immediately prior to the current month in the outer row context. To refer to a value in the outer row context, we need to escape the inner.
EARLIER() allows us to escape the current (inner) row context and refer to the last valid (outer) row context. This can happen through arbitrary levels of nesting of contexts. Luckily, we only have two. EARLIER(RELATED(DimDate[MonthSequential])) finds the [MonthSequential] value of the current row in the outer context. We simply subtract 1 from that to get the prior month (and since we're using [MonthSequential], we have no need to implement any logic to handle wrapping around year barriers).
Thus the context in which we evaluate VALUES(Items[Owner]) is that subset of our Items table where [ItemId] is equal to the current row in our outer row context, and the value of [MonthSequential] is one less than the current row in the outer row context. VALUES() returns the list of values which make up the column reference inside. In this case, since every [ItemId] is associated with only a single [Owner] in any given month, that list is only a single value which can be implicitly cast to a scalar value and represented in our calculated column.
Our IF() simply tests this [Owner] value against that of the current row in the outer row context and returns a 1 or 0 as appropriate.
This will break if you have a single [ItemId] which has multiple distinct [Owner]s in a given month.
Model diagram:
| {
"pile_set_name": "StackExchange"
} |
Q:
Как узнать длину строки у двумерного динамического массива
Выделаю память для строк столбцов массива так:
int n=11;
int **mas = new int *[n];
Потом каждому столбцу выделаю разное количество строк:
for (k = n - 1; k >= 0; k--)
{
gcd=1 + rand() % 8 ;
mas[k] = new __int64[gcd];
}
Как узнать длину каждой строки отдельно подскажите, пожалуйста.
A:
Ни в С++ после выделения памяти с помощью
T* = new T[42];
ни в C после
T* = (T*) malloc(sizeof(T) * 42);
невозможно узнать размер выделенной памяти. По крайней мере, невозможно переносимым способом. То, что Вам нужно, примерно следующая структура (Внимание: это плохой код)
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Foo
{
Foo(int n)
: nrow(n), row_length(new int[n]), data(new int*[n])
{
srand(time(0));
for (int i=0; i<nrow; ++i)
{
row_length[i] = rand() % 8 + 1;
data[i] = new int[row_length[i]];
for (int j = 0; j < row_length[i]; ++j)
data[i][j] = rand() % 10;
}
}
int nrow;
int* row_length;
int** data;
int* operator[] (int i) { return data[i]; }
};
int main()
{
Foo foo(3);
for (int i = 0; i < foo.nrow; ++i)
{
for (int j = 0; j < foo.row_length[i]; ++j)
cout << foo[i][j] << " ";
cout << endl;
}
return 0;
}
Правильно в такой ситуации использовать std::vector<std::vector<T>>
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting 'Namebox' is not defined react/jsx-no-undef error when trying to render a react Component
I'm learning react and I'm stuck on this issue. All I want to do is to render a component which resides in the current Class. When I run this code I'm getting an error .
This is the Code.
class NamesBox extends React.Component{
constructor(){
super();
}
Namebox(props){
return(
<div>
<div>{props.name}</div>
</div>
);
}
sayHello() {
let names = ["joseph",'john','megha','nadhiya'];
return names.map(name => {
return (
<Namebox name={name} key={name}/>
);
})
}
render (){
return (this.sayHello());
}
};
export default NamesBox;
Failed to compile ./src/NamesBox.js Line 21:5: 'Namebox' is not
defined react/jsx-no-undef
Search for the keywords to learn more about each error.
A:
namebox is a function not a component. You are trying to invoke it inside the sayHello function as a component. Try this.namebox(name) instead. You are not suppose to create a component within a component so namebox is just a function and it should start with a lower case letter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused with ufw
I want ufw to block everything on my external interface (enp6s0) but allow everything on my internal ones (br0, tap0).
I had huge issues with this (ufw was blocking stuff on br0 even though I set up a rule to allow in on enevrything), so I set ufw to by default allow everything and then started adding exceptions for the interface I want blocked, like so:
ufw deny in on enp6s0 to any port 67 proto udp
I have a few of these for every port I don't want accessed from outside. But this solution makes me uneasy: basically I'm leaving everything open, just not listening on it. Sooner or later I'm going to forget to protect something.
So I went the other way around and wanted to create a set of rules which would allow certain ports but deny everything else, like so:
ufw insert 1 allow in on enp6s0 from any port ssh proto tcp
ufw insert 2 allow in on enp6s0 from any port http proto tcp
ufw insert 3 deny in on enp6s0 from any port 30:65535 proto tcp
The last command was intentionally leaving port 22 open so I could test effectiveness of the rules without risking losing my ssh connection to the server.
However, adding the deny rule immediately blocked the entire server. Everything, not just 30:65535. nmap thought it was down. Just by some huge luck, my existing ssh session remained active so I could delete the rule.
Now, I know I'm not some ufw guru or something, but this really came as (another) shock to me: it seems I have no idea about how it works.
Can anyone enlighten me on the deny rule? How I need to set it up?
Final edit:
It turned out that uninstalling & reinstalling ufw fixed the issues. It seems I messed up some setting at some point which caused all the unexplained behaviour.
Edit: my network config
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
# Our additions start here:
# tap interface (VMs will use this one)
auto tap0
iface tap0 inet manual
pre-up ip tuntap add tap0 mode tap user root
up ip link set dev tap0 up
post-down ip link del dev tap0
# bridge
auto br0
iface br0 inet static
bridge_ports tap0
address 192.168.100.1
netmask 255.255.255.0
broadcast 192.168.100.255
iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N ufw-after-forward
-N ufw-after-input
-N ufw-after-logging-forward
-N ufw-after-logging-input
-N ufw-after-logging-output
-N ufw-after-output
-N ufw-before-forward
-N ufw-before-input
-N ufw-before-logging-forward
-N ufw-before-logging-input
-N ufw-before-logging-output
-N ufw-before-output
-N ufw-logging-allow
-N ufw-logging-deny
-N ufw-not-local
-N ufw-reject-forward
-N ufw-reject-input
-N ufw-reject-output
-N ufw-skip-to-policy-forward
-N ufw-skip-to-policy-input
-N ufw-skip-to-policy-output
-N ufw-track-forward
-N ufw-track-input
-N ufw-track-output
-N ufw-user-forward
-N ufw-user-input
-N ufw-user-limit
-N ufw-user-limit-accept
-N ufw-user-logging-forward
-N ufw-user-logging-input
-N ufw-user-logging-output
-N ufw-user-output
-A INPUT -j ufw-before-logging-input
-A INPUT -j ufw-before-input
-A INPUT -j ufw-after-input
-A INPUT -j ufw-after-logging-input
-A INPUT -j ufw-reject-input
-A INPUT -j ufw-track-input
-A FORWARD -j ufw-before-logging-forward
-A FORWARD -j ufw-before-forward
-A FORWARD -j ufw-after-forward
-A FORWARD -j ufw-after-logging-forward
-A FORWARD -j ufw-reject-forward
-A FORWARD -j ufw-track-forward
-A FORWARD -i br0 -o enp6s0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i enp6s0 -o br0 -j ACCEPT
-A OUTPUT -j ufw-before-logging-output
-A OUTPUT -j ufw-before-output
-A OUTPUT -j ufw-after-output
-A OUTPUT -j ufw-after-logging-output
-A OUTPUT -j ufw-reject-output
-A OUTPUT -j ufw-track-output
-A ufw-after-input -p udp -m udp --dport 137 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 138 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp -m tcp --dport 139 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp -m tcp --dport 445 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 67 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp -m udp --dport 68 -j ufw-skip-to-policy-input
-A ufw-after-input -m addrtype --dst-type BROADCAST -j ufw-skip-to-policy-input
-A ufw-before-forward -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 4 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 12 -j ACCEPT
-A ufw-before-forward -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A ufw-before-forward -j ufw-user-forward
-A ufw-before-input -i lo -j ACCEPT
-A ufw-before-input -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-input -m conntrack --ctstate INVALID -j ufw-logging-deny
-A ufw-before-input -m conntrack --ctstate INVALID -j DROP
-A ufw-before-input -p icmp -m icmp --icmp-type 3 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 4 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 12 -j ACCEPT
-A ufw-before-input -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A ufw-before-input -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A ufw-before-input -j ufw-not-local
-A ufw-before-input -d 224.0.0.251/32 -p udp -m udp --dport 5353 -j ACCEPT
-A ufw-before-input -d 239.255.255.250/32 -p udp -m udp --dport 1900 -j ACCEPT
-A ufw-before-input -j ufw-user-input
-A ufw-before-output -o lo -j ACCEPT
-A ufw-before-output -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A ufw-before-output -j ufw-user-output
-A ufw-logging-allow -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW ALLOW] "
-A ufw-logging-deny -m conntrack --ctstate INVALID -m limit --limit 3/min --limit-burst 10 -j RETURN
-A ufw-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW BLOCK] "
-A ufw-not-local -m addrtype --dst-type LOCAL -j RETURN
-A ufw-not-local -m addrtype --dst-type MULTICAST -j RETURN
-A ufw-not-local -m addrtype --dst-type BROADCAST -j RETURN
-A ufw-not-local -m limit --limit 3/min --limit-burst 10 -j ufw-logging-deny
-A ufw-not-local -j DROP
-A ufw-skip-to-policy-forward -j ACCEPT
-A ufw-skip-to-policy-input -j ACCEPT
-A ufw-skip-to-policy-output -j ACCEPT
-A ufw-track-forward -p tcp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-forward -p udp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-input -p tcp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-input -p udp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-output -p tcp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-track-output -p udp -m conntrack --ctstate NEW -j ACCEPT
-A ufw-user-input -i enp6s0 -p tcp -m tcp --sport 22 -j ACCEPT
-A ufw-user-input -i enp6s0 -p tcp -m tcp --sport 80 -j ACCEPT
-A ufw-user-input -i enp6s0 -p tcp -m tcp --sport 443 -j ACCEPT
-A ufw-user-input -i enp6s0 -p tcp -m multiport --dports 2000:2100 -j DROP
-A ufw-user-input -i enp6s0 -p tcp -m tcp --dport 53 -j DROP
-A ufw-user-input -i enp6s0 -p udp -m udp --dport 53 -j DROP
-A ufw-user-input -i enp6s0 -p udp -m udp --dport 67 -j DROP
-A ufw-user-limit -m limit --limit 3/min -j LOG --log-prefix "[UFW LIMIT BLOCK] "
-A ufw-user-limit -j REJECT --reject-with icmp-port-unreachable
-A ufw-user-limit-accept -j ACCEPT
A:
You should reset ufw to defaults and start over:
sudo ufw reset
This will disable ufw and reset ufw to it's installation defaults which means to
- deny all incoming and
- allow all outgoing connections.
Then just add some rules to allow incoming connections for the applications you want to use:
sudo ufw allow ssh
sudo allow http
Now you can enable ufw
sudo ufw enable
Now ufw is running and configured to deny all incoming connections except connections to the ports needed for ssh and http. Outgoing connections are always allowed and this is normally desired.
You don't need to add a deny-rule for incoming connections like in your configuration:
deny in on enp6s0 from any port 30:65535 proto tcp`
This rule is unnecessary, incoming connections are denied by default.
If you want to configure the outgoing connections more restrictive, you can add deny-rules rather then defaulting outgoing connections to deny, it keeps rules simpler, mostly you want outgoing connections to be allowed. Deny-rules for outgoing connections would have to be designed carefully.
sudo ufw deny out 6773
for example would deny all outgoing connections on port 6773, any application that would need to use this port wouldn't be able to work properly anymore.
Interfaces
Using more than one interface makes things a bit more complicated. The defaults (deny in, allow out) apply to all interfaces,also rules which don't specify an interface will apply to all interfaces. You want your interfaces to behave different, so you have to add rules for each interface.
The rules in the section above need to be adapted to match your external interface (the rules in your question look like that).
Outgoing connections are allowed by default on all interfaces but not incoming connections, so you only need to add an allow in-rule for each internal interface:
sudo allow in on "interface" from any
Rules Order
Another important thing is the rules order. When a package arrives at the interface, ufw will check the rules,one by one. Whenever a rule matches the rule will be applied and the package denied, rejected or allowed. The rest of the rules which have not been checked at this moment are not used then. In your case I don't see much relevance of the rule order,but we always have to remind that rule order may matter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot ping localhost after migrating to new Mac
After migrating to a new MacBook Pro I can no longer ping localhost.
I already tried to change my /etc/hosts file although it was already right before.
$ host localhost
localhost has address 127.0.0.1
localhost has IPv6 address ::1
$ ping localhost.
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.098 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.081 ms
Pinging localhost. works somehow, can't understand why.
If I restart the system it wont resolve localhost again, but if I ping localhost. then ping localhost starts working. Dunno if this can help anyone with the same problem
What could be wrong?
$ ping localhost
ping: cannot resolve localhost: Unknown host
$ ping localhost.
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.072 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.084 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.077 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.073 ms
^C
--- localhost ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.072/0.076/0.084/0.005 ms
$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.070 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.072 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.088 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.082 ms
^C
--- localhost ping statistics ---
4 packets transmitted, 4 packets received, 0.0% packet loss
more results
MBPdeFrancisco:~ francisco$ dscacheutil -q host -a name localhost
name: localhost
ipv6_address: fe80:1::1
MBPdeFrancisco:~ francisco$ LC_ALL=C cat -vet /etc/hosts
##$
##$
# Host Database$
#$
# localhost is used to configure the loopback interface$
# when the system is booting. Do not change this entry.$
##$
127.0.0.1 localhostM-bM-^@M-($
255.255.255.255 broadcasthostM-bM-^@M-($
::1 localhostM-bM-^@M-($
fe80::1%lo0 localhost
MBPdeFrancisco:~ francisco$ cat /etc/resolv.conf
#
# macOS Notice
#
# This file is not consulted for DNS hostname resolution, address
# resolution, or the DNS query routing mechanism used by most
# processes on this system.
#
# To view the DNS configuration used by this system, use:
# scutil --dns
#
# SEE ALSO
# dns-sd(1), scutil(8)
#
# This file is automatically generated.
#
domain lan
nameserver 2001:8a0:ddce:7401:9e97:26ff:fedb:6214
nameserver 192.168.1.254
A:
Your /etc/hosts file is corrupt; for some reason it has unicode LINE SEPARATOR characters added to several lines (the "M-bM-^@M-(" thing in LC_ALL=C cat -vet's output), including one of those for localhost. macOS's resolver will treat that weird character as part of the hostname, and so if you somehow manage to ping localhost<LINE SEPARATOR>, it'll resolve to 127.0.0.1 just fine. Plain localhost? Not so much.
I don't know how those weird characters would've gotten added; did you try to edit the file with some sophisticated editor that thought it would be a good idea to use the very latest trendy formatting characters, rather than just sticking with what'll work? If so, don't use that editor for unix-style config files (or scripts, or...). I recommend BBEdit instead; even if you don't buy it, it'll let you do the basic stuff in its free demo mode.
As for how to fix it... Well, first make a backup copy in case this goes sideways and messes things up even more than they are now. Then run the command:
sudo perl -pi -e 's/[^[:ascii:]]//g' /etc/hosts
That should purge all the weird unicode characters out of the file. Then try the dscacheutil command again; you should get something like this:
$ dscacheutil -q host -a name localhost
name: localhost
ipv6_address: ::1
ipv6_address: fe80:1::1
name: localhost
ip_address: 127.0.0.1
P.s. for a explanation why someone thought LINE SEPARATOR was a good idea, see the ever-relevant XKCD and Jeff Atwood's rant about "The Great Newline Schism".
| {
"pile_set_name": "StackExchange"
} |
Q:
Copy specific files from subdirectories into one directory
I have a directory:
❯ find ./images -name *150x150.jpg
./images/2060511653921052666.images/thumb-150x150.jpg
./images/1777759401031970571.images/thumb-150x150.jpg
./images/1901716489977597520.images/thumb-150x150.jpg
./images/2008758225324557620.images/thumb-150x150.jpg
./images/1988762968386208381.images/thumb-150x150.jpg
./images/1802341648716075239.images/thumb-150x150.jpg
./images/2051017760380879322.images/thumb-150x150.jpg
./images/1974813836146304123.images/thumb-150x150.jpg
./images/2003120002653201215.images/thumb-150x150.jpg
./images/1911925394312129508.images/thumb-150x150.jpg
(...)
I would like to copy all those files (thumb-150x150.jpg) into one directory.
❯ find ./images -name *150x150.jpg -exec cp {} ./another-directory \;
But of course every file will be overwritten by the next one.
So how could I copy them to either:
1) 1.jpg, 2.jpg, 3.jpg... etc
or
2) use the subdirectory id (./images/2060511653921052666.images/thumb-150x150.jpg) as the target filename (2060511653921052666.jpg in this example) ?
A:
you can use loop:
i=1
find ./images -name *150x150.jpg | while read line; do
cp $line /anotherdir/$i.jpg
i=$[i+1]
done
| {
"pile_set_name": "StackExchange"
} |
Q:
Function clearing the div in vertical tabs not working
I'm learning javascript and I have a problem with a div... On my CV there are four divs that should be hidden and only the active div should be visible.
All fine with that but at the beginning, all is mixed together. I would like instead that only the general tabcontent will be visible...
Can you help with that?
https://github.com/DevFrancoisXavierPelletier/CV
A:
if you want do this with js code ,just add this code somewhere in index.html :
<script>
openTab(event, 'General');
</script>
but it is not right way ! the best way and lightweight way is handle with css , put this css class in bottom of style.css :
.tabcontent{
display: none;
}
.tabcontent:first-child{
display: block;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Iteratively parsing HTML (with lxml?)
I'm currently trying to iteratively parse a very large HTML document (I know.. yuck) to reduce the amount of memory used. The problem I'm having is that I'm getting XML syntax errors such as:
lxml.etree.XMLSyntaxError: Attribute name redefined, line 134, column 59
This then causes everything to stop.
Is there a way to iteratively parse HTML without choking on syntax errors?
At the moment I'm extracting the line number from the XML syntax error exception, removing that line from the document, and then restarting the process. Seems like a pretty disgusting solution. Is there a better way?
Edit:
This is what I'm currently doing:
context = etree.iterparse(tfile, events=('start', 'end'), html=True)
in_table = False
header_row = True
while context:
try:
event, el = context.next()
# do something
# remove old elements
while el.getprevious() is not None:
del el.getparent()[0]
except etree.XMLSyntaxError, e:
print e.msg
lineno = int(re.search(r'line (\d+),', e.msg).group(1))
remove_line(tfilename, lineno)
tfile = open(tfilename)
context = etree.iterparse(tfile, events=('start', 'end'), html=True)
except KeyError:
print 'oops keyerror'
A:
The perfect solution ended up being Python's very own HTMLParser [docs].
This is the (pretty bad) code I ended up using:
class MyParser(HTMLParser):
def __init__(self):
self.finished = False
self.in_table = False
self.in_row = False
self.in_cell = False
self.current_row = []
self.current_cell = ''
HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if not self.in_table:
if tag == 'table':
if ('id' in attrs) and (attrs['id'] == 'dgResult'):
self.in_table = True
else:
if tag == 'tr':
self.in_row = True
elif tag == 'td':
self.in_cell = True
elif (tag == 'a') and (len(self.current_row) == 7):
url = attrs['href']
self.current_cell = url
def handle_endtag(self, tag):
if tag == 'tr':
if self.in_table:
if self.in_row:
self.in_row = False
print self.current_row
self.current_row = []
elif tag == 'td':
if self.in_table:
if self.in_cell:
self.in_cell = False
self.current_row.append(self.current_cell.strip())
self.current_cell = ''
elif (tag == 'table') and self.in_table:
self.finished = True
def handle_data(self, data):
if not len(self.current_row) == 7:
if self.in_cell:
self.current_cell += data
With that code I could then do this:
parser = MyParser()
for line in myfile:
parser.feed(line)
A:
At the moment lxml etree.iterparse supports keyword argument recover=True, so that instead of writing custom subclass of HTMLParser fixing broken html you can just pass this argument to iterparse.
To properly parse huge and broken html you only need to do following:
etree.iterparse(tfile, events=('start', 'end'), html=True, recover=True)
| {
"pile_set_name": "StackExchange"
} |
Q:
umbraco - xslt transformation of xml file retrieved from web site
i want to apply xslt transformation to a xml file , retrieved from another web server (web site).
i dont know how to do this in umbraco.
here is my xslt.
<xsl:template match="/">
<ul>
<xsl:for-each select="result/job">
<li>
<xsl:value-of select="category"/>
</li>
</xsl:for-each>
</ul>
and source of the xml file will be like this.
http://www.somesite.com/xml.aspx
i am totally new at umbraco
A:
You will want to use the GetXmlDocumentByUrl() method from the Umbraco Library.
http://our.umbraco.org/wiki/reference/umbracolibrary/getxmldocumentbyurl
Your XSLT will end up looking something similar to this (dependant on the source XML structure):
<xsl:template match="/">
<xsl:variable name="MyFeed" select="umbraco.library:GetXmlDocumentByUrl('http://www.somesite.com/xml.aspx')" />
<ul>
<xsl:for-each select="$MyFeed/result/job">
<li>
<xsl:value-of select="./category"/>
</li>
</xsl:for-each>
</ul>
</xsl:template>
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the current state of affairs in the world of Java timers?
From time to time I encounter mentions of System.nanoTime() being a lot slower (the call could cost up to microseconds) than System.currentTimeMillis(), but prooflinks are often outdated, or lead to some fairly opinionated blog posts that can't be really trusted, or contain information pertaining to specific platform, or this, or that and so on.
I didn't run benchmarks since I'm being realistic about my ability to conduct an experiment concerning such a sensitive matter, but my conditions are really well-defined, so I'm expecting quite a simple answer.
So, on an average 64-bit Linux (implying 64-bit JRE), Java 8 and a modern hardware, will switching to nanoTime() cost me that microseconds to call? Should I stay with currentTimeMillis()?
A:
As always, it depends on what you're using it for. Since others are bashing nanoTime, I'll put a plug in for it. I exclusively use nanoTime to measure elapsed time in production code.
I shy away from currentTimeMillis in production because I typically need a clock that doesn't jump backwards and forwards around like the wall clock can (and does). This is critical in my systems which use important timer-based decisions. nanoTime should be monotonically increasing at the rate you'd expect.
In fact, one of my co-workers says "currentTimeMillis is only useful for human entertainment," (such as the time in debug logs, or displayed on a website) because it cannot be trusted to measure elapsed time.
But really, we try not to use time as much as possible, and attempt to keep time out of our protocols; then we try to use logical clocks; and finally if absolutely necessary, we use durations based on nanoTime.
Update: There is one place where we use currentTimeMillis as a sanity check when connecting two hosts, but we're checking if the hosts' clocks are more than 5 minutes apart.
A:
If you are currently using currentTimeMillis() and are happy with the resolution, then you definitely shouldn't change.
According the javadoc:
This method provides nanosecond precision, but not necessarily
nanosecond resolution (that is, how frequently the value changes)
no guarantees are made except that the resolution is at least as
good as that of {@link #currentTimeMillis()}.
So depending on the OS implementation, there is no guarantee that the nano time returned is even correct! It's just the 9 digits long and has the same number of millis as currentTimeMillis().
A perfectly valid implementation could be currentTimeMillis() * 1000000
Therefore, I don't think you really gain a benefit from nano seconds even if there wasn't a performance issue.
A:
I want to stress that even if the calls would be very cheap, you will not get the nanosecond resolution of your measurements.
Let me give you an example (code from http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--):
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
So while both long values will be resolved to a nanosecond, JVM is not giving you a guarantee that every call you make to nanoTime(), JVM will give you a new value.
To illustrate this, I wrote a simple program and ran it on Win7x64 (feel free to run it and report the results as well):
package testNano;
public class Main {
public static void main(String[] args) {
long attempts = 10_000_000L;
long stale = 0;
long prevTime;
for (int i = 0; i < attempts; i++) {
prevTime = System.nanoTime();
long nanoTime = System.nanoTime();
if (prevTime == nanoTime) stale++;
}
System.out.format("nanoTime() returned stale value in %d out of %d tests%n", stale, attempts);
}
}
It prints out nanoTime() returned stale value in 9117171 out of 10000000 tests.
EDIT
I also recommend to read the Oracle article on this: https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks. The conclusions of the article are:
If you are interested in measuring absolute time then always use System.currentTimeMillis(). Be aware that its resolution may be quite coarse (though this is rarely an issue for absolute times.)
If you are interested in measuring/calculating elapsed time, then always use System.nanoTime(). On most systems it will give a resolution on the order of microseconds. Be aware though, this call can also take microseconds to execute on some platforms.
Also you might find this discussion interesting: Why is System.nanoTime() way slower (in performance) than System.currentTimeMillis()?.
| {
"pile_set_name": "StackExchange"
} |
Q:
RSpec testing Devise SessionController with Jbuilder view
I'm using RSpec for testing a SessionsController I am overriding from Devise in my Rails application:
class Users::SessionsController < Devise::SessionsController
The sign_in method renders a jbuilder view:
render '/users/sign_in', status: :ok
I get the expected result when testing the view using curl. But I haven't been able to make this work with my specs. I get the following error:
Failure/Error: post '/users/sign_in', @data, format: 'json'
ActionView::MissingTemplate:
Missing template users/sign_in with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :haml]}. Searched in:
The jbuilder views are working for other specs by using render_views. But when I add render_views to this spec, I get:
`method_missing': undefined local variable or method `render_views' for RSpec::ExampleGroups::UserEdit:Class (NameError)
The difference between the specs where render_views works and this spec is the type. It's working here:
describe SomeController, type: :controller do
But not on this one:
describe 'User edit', type: :request do
It's a request type since I'm testing the API response. As I said, I get the expected JSON view using curl from the command line, but it doesn't work in the tests. I must be missing some small detail or doing something completely wrong.
I also tried adding this to Rspec.configure but it didn't change anything:
config.render_views
Edit:
I must add the test pass when using: render json: { stuff }.to_json, status: :ok in the controller's response. This started failing when I refactored this into a jbuilder view.
Regarding the format, I'm using the 'simple_token_authentication' gem and passing this info to each request in the spec:
{
'X-User-Email' => user.email,
'X-User-Token' => user.authentication_token,
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
I had format: :json in other tests and didn't make it work:
post '/users/sign_in', @data, format: :json
So setting format: :json as a value in the second parameter made things work.
A:
You don't need setting render_views for request specs. In fact, the error you're getting right now says that views are actually rendering, it's just there's no correct one for your request type (html).
You need to add format: :json to your second parameter in your request, like this:
@data[:format] = :json
post '/users/sign_in', @data
| {
"pile_set_name": "StackExchange"
} |
Q:
SKAction playSoundFileNamed no audio through iphone speaker
Has anyone had issues playing audio via the SKAction playSoundFileNamed using iOS Sprite Kit through the external speaker of your iOS device? I have the following code that plays the M4A file with no issue through the headphones; however, no audio is played when I unplug the headphones stepping through code it executes just no sound. I have another app that does not use this method and it plays with no issue.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKAction *sound = [SKAction playSoundFileNamed:@"blast.m4a" waitForCompletion:NO];
[self runAction:sound];
}
A:
I had a similar issue but was able to fix it by setting AudioSession category to Playback. This causes the audio to be routed through the phone's speaker when headphones aren't plugged in.
// at the top of AppDelegate.m
#import <AVFoundation/AVFoundation.h>
// in application:didFinishLaunchingWithOptions:
NSError *error;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
You can find more information about this in Apple's Audio Session Programming Guide.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why won't `system` create and return a variable?
In R, When I run
system("FOO='test123'")
I would expect
system("echo $FOO")
to return
test123
in the same way that
system("echo $USER")
returns my username
But it returns nothing. Why is this?
Why would anyone want to do this? I was trying to simulate the use of env FOO='test1234 R -vanilla < script.R while writing script.R, which in turn calls system("echo $FOO)`
A:
Each system call will fire up a NEW shell, with its own environment. Variables set in one shell will not carry over to subsequent shells - they'll each be completely independent of each other.
A:
I don't know R, but in other languages system() (at least on Unix-like systems) creates a new shell (/bin/sh) process to execute the command. Your FOO='test123' sets the value of $FOO, but only within that process. Your system("echo $FOO") executes in a new process in which $FOO hasn't been set.
If R has a way to set environment variables internally (setenv, perhaps?), you should use that instead.
EDIT: As @Joshua says in a comment, it's Sys.setenv.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is XCode giving me an 'unrecognized selector' error?
I'm developing a Mac app using Swift 2 and Xcode 7.
I'm just getting started with Swift after many years focused on Ruby with a touch of JavaScript.
The Mac app that I'm creating includes a web browser view.
My ViewController.swift says:
import Cocoa
import WebKit
class ViewController: NSViewController {
@IBOutlet var url: NSTextField!
@IBOutlet var browser: WKWebView!
@IBAction func go(sender: AnyObject) {
// browser.loadRequest(NSURLRequest(URL:NSURL(string: url.stringValue)!))
// above line broken down for debugging
let url1 = url.stringValue
print("url1 = \(url1)")
let url2 = NSURL(string: url1)!
print("url2 = \(url2)")
let url3 = NSURLRequest(URL:url2)
print("url3 = \(url3)")
print("browser is \(browser)")
browser.loadRequest(url3)
}
}
The app builds successfully. When I run it, enter http://apple.com into the URL field and click the Go button, I see:
url1 = http://apple.com
url2 = http://apple.com
url3 = <NSURLRequest: 0x600000001400> { URL: http://apple.com }
browser is <WebView: 0x608000120e60>
2016-04-06 13:39:51.664 Testivate[6516:427535] -[WebView loadRequest:]: unrecognized selector sent to instance 0x608000120e60
2016-04-06 13:39:51.664 Testivate[6516:427535] -[WebView loadRequest:]: unrecognized selector sent to instance 0x608000120e60
2016-04-06 13:39:51.667 Testivate[6516:427535] (
0 CoreFoundation 0x00007fff93f4a4f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff8ca7a73c objc_exception_throw + 48
2 CoreFoundation 0x00007fff93fb41ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00007fff93eba571 ___forwarding___ + 1009
4 CoreFoundation 0x00007fff93eba0f8 _CF_forwarding_prep_0 + 120
5 Testivate 0x000000010000271a _TFC9Testivate14ViewController2gofPs9AnyObject_T_ + 2154
6 Testivate 0x00000001000027b6 _TToFC9Testivate14ViewController2gofPs9AnyObject_T_ + 54
7 libsystem_trace.dylib 0x00007fff96e1807a _os_activity_initiate + 75
8 AppKit 0x00007fff94567e89 -[NSApplication sendAction:to:from:] + 460
9 AppKit 0x00007fff94579fde -[NSControl sendAction:to:] + 86
10 AppKit 0x00007fff94579f08 __26-[NSCell _sendActionFrom:]_block_invoke + 131
11 libsystem_trace.dylib 0x00007fff96e1807a _os_activity_initiate + 75
12 AppKit 0x00007fff94579e65 -[NSCell _sendActionFrom:] + 144
13 libsystem_trace.dylib 0x00007fff96e1807a _os_activity_initiate + 75
14 AppKit 0x00007fff9457848a -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2693
15 AppKit 0x00007fff945c0fd0 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 744
16 AppKit 0x00007fff94576bb4 -[NSControl mouseDown:] + 669
17 AppKit 0x00007fff94acb469 -[NSWindow _handleMouseDownEvent:isDelayedEvent:] + 6322
18 AppKit 0x00007fff94acc44d -[NSWindow _reallySendEvent:isDelayedEvent:] + 212
19 AppKit 0x00007fff9450b63d -[NSWindow sendEvent:] + 517
20 AppKit 0x00007fff9448bb3c -[NSApplication sendEvent:] + 2540
21 AppKit 0x00007fff942f2ef6 -[NSApplication run] + 796
22 AppKit 0x00007fff942bc46c NSApplicationMain + 1176
23 Testivate 0x0000000100004f34 main + 84
24 libdyld.dylib 0x00007fff9099a5ad start + 1
25 ??? 0x0000000000000003 0x0 + 3
)
Initially I thought the error was saying that loadRequest was an unrecognized selector for browser, but you can see I've pulled apart the function and browser is clearly an instance of WebView, which definitely has loadRequest as a method. You can see from how I've pulled apart the method that I'm definitely providing the loadRequest method with the expected NSURLRequest object.
I'm now thinking that maybe this has something to do with being unable to find the WebView in Main.storyboard, but surely it should be able to? I've defined connections on it like this:
When you view Main.storyboard as source, it says:
<webView fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Ocj-mD-woP">
<rect key="frame" x="62" y="20" width="406" height="211"/>
<webPreferences key="preferences" defaultFontSize="12" defaultFixedFontSize="12">
<nil key="identifier"/>
</webPreferences>
</webView>
Any thoughts? Thanks.
A:
You're mixing up two different kinds of web views.
In your code, you're saying that browser is a WKWebView. That's the newer kind of web view, that was first available in OS X 10.10. It has a method named -loadView: in Objective-C, or loadView() in Swift.
@IBOutlet var browser: WKWebView!
However, when you run the code, the object is actually a WebView, because that's what you put in your storyboard. That's an older kind of web view. It doesn't have a method named -loadView: so you get an error when you try to call it.
browser is <WebView: 0x608000120e60>
-[WebView loadRequest:]: unrecognized selector sent to instance 0x608000120e60
(Read the documentation you linked to again. The WebView's main frame implements -loadRequest:, but WebView does not.)
Here are two possible fixes:
Easier: Fix your code to use WebView correctly, but leave the storyboard the same.
@IBOutlet var browser: WebView!
...
browser.mainFrame.loadRequest(url3)
Harder: Keep the code using WKWebView, but remove the WebView from your storyboard.
Unfortunately it's currently impossible to put a WKWebView in a storyboard, so you will have to write some code to set it up yourself. See the linked answer for an example of how to do it.
If you want to take advantage of the new features of WKWebView, you'll have to use the second alternative.
| {
"pile_set_name": "StackExchange"
} |
Q:
No database selected: login php code
<?php
session_start();
$con=mysqli_connect("localhost","xxx","xxxxxx","xxx");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$eadd = $_POST['eadd'];
$pass = $_POST['pass'];
$eadd = htmlspecialchars(stripslashes(strip_tags($eadd)));
$pass = htmlspecialchars(stripslashes(strip_tags($pass)));
if (filter_var($eadd, FILTER_VALIDATE_EMAIL)) {
$sql = mysql_query("SELECT * FROM accounts WHERE Emailadd = '$eadd' AND Password = '$pass'");
if(!$sql){
die('There was an error in query '. mysql_error());
}
$count = mysql_numrows($sql) or die(mysql_error());
if ($count<=0)
{
echo "
<html>
<style>
body{
background-color:#cccccc;
}
#error{
position:relative;
margin:auto;
top:20px;
width:320px;
height:55px;
background-color:#63a8d7;
border:1px solid #2a262a;
}
#errorC{
position:absolute;
top:20px;
left:20px;
font: 14px arial, tahoma;
}
</style>
<body>
<div id=error>
<div id=errorC>
Incorrect Email Address and Password! <a href=index.php>GO BACK</a>
</div>
</div>
</body>
</html>
";
}
else
{
//have them logged in
$_SESSION['account'] = $eadd;
header('location:home.php');
}
mysqli_close($con);
} else {
echo "
<html>
<style>
body{
background-color:#cccccc;
}
#error{
position:relative;
margin:auto;
top:20px;
width:320px;
height:55px;
background-color:#63a8d7;
border:1px solid #2a262a;
}
#errorC{
position:absolute;
top:20px;
left:20px;
font: 14px arial, tahoma;
}
</style>
<body>
<div id=error>
<div id=errorC>
Invalid Email Address! <a href=index.php>GO BACK</a>
</div>
</div>
</body>
</html>
";
}
?>
Why there is an error "No database selected"? My mysqli_connect is correct. I have another register php code, using which I can register some email address using that connection.But here in login php code, I can't login with the user email address.
A:
From the above code its look like you are using mysqli_connect for database connection and mysql_query for query execution. Use mysqli_query instead of mysql_query . Like this
mysqli_query("SELECT * FROM accounts WHERE Emailadd = '$eadd' AND Password = '$pass'");
| {
"pile_set_name": "StackExchange"
} |
Q:
Didn't get the correct x y value in onTouch
I want to move an image when I drag on the screen, but the x and y values in ACTION_MOVE are not correct. I have printed the x and y value in ACTION_MOVE. In each alternate it prints the correct x and y value.
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
float x=0;
float y=0;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
x=event.getX();
y=event.getY();
System.out.println("x= "+x+" y="+y);
int width = 100, height = 100;
lp = new AbsoluteLayout.LayoutParams(width, height, (int) (x), (int) (y));
break;
}
mLayout.updateViewLayout(view, lp);
return true;
}
This is my code. And printed output is:
01-17 10:31:11.721: I/System.out(3983): x= 71.0 y=91.0
01-17 10:31:11.746: I/System.out(3983): x= 102.0 y=24.0
01-17 10:31:11.776: I/System.out(3983): x= 72.0 y=91.0
01-17 10:31:11.806: I/System.out(3983): x= 103.0 y=24.0
01-17 10:31:11.826: I/System.out(3983): x= 73.0 y=91.0
01-17 10:31:11.851: I/System.out(3983): x= 104.0 y=24.0
01-17 10:31:11.871: I/System.out(3983): x= 74.0 y=91.0
01-17 10:31:11.896: I/System.out(3983): x= 105.0 y=24.0
01-17 10:31:11.921: I/System.out(3983): x= 75.0 y=91.0
01-17 10:31:11.941: I/System.out(3983): x= 107.0 y=24.0
01-17 10:31:11.957: I/System.out(3983): x= 76.0 y=90.0
01-17 10:31:11.976: I/System.out(3983): x= 109.0 y=24.0
01-17 10:31:11.996: I/System.out(3983): x= 77.0 y=90.0
01-17 10:31:12.026: I/System.out(3983): x= 110.0 y=24.0
01-17 10:31:12.056: I/System.out(3983): x= 78.0 y=90.0
01-17 10:31:12.101: I/System.out(3983): x= 111.0 y=24.0
01-17 10:31:12.131: I/System.out(3983): x= 79.0 y=89.0
01-17 10:31:12.186: I/System.out(3983): x= 112.0 y=24.0
01-17 10:31:12.231: I/System.out(3983): x= 80.0 y=89.0
01-17 10:31:12.276: I/System.out(3983): x= 113.0 y=24.0
01-17 10:31:12.296: I/System.out(3983): x= 80.0 y=88.0
01-17 10:31:12.316: I/System.out(3983): x= 114.0 y=24.0
01-17 10:31:12.336: I/System.out(3983): x= 81.0 y=88.0
The alternate points are correct. But how is it happening? How can I solve this problem?
A:
If you check the answer of this question, he says that Views can have a built-in touch event which might be interfering with your touch event. Check if your view has one.
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery template array inside of array
I've a json object like this
[Object]
0: Object
domains: Array[1]
0: "domain1.com"
length: 1
__proto__: Array[0]
name: "name1"
1: Object
domains: Array[2]
0: "domain2.com"
length: 1
__proto__: Array[0]
name: "name2"
These objects are generated on the client and I want to display them by using jQuery.tmpl plugin. I've defined a template to be:
<script id="domain_template" type="text/x-jquery-tmpl">
{{each response}}
{{each response.domains}}
<div class="dummy_copy" data-srvType="${srvType}" data-domain="${domain}">"${value}"</div>
{{/each}}
{{/each}}
</script>
What did i do wrong with it here? thanks
A:
First of all, i convert to JSON my object like this.
arr = []
for srv in response
for domain in srv.domains
arr.push srvType: srv.srvType, domain: domain
domainTmpl = $.tmpl $(@domainTemplate).template(), arr
After having json object it was rendered by jquery template.This will helpfull for all i think
| {
"pile_set_name": "StackExchange"
} |
Q:
Folding a selection of points on a 3D cube
I am trying to find an effective algorithm for the following 3D Cube Selection problem:
Imagine a 2D array of Points (lets make it square of size x size) and call it a side.
For ease of calculations lets declare max as size-1
Create a Cube of six sides, keeping 0,0 at the lower left hand side and max,max at top right.
Using z to track the side a single cube is located, y as up and x as right
public class Point3D {
public int x,y,z;
public Point3D(){}
public Point3D(int X, int Y, int Z) {
x = X;
y = Y;
z = Z;
}
}
Point3D[,,] CreateCube(int size)
{
Point3D[,,] Cube = new Point3D[6, size, size];
for(int z=0;z<6;z++)
{
for(int y=0;y<size;y++)
{
for(int x=0;x<size;x++)
{
Cube[z,y,x] = new Point3D(x,y,z);
}
}
}
return Cube;
}
Now to select a random single point, we can just use three random numbers such that:
Point3D point = new Point(
Random(0,size), // 0 and max
Random(0,size), // 0 and max
Random(0,6)); // 0 and 5
To select a plus we could detect if a given direction would fit inside the current side.
Otherwise we find the cube located on the side touching the center point.
Using 4 functions with something like:
private T GetUpFrom<T>(T[,,] dataSet, Point3D point) where T : class {
if(point.y < max)
return dataSet[point.z, point.y + 1, point.x];
else {
switch(point.z) {
case 0: return dataSet[1, point.x, max]; // x+
case 1: return dataSet[5, max, max - point.x];// y+
case 2: return dataSet[1, 0, point.x]; // z+
case 3: return dataSet[1, max - point.x, 0]; // x-
case 4: return dataSet[2, max, point.x]; // y-
case 5: return dataSet[1, max, max - point.x];// z-
}
}
return null;
}
Now I would like to find a way to select arbitrary shapes (like predefined random blobs) at a random point.
But would settle for adjusting it to either a Square or jagged Circle.
The actual surface area would be warped and folded onto itself on corners, which is fine and does not need compensating ( imagine putting a sticker on the corner on a cube, if the corner matches the center of the sticker one fourth of the sticker would need to be removed for it to stick and fold on the corner). Again this is the desired effect.
No duplicate selections are allowed, thus cubes that would be selected twice would need to be filtered somehow (or calculated in such a way that duplicates do not occur). Which could be a simple as using a HashSet or a List and using a helper function to check if the entry is unique (which is fine as selections will always be far below 1000 cubes max).
The delegate for this function in the class containing the Sides of the Cube looks like:
delegate T[] SelectShape(Point3D point, int size);
Currently I'm thinking of checking each side of the Cube to see which part of the selection is located on that side.
Calculating which part of the selection is on the same side of the selected Point3D, would be trivial as we don't need to translate the positions, just the boundary.
Next would be 5 translations, followed by checking the other 5 sides to see if part of the selected area is on that side.
I'm getting rusty in solving problems like this, so was wondering if anyone has a better solution for this problem.
@arghbleargh Requested a further explanation:
We will use a Cube of 6 sides and use a size of 16. Each side is 16x16 points.
Stored as a three dimensional array I used z for side, y, x such that the array would be initiated with: new Point3D[z, y, x], it would work almost identical for jagged arrays, which are serializable by default (so that would be nice too) [z][y][x] but would require seperate initialization of each subarray.
Let's select a square with the size of 5x5, centered around a selected point.
To find such a 5x5 square substract and add 2 to the axis in question: x-2 to x+2 and y-2 to y+2.
Randomly selectubg a side, the point we select is z = 0 (the x+ side of the Cube), y = 6, x = 6.
Both 6-2 and 6+2 are well within the limits of 16 x 16 array of the side and easy to select.
Shifting the selection point to x=0 and y=6 however would prove a little more challenging.
As x - 2 would require a look up of the side to the left of the side we selected.
Luckily we selected side 0 or x+, because as long as we are not on the top or bottom side and not going to the top or bottom side of the cube, all axis are x+ = right, y+ = up.
So to get the coordinates on the side to the left would only require a subtraction of max (size - 1) - x. Remember size = 16, max = 15, x = 0-2 = -2, max - x = 13.
The subsection on this side would thus be x = 13 to 15, y = 4 to 8.
Adding this to the part we could select on the original side would give the entire selection.
Shifting the selection to 0,6 would prove more complicated, as now we cannot hide behind the safety of knowing all axis align easily. Some rotation might be required. There are only 4 possible translations, so it is still manageable.
Shifting to 0,0 is where the problems really start to appear.
As now both left and down require to wrap around to other sides. Further more, as even the subdivided part would have an area fall outside.
The only salve on this wound is that we do not care about the overlapping parts of the selection.
So we can either skip them when possible or filter them from the results later.
Now that we move from a 'normal axis' side to the bottom one, we would need to rotate and match the correct coordinates so that the points wrap around the edge correctly.
As the axis of each side are folded in a cube, some axis might need to flip or rotate to select the right points.
The question remains if there are better solutions available of selecting all points on a cube which are inside an area. Perhaps I could give each side a translation matrix and test coordinates in world space?
A:
Found a pretty good solution that requires little effort to implement.
Create a storage for a Hollow Cube with a size of n + 2, where n is the size of the cube contained in the data. This satisfies the : sides are touching but do not overlap or share certain points.
This will simplify calculations and translations by creating a lookup array that uses Cartesian coordinates.
With a single translation function to take the coordinates of a selected point, get the 'world position'.
Using that function we can store each point into the cartesian lookup array.
When selecting a point, we can again use the same function (or use stored data) and subtract (to get AA or min position) and add (to get BB or max position).
Then we can just lookup each entry between the AA.xyz and BB.xyz coordinates.
Each null entry should be skipped.
Optimize if required by using a type of array that return null if z is not 0 or size-1 and thus does not need to store null references of the 'hollow cube' in the middle.
Now that the cube can select 3D cubes, the other shapes are trivial, given a 3D point, define a 3D shape and test each part in the shape with the lookup array, if not null add it to selection.
Each point is only selected once as we only check each position once.
A little calculation overhead due to testing against the empty inside and outside of the cube, but array access is so fast that this solution is fine for my current project.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS automatic isn't working
I am writing a client-side application with AngularJS for fun. In a part of the application it's supposed to show all the applicants in a table, automatically fetched from my JSON array. But it isn't working.
This is my code:
//engine.js
(function(){
angular
.module("resumeBase", []);
})();
//controllers.js
(function(){
angular
.module("resumeBase")
.controller("tabularList", listController);
function listController() {
var vm = this;
vm.data = applicants;
}
var applicants = [
{
firstname: "Nima",
lastname: "Bavari",
evaluation: 5,
category: "IT & Computers",
fileLocation: "",
empConfirmed: "found",
confirmTime: "01-01-2017",
employer: "EnDATA",
payConfirmed: "yes"
}
]
})();
<!DOCTYPE html>
<html ng-app="resumeBase">
<head>
<title>::Search Entries::</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
</head><body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script type="text/javascript" src="scripts/engine.js"></script>
<script type="text/javascript" src="scripts/controllers.js"></script>
<div id="container" ng-controller="tabularList">
<hr />
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Evaluation</th>
<th>Category</th>
<th>Resume</th>
<th>Found Job?</th>
<th>Date and Time</th>
<th>Employer</th>
<th>Paid Us?</th>
</tr>
<tr ng-repeat="item in tabularList.data">
<td>{{item.firstname}}</td>
<td>{{item.lastname}}</td>
<td>{{item.evaluation}}</td>
<td>{{item.category}}</td>
<td><a ng-href="{{item.fileLocation}}" target="blank">{{item.fileLocation}}</a></td>
<td>{{item.empConfirmed}}</td>
<td>{{item.confirmTime}}</td>
<td>{{item.employer}}</td>
<td>{{item.payConfirmed}}</td>
</tr>
</table>
[<a href="index.php">Add New Entry</a>]
</div>
</body>
</html>
What do you recommend? Where is my mistake?
A:
You are missing the controller as syntax, Just change your HTML as,
<div id="container" ng-controller="tabularList as vm">
also,
<tr ng-repeat="item in vm.data">
DEMO
//engine.js
(function(){
angular
.module("resumeBase", []);
})();
//controllers.js
(function(){
angular
.module("resumeBase")
.controller("tabularList", listController);
function listController() {
var vm = this;
vm.data = applicants;
}
var applicants = [
{
firstname: "Nima",
lastname: "Bavari",
evaluation: 5,
category: "IT & Computers",
fileLocation: "",
empConfirmed: "found",
confirmTime: "01-01-2017",
employer: "EnDATA",
payConfirmed: "yes"
}
]
})();
<!DOCTYPE html>
<html ng-app="resumeBase">
<head>
<title>::Search Entries::</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
</head><body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div id="container" ng-controller="tabularList as vm">
<hr />
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Evaluation</th>
<th>Category</th>
<th>Resume</th>
<th>Found Job?</th>
<th>Date and Time</th>
<th>Employer</th>
<th>Paid Us?</th>
</tr>
<tr ng-repeat="item in vm.data">
<td>{{item.firstname}}</td>
<td>{{item.lastname}}</td>
<td>{{item.evaluation}}</td>
<td>{{item.category}}</td>
<td><a ng-href="{{item.fileLocation}}" target="blank">{{item.fileLocation}}</a></td>
<td>{{item.empConfirmed}}</td>
<td>{{item.confirmTime}}</td>
<td>{{item.employer}}</td>
<td>{{item.payConfirmed}}</td>
</tr>
</table>
[<a href="index.php">Add New Entry</a>]
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieval of NSArray from NSUserDefaults returns empty array
I am experiencing strange behaviour with NSUserDefaults. I am initially storing an array to the user defaults in my AppDelegate.m:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:@"weekdayIDs"];
if (weekdayIDs == nil) {
weekdayIDs = [NSArray arrayWithObjects:@"su", @"mo", @"tu", @"we", @"th", @"fr", @"sa", nil];
[defaults setObject:weekdayIDs forKey:@"weekdayIDs"];
}
[defaults synchronize];
Now in a different view controller ContentViewController.m, I want to retrieve the array:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:@"weekdayIDs"];
But I just get an array without objects, although its count == 7. I also used arrayForKey: but with the same result. I added a screenshot from my breakpoint.
I am regularly using NSUserDefaults, but currently I am bit stuck on this. It's probably a stupid mistake, anyone care to help?
Thank you so much!
-- Update:
I also figured it might be a problem with the init of the NSArray in the first place, but even replacing its objects with manually created NSString *dwid_su = [NSString stringWithString:@"su"]; didn't work.
A:
Your code works perfectly.
Just, print the description of you array and you will see what you want.
Right click on weekdayIDs variable and select Print Description of weekdayIDs
or use through lldb debugger console po weekdayIDs
or NSLog(@"%@", weekdayIDs);
Here the results.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble displaying data in AngularJS
I made a small angularjs application where the user picks a month and then the page displays the appropriate fly (as in fly fishing) to use. I can get part of it to work but not the other. Part that is working: when the user selects a month the app does display the correct fly to use. Part that is not working: I would like the display text to read: "The correct fly to use for [month name goes here] is : [name of fly goes here]."
Repeating what I said earlier, the second part of what I want displayed is working. I do get the correct fly name. It is the first part where I want it to repeat the selected month that I cannot figure out. Thank you.
JS
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: 'views/home.html',
controller: 'myController'
})
.when('/directory', {
templateUrl: 'views/directory.html',
//since this page requires a controller
controller: 'myController'
})
.otherwise({
redirectTo: '/home'
});
}]); //.config
angular.module('myApp')
.controller('myController', function($scope) {
$scope.dir_message = ("This is the directory page.");
$scope.months = [{monthName: 'January', flyName: 'Clouser Deep Minnow' },{ monthName: 'February', flyName: 'Woolly Bugger' },{ monthName: 'March', flyName: 'Zonker' }];
});
HTML
<p>Select a Month.</p>
<div ng-app="myApp">
<select ng-model="selectedItem">
<option ng-repeat="month in months" value="{{month.flyName}}">{{month.monthName}}</option>
</select>
<div ng-model="month">
<p>The correct fly to use for {{month.monthName}} is : {{selectedItem}}</p>
</div>
</div>
A:
Use ng-options instead of ng-repeat. That will allow binding a month object (with its name and its fly name) to the selectedItem property.
<select ng-model="selectedItem" ng-options="month as month.monthName for month in months">
<option value=""></option>
</select>
<p>The correct fly to use for {{ selectedItem.monthName}} is : {{ selectedItem.flyName }}</p>
Note than ng-model on a div makes no sense.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC 4 - Insert list/array from Controller to SQL Server
I am using MVC4 C# Razor view and MS SQL Server. I need to insert a list/array value from controller to sql server. I am passing values from view to controller and getting the values in controller.
My data structures are -
{sid: "101", m1Qty: "1", m2Qty: "3", m3Qty: ""}
{sid: "102", m1Qty: "5", m2Qty: "6", m3Qty: ""}
{sid: "103", m1Qty: "8", m2Qty: "0", m3Qty: ""}
Above data needed to insert my table (tbl_monthqty) in the below order. ID auto generated -
ID SID MonthID mQty
1 101 1 1
2 102 1 5
3 103 1 8
4 101 2 3
5 102 2 6
If any value null or 0, need to ignore
MonthID is for example - m1Qty = 1, m2Qty = 2, m3Qty = 3
My controller (C#) is -
[HttpPost]
public JsonResult SaveQty(IList<AllQty> model)
{
var list = new [] { model };
var count = list.Count();
DataTable dt = new DataTable();
dt.Columns.Add("SID");
dt.Columns.Add("MonthID");
dt.Columns.Add("mQty");
for(int i=0; i<count; i++)
{
//dt.Rows.Add();
// Not sure what I will do here
}
return Json(new { success = true });
}
My class is -
public class AllQty
{
public int SID { get; set; }
public int MonthID { get; set; }
public int mQty { get; set; }
}
I am getting the list value in controller but not sure how I will insert those list/array values in my table. I have tried few asked questions like this but did not work.
A:
First create data model that represent json data structure:
public class FirstModel
{
public int SID;
public string m1Qty;
public string m2Qty;
public string m3Qty;
}
Then data model that you want to store the data:
public class AllQty
{
public int SID { get; set; }
public int MonthID { get; set; }
public int mQty { get; set; }
}
Then convert the json to list of FirstModel objects (I assume you already did it), and finally convert data in List to List :
List<FirstModel> qtYs = new List<FirstModel>();
List<AllQty> allQties = new List<AllQty>();
foreach (FirstModel item in qtYs)
{
if (string.IsNullOrEmpty(item.m1Qty))
{
AllQty allQty = new AllQty
{
MonthID = 1,
mQty = int.Parse(item.m1Qty),
SID = item.SID
};
allQties.Add(allQty);
}
if (string.IsNullOrEmpty(item.m2Qty))
{
AllQty allQty = new AllQty
{
MonthID = 2,
mQty = int.Parse(item.m1Qty),
SID = item.SID
};
allQties.Add(allQty);
}
if (string.IsNullOrEmpty(item.m3Qty))
{
AllQty allQty = new AllQty
{
MonthID = 3,
mQty = int.Parse(item.m1Qty),
SID = item.SID
};
allQties.Add(allQty);
}
}
DataTable dt = new DataTable();
dt.Columns.Add("SID");
dt.Columns.Add("MonthID");
dt.Columns.Add("mQty");
foreach (AllQty allQty in allQties)
{
var row = dt.NewRow();
row["SID"] = allQty.SID;
row["MonthID"] = allQty.MonthID;
row["mQty"] = allQty.mQty;
dt.Rows.Add(row);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What does ----s mean in the context of StringBuilder.ToString()?
The Reference Source page for stringbuilder.cs has this comment in the ToString method:
if (chunk.m_ChunkLength > 0)
{
// Copy these into local variables so that they
// are stable even in the presence of ----s (hackers might do this)
char[] sourceArray = chunk.m_ChunkChars;
int chunkOffset = chunk.m_ChunkOffset;
int chunkLength = chunk.m_ChunkLength;
What does this mean? Is ----s something a malicious user might insert into a string to be formatted?
A:
The source code for the published Reference Source is pushed through a filter that removes objectionable content from the source. Verboten words are one, Microsoft programmers use profanity in their comments. So are the names of devs, Microsoft wants to hide their identity. Such a word or name is substituted by dashes.
In this case you can tell what used to be there from the CoreCLR, the open-sourced version of the .NET Framework. It is a verboten word:
// Copy these into local variables so that they are stable even in the presence of race conditions
Which was hand-edited from the original that you looked at before being submitted to Github, Microsoft also doesn't want to accuse their customers of being hackers, it originally said races, thus turning into ----s :)
A:
In the CoreCLR repository you have a fuller quote:
Copy these into local variables so that they are stable even in the presence of race conditions
Github
Basically: it's a threading consideration.
A:
In addition to the great answer by @Jeroen, this is more than just a threading consideration. It's to prevent someone from intentionally creating a race condition and causing a buffer overflow in that manner. Later in the code, the length of that local variable is checked. If the code were to check the length of the accessible variable instead, it could have changed on a different thread between the time length was checked and wstrcpy was called:
// Check that we will not overrun our boundaries.
if ((uint)(chunkLength + chunkOffset) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
{
///
/// imagine that another thread has changed the chunk.m_ChunkChars array here!
/// we're now in big trouble, our attempt to prevent a buffer overflow has been thawrted!
/// oh wait, we're ok, because we're using a local variable that the other thread can't access anyway.
fixed (char* sourcePtr = sourceArray)
string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
}
else
{
throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
} while (chunk != null);
Really interesting question though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Systemd read /etc/pm/.....?
Do systems using systemd read and execute scripts in /etc/pm/sleep.d/ ?
I'm starting to concluded the answer is that systemd ignores these scripts. If this is true what is the replacement?
Update: man systemd-sleep states scripts can be added to /lib/systemd/system-sleep/. The details were insufficient for me but I tried a modification of an Arch wiki example and created /lib/systemd/system-sleep/root-resume.service.
[Unit]
Description=Local system resume actions
After=suspend.target
[Service]
Type=simple
ExecStart=/bin/systemctl restart network-manager.service
[Install]
WantedBy=suspend.target
My intention is to restart network-manager after resuming because occasionally it isn't working.
This doesn't seem to be doing what I want.
A:
Scripts in /etc/pm/config.d|power.d|sleep.d are ignored under systemd. Instead a systemd "unit" (service) must be created and enabled.
To restart networking after the system resumes from sleep I created the file /lib/systemd/system/root-resume.service:
[Unit]
Description=Local system resume actions
After=suspend.target
[Service]
Type=oneshot
ExecStart=/bin/systemctl restart network-manager.service
[Install]
WantedBy=suspend.target
Then I activated the service with sudo systemctl enable root-resume.service. Enabling the service creates a symbolic link for the file in /etc/systemd/system/suspend.target.wants/
Contrary to man systemd-sleep service files placed in /lib/systemd/system-sleep/ are ignored.
A:
No, nor those in /usr/lib/pm-utils/sleep.d. But it runs all scripts (not service files) in /lib/systemd/system-sleep/ with executable bits set.
Here's an example one for calling pm-powersave, modified from /usr/lib/pm-utils/sleep.d/00powersave.
#!/bin/sh
# do not run pm-powersave on ARM during suspend; the 1.5 seconds that it takes
# to run it don't nearly compensate the potentially slightly slower suspend
# operation in low power mode
ARCH=`uname -m`
case $1 in
pre) [ "$ARCH" != "${ARCH#arm}" ] || pm-powersave false ;;
post) pm-powersave ;;
esac
exit 0
$1 is "post" on resume, "pre" otherwise.
$2 in both cases contains either "suspend", "hibernate", or "hybrid-sleep".
| {
"pile_set_name": "StackExchange"
} |
Q:
Java Finding String regex
I tried to get these date 22-APR-16 11.00.00.000000 and 22-APR-16 10.30.00.000000.
My codes are there but it cant find ,how can I do?
String pattern = "(Başlangıç Tarihi:\\s+)([0-9/:]+\\s+[0-9:]+)(.*)\\s+(Bitiş Tarihi:\\s+)([0-9/:]+\\s+[0-9:]+)(.*)";
Pattern r = Pattern.compile(pattern);
String text = "Başlangıç Tarihi: 22-APR-16 11.00.00.000000 AM Bitiş Tarihi: 22-APR-16 10.30.00.000000 PM";
Matcher m = r.matcher(text);
if(m.find())
{
String startDate = m.group(2);
String endDate = m.group(5);
System.out.println("Start Date : " + startDate);
System.out.println("End Date : " + endDate);
}
A:
KISS
String pattern = "(Başlangıç Tarihi:\\s+)(\\d+-[A-Za-z]+-\\d+\\s[\\d.]+)(.*)\\s+(Bitiş Tarihi:\\s+)(\\d+-[A-Za-z]+-\\d+\\s[\\d.]+)";
Ideone Demo
Moreover, you can just use
(\\d+-[A-Za-z]+-\\d+\\s[\\d.]+)
and find all the matches using loop and store it an array or arraylist. Every even element will be start date and odd element will be end date
| {
"pile_set_name": "StackExchange"
} |
Q:
Why the v-t and i-t curves for capacitor are exponential curve?
If we plot and compare v-t or I-t curves with actual exponential curve we can see that they are same, but why? Is there any proof?
From the equation we can see that e is creating bridge between electrical property and time. Why e?
I have a good text book that covers the curve’s characteristics and how it can be used but doesn’t show any mathematical proof.
A:
Capacitance is defined as:
\$C = \frac{Q}{V}\$
and equally:
\$C = \frac{\delta Q}{\delta V}\$
Since current is defined as the rate of change of charge:
\$I(t) = \frac{\delta Q(t)}{\delta t}\$
Thus:
\$I(t) = C \frac{\delta V(t)}{\delta t}\$
If we set up a circuit with a voltage source, Resistor and a capacitor
\$V = V_r + V_c\$ and this creates a differential equation
\$v = i(t)R + \frac{1}{C}\int i(t) \delta t \$
Solving such differential equations produces an equation:
\$I(t) = \frac{V}{R}e^\frac{-t}{RC}\$
Which equally can be re-arranged to be
\$V(t) = V(1-e^\frac{-t}{RC}) \$ taking into account initial conditions
| {
"pile_set_name": "StackExchange"
} |
Q:
Memory allocations in Julia
I'm extremely dissatisfied after translating a program from Python to Julia:
for small/very small inputs, Python is faster
for medium inputs, Julia is faster (but not that much)
for big inputs, Python is faster
I think the reason is that I don't understand how memory allocation works (autodidact here, no CS background). I would post my code here but it is too long and too specific and it would not be beneficial for anybody but me. Therefore I made some experiments and now I have some questions.
Consider this simple script.jl:
function main()
@time begin
a = [1,2,3]
end
end
main()
When I run it I get:
$ julia script.jl
0.000004 seconds (1 allocation: 96 bytes)
1. Why 96 bytes? When I set a = [] I get 64 bytes (why does an empty array weight so much?). 96 bytes - 64 bytes = 32 bytes. But a is an Array{Int64,1}. 3 * 64 bits = 3 * 8 bytes = 24 bytes != 32 bytes.
2. Why do I get 96 bytes even if I set a = [1,2,3,4]?
3. Why do I get 937.500 KB when I run this:
function main()
@time begin
for _ in 1:10000
a = [1,2,3]
end
end
end
main()
and not 960.000 KB?
4. Why is, for instance, filter() so inefficient? Take a look at this:
check(n::Int64) = n % 2 == 0
function main()
@time begin
for _ in 1:1000
a = [1,2,3]
b = []
for x in a
check(x) && push!(b,x)
end
a = b
end
end
end
main()
$ julia script.jl
0.000177 seconds (3.00 k allocations: 203.125 KB)
instead:
check(n::Int64) = n % 2 == 0
function main()
@time begin
for _ in 1:1000
a = [1,2,3]
a = filter(check,a)
end
end
end
main()
$ julia script.jl
0.002029 seconds (3.43 k allocations: 225.339 KB)
And if I use an anonymous function (x -> x % 2 == 0)instead of check inside filter, I get:
$ julia script.jl
0.004057 seconds (3.05 k allocations: 206.555 KB)
Why should I use a built-in function if it is slower and needs more memory?
A:
Quick answers:
1. Arrays keep track of their dimensionality and size, among other things, in a header.
2. Julia ensures its arrays are 16-byte aligned. The pattern becomes obvious if you look at the allocations for a few more examples:
julia> [@allocated(Array{Int64}(i)) for i=0:8]'
1x9 Array{Any,2}:
64 80 80 96 96 112 112 128 128
3. It's reporting in kilobytes. There are 1024 bytes in a kilobyte:
julia> 937.500 * 1024
960000.0
4. Anonymous functions and passing functions to higher order functions like filter are known performance gotchas in 0.4, and have been fixed in the latest development version.
In general, getting more allocations than you expect is often a sign of type-instability. I highly recommend reading through the manual's Performance Tips page for more information about this.
A:
It's hard to figure out why your code is slow without knowing anything about it, but if you're willing, you could post it to julia-users – lots of people there (myself included) are happy to help with some performance analysis and tweaking. Julia has a pretty simple performance model once you get the hang of it, but it does take a little time to get it. Once you do, it's generally possible to get C-like performance. Here are some answers to your specific questions.
Why 96 bytes? Why does an empty array weight so much?
Why do I get 96 bytes even if I set a = [1,2,3,4]?
In dynamic languages, arrays are runtime objects and metadata about them takes some space. You need to store the type tag of the object, the number and size of dimensions, and flags for memory management. This is pretty standard in dynamic languages – IIRC, in PHP each array has ~400 bytes of overhead, but a PHP "array" is really much more than that. Python and Ruby are probably pretty similar to Julia in terms of array object overhead.
Furthermore, 1-dimensional arrays in Julia are dynamically resizeable via push! and pop! and other similar operations, and are somewhat overallocated to make those operations more efficient. When you grow a vector by pushing elements to it individually, you periodically will need more memory. In order to make this efficient, Julia pre-allocates extra space. As a result, one-element and two-element arrays have the same storage size; so do three-element and four-element arrays. For even moderately large arrays, this overhead is negligible. If you need to store a lot of small arrays, of course, it could become a problem. There are various ways to work around this issue, but it doesn't seem to really be your problem.
Why do I get 937.500 KB
1 KB = 1024 bytes, so 937.5 KB * 1024 bytes/KB = 960000 bytes.
Why is, for instance, filter() so inefficient?
If you use the development version of Julia, this is efficient. This required a massive overhaul of how functions are implemented and how they interact with the type system, which was done by Jeff Bezanson. Here's the performance now:
julia> check(n) = n % 2 == 0
check (generic function with 1 method)
julia> function f1()
for _ in 1:1000
a = [1,2,3]
b = []
for x in a
check(x) && push!(b,x)
end
a = b
end
end
f1 (generic function with 1 method)
julia> function f2()
for _ in 1:1000
a = [1,2,3]
a = filter(x -> x % 2 == 0, a)
end
end
f2 (generic function with 1 method)
julia> @time f1() # compilation
0.013673 seconds (16.86 k allocations: 833.856 KB)
julia> @time f1()
0.000159 seconds (3.00 k allocations: 203.281 KB)
julia> @time f2() # compilation
0.012211 seconds (7.79 k allocations: 449.308 KB)
julia> @time f2()
0.000159 seconds (3.00 k allocations: 203.281 KB)
The performance is now indistinguishable. That is only available on a recent version of Julia master, not the 0.4 stable release, however, so if you're using a stable release, for maximal performance, you need to write out the filter operation yourself.
| {
"pile_set_name": "StackExchange"
} |
Q:
Кодирование массива категориальных признаков в машинном обучении
Есть один столбец категориальных признаков (они закодированы 1,2,3,4,5), этот столбец может принимать несколько значений через запятую, например
3,5.
Как преобразовать данный столбец по типу OneHotEncoder, только чтоб единицы проставлялись по значениям из массива, MultiHotEncoder (multiple hot encoder) ?
Как сделать это в python при помощи sklearn.
A:
Пример:
In [14]: df
Out[14]:
Col1 Col2 Col3
0 C 33.0 [Apple, Orange, Banana]
1 A 2.5 [Apple, Grape]
2 B 42.0 [Banana]
In [15]: from sklearn.preprocessing import MultiLabelBinarizer
In [16]: mlb = MultiLabelBinarizer()
In [17]: df = df.join(pd.DataFrame(mlb.fit_transform(df.pop('Col3')),
...: columns=mlb.classes_,
...: index=df.index))
In [18]: df
Out[18]:
Col1 Col2 Apple Banana Grape Orange
0 C 33.0 1 1 0 1
1 A 2.5 1 0 1 0
2 B 42.0 0 1 0 0
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change the behavior of Cmd + D in RubyMine editor
I'm using macOS Mojave & RubyMine 2019.1 .
When I select multiple lines and press Cmd + D, it duplicates only where is selected, not duplicating the whole lines selected.
See the images below.
The first image is before pressing Cmd + D . The second one is after pressing.
I expected it works like the third image.
I could not find any configurations to fix this.
Is it impossible to make it work like the third image?
A:
Use the Duplicate Entire Lines action instead:
| {
"pile_set_name": "StackExchange"
} |
Q:
Time taken by a stone to reach the ground is independent of point of dropping
A balloon is rising. A stone is dropped and the stone takes $\frac{2u}{g}$ to reach ground (Nothing is known about $u$ and $g$ is the acceleration due to gravity), irrespective if the point of dropping. Find the acceleration of the balloon as a function of time. How to do this question? I came across it somewhere on the internet and the hint was that it can be proved that $u$ is the initial velocity of the balloon. How? Also, apart from the mathematics, some insight on how such a condition can occur. Thanks
A:
Starting out with the general $$z := h + v~t - \frac {g}{2}~t^2,$$
where
$t \ge 0$ is the duration since the stone had been released,
$z[~t~]$ is the remaining "height above ground" of the stone,
$h$ is the "heigt above ground" of ballon and stone at the release, and
$v$ is the vertical speed of the ballon at the release.
Given $z[~\frac{2~u}{g}~] := 0$ it follows a relation between $h$ and $v$:
$$0 = h + \frac{2~u~v}{g} - \frac {g}{2}~\left(\frac{2~u}{g}\right)^2,$$
$$2~\frac{u^2}{g} = h + v~\frac{2~u}{g}.$$
Now, considering the motion of the ballon until the release, we also have $$v[~\tau~] := \frac{d}{d \tau}[~h[~\tau~]~],$$
where $\tau$ is the duration since the ballon had taken off the ground;
and consequently:
$$v[~\tau~] := \frac{d}{d \tau}[~h~] = u - h~\frac{g}{2~u},$$
$$\int ~d \tau = \int \frac{dh}{u - h~\frac{g}{2~u}},$$
$$\tau = \frac{2~u}{g}~\text{Ln}[~\frac{1}{1 - h[~\tau~]~\frac{g}{2~u^2} }~] + \text{const.}.$$
Requiring $h[~\tau = 0~] = 0$ leads to
$$\tau = \frac{2~u}{g}~\text{Ln}[~\frac{1}{1 - h[~\tau~]~\frac{g}{2~u^2} }~],$$
$$h[~\tau~] = \frac{2~u^2}{g}~(1 - \text{Exp}[~-\tau~\frac{g}{2~u}~])$$
and consequently
$$v[~\tau~] = u - h~\frac{g}{2~u} = u~\text{Exp}[~-\tau~\frac{g}{2~u}~].$$
Therefore also: $v[~\tau = 0~] = u$, as required.
Find the acceleration of the balloon as a function of [its duration since take-off]
Differentiating once more:
$$a[~\tau~] := \frac{d}{d \tau}[~v~] = \frac{d}{d \tau}[~u~\text{Exp}[~-\tau~\frac{g}{2~u}~]~] = \frac{g}{2}~\text{Exp}[~-\tau~\frac{g}{2~u}~].$$
| {
"pile_set_name": "StackExchange"
} |
Q:
target parameter in DispatchQueue
In Swift 3, the creation of a DispatchQueue instance:
DispatchQueue(label: String,
qos: DispatchQoS,
attributes: DispatchQueue.Attributes,
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency,
target: DispatchQueue?)
I see the sample codes from StackOverFlow, it can be nil, .global() or .main, what's the meaning of this target parameter?
I guess .main means the queue will run on main thread, but what for .nil or .global() ?
A:
There's no documentation for Swift so I dropped back to the old documentation for GCD. The closest that I've found is for the function dispatch_set_target_queue:
An object's target queue is responsible for processing the object. The target queue determines the queue on which the object's finalizer is invoked. In addition, modifying the target queue of some objects changes their behavior:
Dispatch queues:
A dispatch queue's priority is inherited from its target queue. Use the dispatch_get_global_queue function to obtain a suitable target queue of the desired priority.
If you submit a block to a serial queue, and the serial queue’s target queue is a different serial queue, that block is not invoked concurrently with blocks submitted to the target queue or to any other queue with that same target queue.
So looks like the target queue does 2 things:
Provide the priority for your new queue
Executes the finalizer (deinit) of all objects in your queue
Reading between the lines, there are some sychronization between your queue and the target queue. I don't have Xcode at the moment so I can't test.
A:
The target is explained by apple as:
"A dispatch queue's priority is inherited from its target queue. Use the dispatch_get_global_queue function to obtain a suitable target queue of the desired priority.
If you submit a block to a serial queue, and the serial queue’s target queue is a different serial queue, that block is not invoked concurrently with blocks submitted to the target queue or to any other queue with that same target queue."
https://developer.apple.com/reference/dispatch/1452989-dispatch_set_target_queue
1.
.main will run on the main thread. The main thread is used primarily for UI work so you should be cautious when using this thread for work that is not UI related because it could make the UI hang or appear unresponsive. This queue has the highest priority.
2.
.global is primarily used for other work that is not UI related. and schedules blocks when threads become available. the global queue has three priorities Low, Default & High. This queue has the second highest priority with 3 different types.
3.
nil is the lowest priority and will be lower than any global queue. it has no priority, it just needs to get done.
Summary
.main as target for UI work
.global as target for other work that needs to be done as soon as possible
nil as target for work that just needs to get done at some point (your not bothered when)
| {
"pile_set_name": "StackExchange"
} |
Q:
Pretty-print object hierarchy in Java?
I'm working on a data analytics project where we are representing a lot of the basic entities you find in a language. I'd like to find a better way to print out their object graphs though for debugging purposes though. So, for example, we might have:
Function: Average
Description: some description
Overload #1:
parameter-set: paramset-a
columns:
currency: string
value: double
scale: integer
result-set: result-set-a
preference: first-find
Overload #2: ...
Overload #3: ...
My Question
Let's say, in the above example, Function is my root object. Function has some attributes and a series of overloads, each with their own attributes and child objects.
Is there a library that can help me to print the object graph under a root function, in a well-formatted way?
PS: The above example is relatively trivial; in many of our cases, the object hierarchies are 6-10 levels deep, and that's when the real problem comes in.
A:
This is far from perfect, but this question really deserves an answer.
https://github.com/EsotericSoftware/jsonbeans is one way to kind of accomplish something like this. It converts arbitrary Java objects (without having to annotate the fields or anything) to JSON, and includes a pretty-printing method. It can do approximately what you are asking for.
Using this library, you can do something like this:
Json json = new Json();
System.out.println(json.prettyPrint(person));
For some example data, the output you might get looks like this:
{
"name": "Nate",
"age": 31,
"numbers": [
{
"name": "Home",
"class": "com.example.PhoneNumber",
"number": "206-555-1234"
},
{
"name": "Work",
"class": "com.example.PhoneNumber",
"number": "425-555-4321"
}
]
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I fix an error while updating packages cache?
When I try to update in Ubuntu 11.04 after installation, I get the following error
E: Some index files failed to download. They have been ignored, or old ones
used instead.
I tried the following command still the same error
sudo rm /var/lib/apt/lists/* -vf
sudo apt-get update
Please help me.
A:
Proxy problem. Permissions to download the package weren't there.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Populate jQuery Object with Data from Link Inside HTML List?
I have a list that looks like this:
<ul id="theLinks">
<li><a href="one.php">One</a></li>
<li><a href="two.php">Two</a></li>
<li><a href="three.php">Three</a></li>
<li><a href="four.php">Four</a></li>
</ul>
I would like to populate a jQuery Object with the data from that list so it looks like this:
var Links = {
'One' : 'one.php',
'Two' : 'two.php',
'Three' : 'three.php',
'Four' : 'four.php'
}
What is the best method for solving this problem?
Thanks in advance!
A:
var Links = {};
$('#theLinks li a').each(function(){
Links[this.innerHTML] = this.href.substring(this.href.lastIndexOf("/") + 1);
});
Fiddle link
Note: the links will not be in order because this is not an array.
Outputs:
Four: "four.php"
One: "one.php"
Three: "three.php"
Two: "two.php"
| {
"pile_set_name": "StackExchange"
} |
Q:
Microsoft SQL Server 2008 R2 Setup MOF compiler could not connect with the WMI server
I have installed visual studio 2010 on my Inspiron 1464 64 bit processor which has windows 7 professional installed. I tried to install sql server 2008 r2 express edition with tools version 10.50.1600.1 from microsoft. But i am unable to install it i have got the following error in the middle of the installed and it closed.
TITLE: Microsoft SQL Server 2008 R2 Setup
The following error has occurred:
The MOF compiler could not connect with the WMI server. This is either because of a semantic error such as an incompatibility with the existing WMI repository or an actual error such as the failure of the WMI server to start.
For help, click: http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=10.50.1600.1&EvtType=0xA60E3551%25400xD3BEBD98%25401211%25401
Here is the log file message of the above error.
Machine Properties:
Machine name: GHAFFAR-PC
Machine processor count: 4 OS version: Windows 7 OS service pack: OS region:
United States OS language: English (United States)
OS architecture: x64 Process architecture: 64
Bit OS clustered: No
Product features discovered: Product Instance
Instance ID Feature
Language Edition Version Clustered
Sql Server 2008 SQLEXPRESS MSSQL10.SQLEXPRESS
Database Engine Services 1033 Express
Edition 10.1.2531.0 No Sql Server 2008
SQLEXPRESS MSSQL10.SQLEXPRESS SQL Server
Replication 1033 Express Edition
10.1.2531.0 No
Package properties: Description: SQL Server
Database Services 2008 R2 ProductName: SQL Server
2008 R2 Type: RTM Version:
10 SPLevel: 0 Installation location:
d:\d2a7ae0724758063e2a9b4\x64\setup\ Installation edition:
EXPRESS_ADVANCED
User Input Settings: ACTION: Install
ADDCURRENTUSERASSQLADMIN: True AGTSVCACCOUNT:
NT AUTHORITY\NETWORK SERVICE AGTSVCPASSWORD: *
AGTSVCSTARTUPTYPE: Disabled ASBACKUPDIR:
Backup ASCOLLATION: Latin1_General_CI_AS
ASCONFIGDIR: Config ASDATADIR:
Data ASDOMAINGROUP: ASLOGDIR:
Log ASPROVIDERMSOLAP: 1 ASSVCACCOUNT:
ASSVCPASSWORD: ASSVCSTARTUPTYPE:
Automatic ASSYSADMINACCOUNTS: ASTEMPDIR:
Temp BROWSERSVCSTARTUPTYPE: Disabled CONFIGURATIONFILE:
CUSOURCE: ENABLERANU: True
ENU: True ERRORREPORTING:
False FARMACCOUNT: FARMADMINPORT:
0 FARMPASSWORD: FEATURES:
SQLENGINE,SSMS,SNAC_SDK FILESTREAMLEVEL: 0
FILESTREAMSHARENAME: FTSVCACCOUNT:
FTSVCPASSWORD: HELP:
False IACCEPTSQLSERVERLICENSETERMS: False INDICATEPROGRESS:
False INSTALLSHAREDDIR: C:\Program Files\Microsoft SQL
Server\ INSTALLSHAREDWOWDIR: C:\Program Files
(x86)\Microsoft SQL Server\ INSTALLSQLDATADIR:
INSTANCEDIR: D:\Program Files\Microsoft SQL Server\
INSTANCEID: MSSQLSERVER INSTANCENAME:
MSSQLSERVER ISSVCACCOUNT: NT
AUTHORITY\NetworkService ISSVCPASSWORD:
ISSVCSTARTUPTYPE: Automatic NPENABLED:
0 PASSPHRASE: PCUSOURCE:
PID: QUIET:
False QUIETSIMPLE: False ROLE:
AllFeatures_WithDefaults RSINSTALLMODE:
FilesOnlyMode RSSVCACCOUNT: NT AUTHORITY\NETWORK
SERVICE RSSVCPASSWORD: RSSVCSTARTUPTYPE:
Automatic SAPWD: SECURITYMODE:
SQLBACKUPDIR: SQLCOLLATION:
SQL_Latin1_General_CP1_CI_AS SQLSVCACCOUNT: NT
AUTHORITY\NETWORK SERVICE SQLSVCPASSWORD: *
SQLSVCSTARTUPTYPE: Automatic SQLSYSADMINACCOUNTS:
Ghaffar-PC\Ghaffar SQLTEMPDBDIR:
SQLTEMPDBLOGDIR: SQLUSERDBDIR:
SQLUSERDBLOGDIR: SQMREPORTING:
False TCPENABLED: 0 UIMODE:
AutoAdvance X86: False
Configuration file: C:\Program Files\Microsoft SQL
Server\100\Setup Bootstrap\Log\20111222_105332\ConfigurationFile.ini
Detailed results: Feature: Database Engine
Services Status: Failed: see logs for details
MSI status: Passed Configuration status:
Failed: see details below Configuration error code:
0xD3BEBD98@1211@1 Configuration error description: The MOF compiler
could not connect with the WMI server. This is either because of a
semantic error such as an incompatibility with the existing WMI
repository or an actual error such as the failure of the WMI server to
start.
Feature: SQL Client Connectivity SDK Status: Passed MSI status:
Passed Configuration status: Passed
Feature: Management Tools - Basic Status:
Failed: see logs for details MSI status: Passed
Configuration status: Failed: see details below
Configuration error code: 0xD3BEBD98@1211@1 Configuration error
description: The MOF compiler could not connect with the WMI server.
This is either because of a semantic error such as an incompatibility
with the existing WMI repository or an actual error such as the
failure of the WMI server to start. Rules with failures: Global
rules: Scenario specific rules:
Rules report file: C:\Program Files\Microsoft SQL
Server\100\Setup
Bootstrap\Log\20111222_105332\SystemConfigurationCheck_Report.htm
I went to the above link for sorting out the error but nothing their. Can any buddy tell me how actually it would be cured?
Best regards,
Ghaffar
A:
I faced same problem while installing MS SQL Server 2017 Enterprise.
I've used Windows Installer CleanUp Utility (Microsoft product) to remove everything associated with SQL server. This tool listed tone of components and apps from SQL Server which I didn't see in Control Panel - Uninstall Software option.
I could select all SQL programs and start uninstall procedure for all of them. This tool is really effective.
I was able to install MS SQL Server 2017 Enterprise successfully after that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Returning the timestamp field in elasticsearch
Why can I not see the _timestamp field while being able to filter a query by it?
The following query return the correct documents, but not the timestamp itself. How can I return the timestamp?
{
"fields": [
"_timestamp",
"_source"
],
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"range": {
"_timestamp": {
"from": "2013-01-01"
}
}
}
}
}
}
The mapping is:
{
"my_doctype": {
"_timestamp": {
"enabled": "true"
},
"properties": {
"cards": {
"type": "integer"
}
}
}
}
sample output:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [ {
"_index" : "test1",
"_type" : "doctype1",
"_id" : "HjfryYQEQL6RkEX3VOiBHQ",
"_score" : 1.0, "_source" : {"cards": "5"}
}, {
"_index" : "test1",
"_type" : "doctype1",
"_id" : "sDyHcT1BTMatjmUS0NSoEg",
"_score" : 1.0, "_source" : {"cards": "2"}
}]
}
A:
When timestamp field is enabled, it's indexed but not stored by default. So, while you can search and filter by the timestamp field, you cannot easily retrieve it with your records. In order to be able to retrieve the timestamp field you need to recreate your index with the following mapping:
{
"my_doctype": {
"_timestamp": {
"enabled": "true",
"store": "yes"
},
"properties": {
...
}
}
}
This way you will be able to retrieve timestamp as the number of milliseconds since the epoch.
A:
It is not necessary to store the timestamp field, since its exact value is preserved as a term, which is also more likely to already be present in RAM, especially if you are querying on it. You can access the timestamp via its term using a script_value:
{
"query": {
...
},
"script_fields": {
"timestamp": {
"script": "_doc['_timestamp'].value"
}
}
}
The resulting value is expressed in miliseconds since UNIX epoch. It's quite obscene that ElasticSearch can't do this for you, but hey, nothing's perfect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Linux Command not working using java if it contains special symbol
I am trying to run the below code but it is not working, can someone help me understand why it is behaving like this or am i missing something?
import java.io.IOException;
public class SimpleClass {
public static void main(String args[]){
try {
Process process = Runtime.getRuntime().exec("bash mkdir demoDir");
// Process process2 = Runtime.getRuntime().exec("echo sometext >> someFile.txt");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
If i execute the first process it is working fine but if i execute process2 it is not working. someFile.txt is present and the present working directory, apart from this command if i try to make directory like mkdir /home/dummy/demoDir then also it is not working but my program gets executed successfully.
A:
The answer to this question was already discussed here. Use
String[] cmd = {"bash", "-c", "echo sometext >> someFile.txt" };
Process process2 = Runtime.getRuntime().exec(cmd);
instead. Works for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Question about a polynomial's degree
How can we show that if $p(x)$ is a polynomial of degree $d-1$, then
$$\sum_{k=n_0}^n p(k)$$
is a polynomial in $n$ of degree $d$?
A:
It suffices to prove that $\sum_{k=0}^{n}{p(k)}$ is a polynomial in $n$ of degree $d$, since $\sum_{k=n_0}^{n}{p(k)}$ differs from $\sum_{k=0}^{n}{p(k)}$ by a constant.
Note that $$\sum_{k=0}^{n}{\binom{k}{d}}=\binom{n+1}{d+1}$$
This can be proven by induction on $n$, or by double counting the number of ways to choose $d+1$ numbers from $\{0, 1, \ldots, n \}$.
Now we induct on $d$:
The base case $d=1$ is clearly true. Suppose that the statement holds for $d=i$, then for a polynomial $p(x)$ with degree $(i+1)-1=i$, we may write $p(x)=a\binom{x}{i}+q(x)$ where $a$ is $i!$ multiplied by the leading coefficient of $p(x)$, and $q(x)$ is a polynomial with degree $i-1$. Then
$$\sum_{k=0}^{n}{p(k)}=\sum_{k=0}^{n}{a\binom{k}{i}}+\sum_{k=0}^{n}{q(k)}=a\binom{n+1}{i+1}+\sum_{k=0}^{n}{q(k)}$$
Note that $a\binom{n+1}{i+1}$ is a polynomial in $n$ of degree $i+1$, and by the induction hypothesis $\sum_{k=0}^{n}{q(k)}$ is a polynomial in $n$ of degree $i$.
Therefore $\sum_{k=0}^{n}{p(k)}$ is indeed a polynomial in $n$ of degree $i+1$, and we are done by induction.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get all documents from ElasticSearch using elasticsearchTemplate
I have many documents on my elasticsearch. I am using elasticsearchTemplate.queryForList(SearchQuery, class) to get the documents depending on my query. This query always return 10 documents. Does elasticsearch provide any api where all the documents that match the query will be returned?
A:
You need to add Page Request in your searchQuery.
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withPageable(new PageRequest(0, repository.count() as int))
SearchQuery query = builder.build()
Repository.count() will give the count of documents in your index.
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bash: How to select elements in array
I have an array with subdirs and files:
~$ array=(elem1/a elem1/b elem2/a elem2/b)
I need to select all files (with its subdir) inside subdir elem1.
I've tried with a for loop and case:
for element in "${array[@]}"; do
case $element in
elem1*)
# action I need to perform on this element
echo "This is $element"
;;
esac
done
I'd like to get the list of elements I need using some glob, in a similar way as this (which substracts substrings from array elements):
~$ echo ${array[@]%/a}
elem1 elem1/b elem2 elem2/b
My main concern is that I shoudn't hardcode what strings I'm searching for, as I don't know its contents - in my final version of this script I'm getting them from another array.
A:
My answer prints every element of the array in a different line, then filters the ones you are interested (grep) and put them into a new array
newarray=( $(printf "%s\n" "${array[@]}" | grep ^elem/) )
The only problem would be if the elements of your array (subdirs and file namews) might contain EOL or blank chars.
Bonus
If your elements contain EOL or blank chars, you should use the NUL (\000) char and grep -zZ to handle it; but then you need more code to turn out those NUL-char strings into something which the bash can work with -- the bash stops reading when it finds a NUL char.
In this example I use awk, which has no problem to handle NUL chars, and makes unnecessary the use of grep:
eval newarray=( $(printf "%s\000" "${A[@]}" |
awk 'BEGIN { FS="\000" }
/^elem\// {
gsub("\042","\\\042")
printf("[" NR-1 "]=\042%s\042 ",$0)
}'
)
)
| {
"pile_set_name": "StackExchange"
} |
Q:
'Expected end_of_string but found colon' error when chaining where filters
I've just tried to bump my Jekyll version from 3.4.3 to 3.8.5 and when I run the build, I'm getting this error:
Liquid Warning: Liquid syntax error (line 37): Expected end_of_string but found colon in "{{site.documents | where: "belongs_to_group", page.group | where: "lang": lang | sort: "page.date" | reverse }}"
What has changed in chaining where filters? I cannot seem to find anything in the docs.
When I only include one where filter, the variable gets properly assigned.
{% assign boxes = site.documents | where: "belongs_to_group", page.group %}
As soon as I add another one, I get the said error.
Here a full example on how I was able to assign the veraiable in a previous Jekyll version.
{% assign boxes = site.documents | where: "belongs_to_group", page.group | where: "lang": lang | where_exp: "item", "item.start_datetime > site.time" | sort: "start_datetime" %}
How can I still add those filters in the new Jekyll version?
A:
It looks like the issue here might be in this snippet:
where: "lang": lang
The key and value should be separated by a comma (Jekyll docs).
where: "lang", lang
Your other where clause is formatted correctly, which is why it isn't throwing an error when you include only that one.
| {
"pile_set_name": "StackExchange"
} |
Q:
MediaPlayer.createVolumeShaper throws an IllegalArgumentException: invalid configuration or operation: -19
When using the new VolumeShaper in Android O, I am attempting to create it with a MediaPlayer:
// Create a VolumeShaper configuration
VolumeShaper.Configuration volumeShaperConfig =
new VolumeShaper.Configuration.Builder()
.setDuration(3000)
.setCurve(new float[] {0.f, 1.f}, new float[] {0.f, 1.f})
.setInterpolatorType(VolumeShaper.Configuration.INTERPOLATOR_TYPE_LINEAR)
.build();
mVolumeShaper = mMediaPlayer.createVolumeShaper(configuration);
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepareAsync();
When I try to run it, however, it throws an exception:
Caused by: java.lang.IllegalArgumentException: invalid configuration or operation: -19
at android.media.VolumeShaper.applyPlayer(VolumeShaper.java:189)
at android.media.VolumeShaper.<init>(VolumeShaper.java:54)
at android.media.MediaPlayer.createVolumeShaper(MediaPlayer.java:1392)
A:
In order to create a VolumeShaper, the MediaPlayer object has to be in the "Initialized" state, which happens after calling setDataSource on it. (See: MediaPlayer state diagram.)
In this case it's as simple as changing the code to do it in this order:
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepareAsync();
mVolumeShaper = mMediaPlayer.createVolumeShaper(configuration);
It's also possible to delay the creation of VolumeShaper until calling .start() on the MediaPlayer, and it's worth noting that, with the configuration above, the volume will start off muted, so you'll need to apply the VolumeShaper when starting to play or the output will be silent.
To do this, just use this:
public void play() {
mMediaPlayer.start();
mVolumeShaper.apply(VolumeShaper.Operation.PLAY);
}
To mute it, before pausing or as the track is ending, just apply it in reverse, like this:
public void setMuted(boolean muted) {
if (muted) {
mVolumeShaper.apply(VolumeShaper.Operation.REVERSE);
} else {
mVolumeShaper.apply(VolumeShaper.Operation.PLAY);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to merge multiple variables and create a new data set?
https://www.kaggle.com/nowke9/ipldata ----- Contains the IPL Data.
This is exploratory study performed for the IPL data set. (link for the data attached above) After merging both the files with "id" and "match_id", I have created four more variables namely total_extras, total_runs_scored, total_fours_hit and total_sixes_hit. Now I wish to combine these newly created variables into one single data frame. When I assign these variables into one single variable namely batsman_aggregate and selecting only the required columns, I am getting an error message.
library(tidyverse)
deliveries_tbl <- read.csv("deliveries_edit.csv")
matches_tbl <- read.csv("matches.csv")
combined_matches_deliveries_tbl <- deliveries_tbl %>%
left_join(matches_tbl, by = c("match_id" = "id"))
# Add team score and team extra columns for each match, each inning.
total_score_extras_combined <- combined_matches_deliveries_tbl%>%
group_by(id, inning, date, batting_team, bowling_team, winner)%>%
mutate(total_score = sum(total_runs, na.rm = TRUE))%>%
mutate(total_extras = sum(extra_runs, na.rm = TRUE))%>%
group_by(total_score, total_extras, id, inning, date, batting_team, bowling_team, winner)%>%
select(id, inning, total_score, total_extras, date, batting_team, bowling_team, winner)%>%
distinct(total_score, total_extras)%>%
glimpse()%>%
ungroup()
# Batsman Aggregate (Runs Balls, fours, six , Sr)
# Batsman score in each match
batsman_score_in_a_match <- combined_matches_deliveries_tbl %>%
group_by(id, inning, batting_team, batsman)%>%
mutate(total_batsman_runs = sum(batsman_runs, na.rm = TRUE))%>%
distinct(total_batsman_runs)%>%
glimpse()%>%
ungroup()
# Number of deliveries played .
balls_faced <- combined_matches_deliveries_tbl %>%
filter(wide_runs == 0)%>%
group_by(id, inning, batsman)%>%
summarise(deliveries_played = n())%>%
ungroup()
# Number of 4 and 6s by a batsman in each match.
fours_hit <- combined_matches_deliveries_tbl %>%
filter(batsman_runs == 4)%>%
group_by(id, inning, batsman)%>%
summarise(fours_hit = n())%>%
glimpse()%>%
ungroup()
sixes_hit <- combined_matches_deliveries_tbl %>%
filter(batsman_runs == 6)%>%
group_by(id, inning, batsman)%>%
summarise(sixes_hit = n())%>%
glimpse()%>%
ungroup()
batsman_aggregate <- c(batsman_score_in_a_match, balls_faced, fours_hit, sixes_hit)%>%
select(id, inning, batsman, total_batsman_runs, deliveries_played, fours_hit, sixes_hit)
The error message is displayed as:-
Error: `select()` doesn't handle lists.
The required output is the data set created newly constructed variables.
A:
You'll have to join those four tables, not combine using c.
And the join type is left_join so that all batsman are included in the output. Those who didn't face any balls or hit any boundaries will have NA, but you can easily replace these with 0.
I've ignored the by since dplyr will assume you want c("id", "inning", "batsman"), the only 3 common columns in all four data sets.
batsman_aggregate <- left_join(batsman_score_in_a_match, balls_faced) %>%
left_join(fours_hit) %>%
left_join(sixes_hit) %>%
select(id, inning, batsman, total_batsman_runs, deliveries_played, fours_hit, sixes_hit) %>%
replace(is.na(.), 0)
# A tibble: 11,335 x 7
id inning batsman total_batsman_runs deliveries_played fours_hit sixes_hit
<int> <int> <fct> <int> <dbl> <dbl> <dbl>
1 1 1 DA Warner 14 8 2 1
2 1 1 S Dhawan 40 31 5 0
3 1 1 MC Henriques 52 37 3 2
4 1 1 Yuvraj Singh 62 27 7 3
5 1 1 DJ Hooda 16 12 0 1
6 1 1 BCJ Cutting 16 6 0 2
7 1 2 CH Gayle 32 21 2 3
8 1 2 Mandeep Singh 24 16 5 0
9 1 2 TM Head 30 22 3 0
10 1 2 KM Jadhav 31 16 4 1
# ... with 11,325 more rows
There are also 2 batsmen who didn't face any delivery:
batsman_aggregate %>% filter(deliveries_played==0)
# A tibble: 2 x 7
id inning batsman total_batsman_runs deliveries_played fours_hit sixes_hit
<int> <int> <fct> <int> <dbl> <dbl> <dbl>
1 482 2 MK Pandey 0 0 0 0
2 7907 1 MJ McClenaghan 2 0 0 0
One of which apparently scored 2 runs! So I think the batsman_runs column has some errors. The game is here and clearly says that on the second last delivery of the first innings, 2 wides were scored, not runs to the batsman.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.