text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Vagrant public network not reachable?
I'm trying to using vagrant for a distributed project on my Home Network. This is the Vagrantfile that I'm using on each host (3 machines in total):
# -*- mode: ruby -*-
# # vi: set ft=ruby :
# Specify minimum Vagrant version and Vagrant API version
Vagrant.require_version ">= 1.6.0"
VAGRANTFILE_API_VERSION = "2"
# Require YAML module
require 'yaml'
# Read YAML file with box details
servers = YAML.load_file('RaftFS/servers.yaml')
# Create boxes
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Create servers
# Iterate through entries in YAML file
servers.each do |key,value|
#the line below will be different on each machine
if key == "hal9000"
config.vm.define key do |srv|
srv.vm.box = value['box']
#srv.vm.network "private_network", ip: value['ip']
srv.vm.network :public_network, ip:value['ip']
srv.vm.hostname=key
srv.vm.synced_folder ".", "/vagrant" , disabled:true
srv.vm.synced_folder "ServersFS/"+key+"/", "/vagrant/ServersFS" , create: true
srv.vm.synced_folder "./RaftFS", "/vagrant/RaftFS"
srv.vm.provision :shell do |shell|
shell.path = "provision.sh"
shell.args = "'TRUE'"
end
srv.vm.provider :virtualbox do |vb|
vb.name = key
vb.memory = value['ram']
end
end
end
end
end
And this is the servers.yaml:
jarvis:
box: hashicorp/precise32
ram: 512
ip: 192.168.1.200
ftpPort: 8080
diskSpace: 500
skynet:
box: hashicorp/precise32
ram: 512
ip: 192.168.1.201
ftpPort: 8081
diskSpace: 500
hal9000:
box: hashicorp/precise32
ram: 512
ip: 192.168.1.202
ftpPort: 8083
diskSpace: 500
Now, if I ssh each machine and run ifconfig the IP is set correctly. The problem is that if I try contact it in any way it semms to be unreachable, even from the same host machine! In other words, trying to ping the IP address from the shell of the host machine, no response comes from the guest machine.
A:
It looks like you're only setting the hal9000 VM to use a public (or bridged) network (or in fact do any configuration) so the other guests are just using the default host only network which should mean that they only have connection to the host machine and not to each other.
If you take out the:
if key == "hal9000"
line then it should configure things properly.
However, unless you genuinely want the machines to be web facing these VMs should all be in a private network which should work by uncommenting the private networking line you already have there.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i remove a specified field from all documents of a collection using mongoose?
I want to remove key "passwrod" from all documents from users collection using mongoose , is it possible to do it using $unset ?
{ "_id" : ObjectId("58ec890c91b2b612084fd827"),
"username" : "zain",
"passwrod" : 123,
"password" : 8 },
{ "_id" : ObjectId("58ec8918364116187845948d"),
"username" : "bob",
"password" : 123,
"passwrod" : 12 }
A:
Documents:
{ "_id" : ObjectId("58ec890c91b2b612084fd827"), "username" : "zain", "passwrod" : 123, "password" : 8 }
{ "_id" : ObjectId("58ec8918364116187845948d"), "username" : "bob", "password" : 123, "passwrod" : 12 }
Query:
db.collection.updateMany({}, {$unset:{"passwrod":1}})
Result:
{ "_id" : ObjectId("58ec890c91b2b612084fd827"), "username" : "zain", "password" : 8 }
{ "_id" : ObjectId("58ec8918364116187845948d"), "username" : "bob", "password" : 123 }
| {
"pile_set_name": "StackExchange"
} |
Q:
Watch elements count by class using jQuery
I have simple HTML:
ul > li > button
And have some JavaScript code:
$('.side-filters .filters_list li').each(function(){
$(this).find('button').click(function(){
var arrList = $('.side-filters .filters_list li .active').map(function(){
return $(this).attr('id');
}).get();
if($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
});
If I click on a button, add class 'active' to the button, and if clicked again, remove class.
I need live count elements witn class 'active'. If there is at least one given ul class 'someclass' and if I click again and have no elements with class active, remove 'someclass' from the Ul.
How can I do this?
A:
There is no need to loop through the elements and add a click to every button. Add one listener.
//listen for click on a button
$('.side-filters', "click", ".filters_list li button", function(){
//toggle the active class on the button
var button = $(this).toggleClass("active");
//see if anything is selected
var hasSelection = $('.side-filters .filters_list li .active').length > 0;
//toggle a class on the closest ul based on if anything is selected.
button.closest("ul").toggleClass("someclass", hasSelection);
});
References:
toggleClass(class [, switch])
.closest( selector )
| {
"pile_set_name": "StackExchange"
} |
Q:
One time db scrub with .install file
I need to scrub a production db to replace paths in the body field. Being a production database, it needs to happen in a time-sensitive, well-documented way with the solution frozen in code. I'd assume that a .install file would be the best way to do this.
What would a one time install script look like to search the database for "http://mysite.com" and replace with "https://www.mysite.com" in the default body field?
A:
I typically do things like this outside of modules, and instead use a drush script.
The script itself, would go something like
Go into maintenance mode
Do an EntityFieldQuery to get my nids.
Loop through each nid, and
Load the node, and make an entity metadata wrapper
Do the search and replace on the fields
Save the node
Exit maintenance mode
Before and after running the script, I usually do a drush sql-dump. You can even combine all of this into a single script
#!/bin/bash
drush variable-set -y --always-set maintenance_mode 1
drush sql-dump --result-file=~/db/before.sql
drush scr path/to/my/script.php
drush sql-dump --result-file=~/db/after.sql
drush variable-delete -y --exact maintenance_mode
By doing a drush script, you can really ensure that the task runs when you want it to, and you aren't bound by execution time limits. I also find it easier to debug.
That said, you should just be able to use Pathologic to rewrite the URLs. Install/enable it, and add it to your text formats, and configure to do the path fixups.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wizard - What is the Purpose of Teleport?
I remember Diablo 2 where we could teleport without cooldown to travel the map very fast, but now with that high cooldown of Teleport, in what situation would I ever use this skill ?
A:
The Diablo 3 incarnation of teleport is geared towards tactical movement, not rapid transit.
Given how squishy the wizard can be on higher difficulties, I find teleport valuable for:
Teleporting out of a Waller's walls.
Escaping after being vortexed by a Vortex or jailed by a Jailer
Dodging Boss spells (Belial's Fists / Diablo's cages / Butcher's fire)
The point is, stop trying to use it as simple movement, and start thinking about it as a defensive cooldown (especially with runes like Safe Passage and Shatter).
A:
You could use Teleport in various ways in Diablo 3:
Teleporting across the map.
By using a Wormhole rune, you could teleport across the map at least 2 times consecutively.
Running away from mobs when on low Health.
This is a good tactic to evade monsters that are going to kill you, or at least sometimes get out of their way due to their damage spikes. Like boss fights, for example.
Positioning yourself for your team quicker.
Good positioning always works for an effective dps role. Usually on the easier difficulties its not usually used, but if you want to get in on the action faster or execute a strategy quicker, teleport works.
Kiting a boss monster.
Sometimes some boss monsters walk faster than you do. (Not just the ones with "Fast" on them) To kite them or at least draw away the aggro from you and onto your teammates, you could always use teleport to kite and disengage from a fight.
Lots of other uses
Teleport isnt always just Teleport. Runes make teleport into a whole new array of combos that you could use with skills. Try it out, mix and match and see if it works.
| {
"pile_set_name": "StackExchange"
} |
Q:
Common uses for the Tag property
I've started using this alot to link elements of my UI to their data backing class (whatever that might be). What are some of the common uses you put the Tag property to use for?
Indeed, do you use it at all? I know I didn't for a very long time.
A:
Just as you describe, the most frequent use of the Tag property I have come across and use in both WinForms, WPF and Silverlight is to indicate the real data that the control relates to. This is especially useful on ListViewItem instances or auto-generated user interface where you want to use the same event handler for multiple objects where only the target data is different (i.e. the action to be performed remains the same).
However, I have also used the Tag to store an enumeration value (though you should avoid value types as it would cause boxing when assigning the value to the Tag property) or a string that is then used to determine the action that needs to be performed instead of the data on which to perform it, and in one particular usage, I stored a delegate so that I could auto-generate some buttons and embed their handlers in the Tag (the handler information was supplied in a data driven manner).
I am sure there are many other ways to use Tag and many other ways to replace the uses of Tag with something more strongly typed, but that's how I've used it.
A:
The Tag property is an ancient (in programming language terms) hold over for controls. To my knowledge, it's been used in everything from visual basic, delphi, and pretty much any other gui based language.
It is simply an extra property that allows you to add a numeric value for any reason you want to the control.
I've seen it used for everything from a counter to holding a record id that the control is tied to.
A:
It is a bit of a kludge. It is often used in for instance a TreeView to link a Node to a data element.
But I would not over-use it, since it is very public and not very flexible. Note that you can almost always use a Dictionary< Control, ValueType> instead, and have a lot more control that way.
| {
"pile_set_name": "StackExchange"
} |
Q:
pandas.io.ga not working for me
So I have worked through the Hello Analytics tutorial to confirm that OAuth2 is working as expected for me, but I'm not having any luck with the pandas.io.ga module. In particular, I am stuck with this error:
In [1]: from pandas.io import ga
In [2]: df = ga.read_ga("pageviews", "pagePath", "2014-07-08")
/usr/local/lib/python2.7/dist-packages/pandas/core/index.py:1162: FutureWarning: using '-' to provide set differences
with Indexes is deprecated, use .difference()
"use .difference()",FutureWarning)
/usr/local/lib/python2.7/dist-packages/pandas/core/index.py:1147: FutureWarning: using '+' to provide set union with
Indexes is deprecated, use '|' or .union()
"use '|' or .union()",FutureWarning)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-b5343faf9ae6> in <module>()
----> 1 df = ga.read_ga("pageviews", "pagePath", "2014-07-08")
/usr/local/lib/python2.7/dist-packages/pandas/io/ga.pyc in read_ga(metrics, dimensions, start_date, **kwargs)
105 reader = GAnalytics(**reader_kwds)
106 return reader.get_data(metrics=metrics, start_date=start_date,
--> 107 dimensions=dimensions, **kwargs)
108
109
/usr/local/lib/python2.7/dist-packages/pandas/io/ga.pyc in get_data(self, metrics, start_date, end_date, dimensions,
segment, filters, start_index, max_results, index_col, parse_dates, keep_date_col, date_parser, na_values, converters,
sort, dayfirst, account_name, account_id, property_name, property_id, profile_name, profile_id, chunksize)
293
294 if chunksize is None:
--> 295 return _read(start_index, max_results)
296
297 def iterator():
/usr/local/lib/python2.7/dist-packages/pandas/io/ga.pyc in _read(start, result_size)
287 dayfirst=dayfirst,
288 na_values=na_values,
--> 289 converters=converters, sort=sort)
290 except HttpError as inst:
291 raise ValueError('Google API error %s: %s' % (inst.resp.status,
/usr/local/lib/python2.7/dist-packages/pandas/io/ga.pyc in _parse_data(self, rows, col_info, index_col, parse_dates,
keep_date_col, date_parser, dayfirst, na_values, converters, sort)
313 keep_date_col=keep_date_col,
314 converters=converters,
--> 315 header=None, names=col_names))
316
317 if isinstance(sort, bool) and sort:
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _read(filepath_or_buffer, kwds)
237
238 # Create the parser.
--> 239 parser = TextFileReader(filepath_or_buffer, **kwds)
240
241 if (nrows is not None) and (chunksize is not None):
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in __init__(self, f, engine, **kwds)
551 self.options['has_index_names'] = kwds['has_index_names']
552
--> 553 self._make_engine(self.engine)
554
555 def _get_options_with_defaults(self, engine):
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _make_engine(self, engine)
694 elif engine == 'python-fwf':
695 klass = FixedWidthFieldParser
--> 696 self._engine = klass(self.f, **self.options)
697
698 def _failover_to_python(self):
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in __init__(self, f, **kwds)
1412 if not self._has_complex_date_col:
1413 (index_names,
-> 1414 self.orig_names, self.columns) = self._get_index_name(self.columns)
1415 self._name_processed = True
1416 if self.index_names is None:
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _get_index_name(self, columns)
1886 # Case 2
1887 (index_name, columns_,
-> 1888 self.index_col) = _clean_index_names(columns, self.index_col)
1889
1890 return index_name, orig_names, columns
/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _clean_index_names(columns, index_col)
2171 break
2172 else:
-> 2173 name = cp_cols[c]
2174 columns.remove(name)
2175 index_names.append(name)
TypeError: list indices must be integers, not Index
OAuth2 is working as expected and I have only used these parameters as demo variables--the query itself is junk. Basically, I cannot figure out where the error is coming from, and would appreciate any pointers that one may have.
Thanks!
SOLUTION (SORT OF)
Not sure if this has to do with the data I'm trying to access or what, but the offending Index type error I'm getting arises from the the index_col variable in pandas.io.ga.GDataReader.get_data() is of type pandas.core.index.Index. This is fed to pandas.io.parsers._read() in _parse_data() which falls over. I don't understand this, but it is the breaking point for me.
As a fix--if anyone else is having this problem--I have edited line 270 of ga.py to:
index_col = _clean_index(list(dimensions), parse_dates).tolist()
and everything is now smooth as butter, but I suspect this may break things in other situations...
A:
Unfortunately, this module isn't really documented and the errors aren't always meaningful. Include your account_name, property_name and profile_name (profile_name is the View in the online version). Then include some dimensions and metrics you are interested in. Also make sure that the client_secrets.json is in the pandas.io directory. An example:
ga.read_ga(account_name=account_name,
property_name=property_name,
profile_name=profile_name,
dimensions=['date', 'hour', 'minute'],
metrics=['pageviews'],
start_date=start_date,
end_date=end_date,
index_col=0,
parse_dates={'datetime': ['date', 'hour', 'minute']},
date_parser=lambda x: datetime.strptime(x, '%Y%m%d %H %M'),
max_results=max_results)
Also have a look at my recent step by step blog post about GA with pandas.
| {
"pile_set_name": "StackExchange"
} |
Q:
JFrame size decreasing
I need your help in java 1.4.
How can I prohibit JFrame decreasing.
In java 5 or 6 I just:
new JFrame("TEST").setMinimumSize(...);
But how in java 1.4? That code does not work!
A:
This used to be a bug which was fixed in mustang. Take a look at the bug details for possible workarounds that you can try in 1.4.
| {
"pile_set_name": "StackExchange"
} |
Q:
IUP strange tab close behavior
I am trying to create a simple text editor with IUP using IupTabs and IupScintilla. However, when running on Linux, I am encountering a strange tab-closing behavior that I cannot seem to resolve.
When there are multiple tabs present, and the first is removed (either with the SHOWCLOSE button or via my callback close_cb, the single remaining tab is left blank. I have tried all combinations of IupUpdate, IupRedraw, IupRefresh, and IupRefreshChildren and nothing seems to force the tab to be drawn correctly.
I even dove into the IUP source and located the gtkTabsCloseButtonClicked function in iupgtk_tabs.c (line 307) to verify that the tab is being removed with the following code, so that my callback close_cb is at least performing the same action.
if (ret == IUP_CONTINUE) /* destroy tab and children */
{
IupDestroy(child);
IupRefreshChildren(ih);
}
I have distilled the problem down to the sample code below. I am running this on Lubuntu 12.04 x86-64. IUP version is iup-3.16_Linux32_64_lib, downloaded from Sourceforge. The problem only occurs on GTK and not Windows. I am not sure if this is a bug or if I am just doing something wrong. If it is a bug, I am not sure if it is related to GTK or IUP.
#include <iup.h>
#include <iup_scintilla.h>
#include <stdlib.h>
int new_cb( Ihandle* self )
{
// create a new Scintilla control
Ihandle* sci = IupScintilla();
IupSetAttributes( sci, "TABSIZE=4, EXPAND=YES, VISIBLE=YES, "
"TABTITLE=Untitled, TABIMAGE=IUP_FileSave" );
// add the Scintilla to the tabs
Ihandle* tabs = IupGetHandle( "tabs" );
IupAppend( tabs, sci );
IupMap( sci );
IupSetAttributeHandle( tabs, "VALUE", sci );
IupSetFocus( sci );
IupRefresh( tabs );
return IUP_IGNORE;
}
int close_cb( Ihandle* self )
{
Ihandle* tabs = IupGetHandle( "tabs" );
int old_count = IupGetChildCount( tabs );
if ( old_count == 0 ) return IUP_IGNORE;
// remove the current tab
Ihandle* old_tab = IupGetAttributeHandle( tabs, "VALUE" );
// see iupgtk_tabs.c:307
IupDestroy( old_tab );
IupRefreshChildren( tabs );
int new_count = IupGetChildCount( tabs );
if ( new_count == 0 ) return IUP_IGNORE;
// set focus to the new tab
Ihandle* new_tab = IupGetAttributeHandle( tabs, "VALUE" );
IupSetFocus( new_tab );
return IUP_IGNORE;
}
int tabchange_cb( Ihandle* self, Ihandle* old_tab, Ihandle* new_tab )
{
// set focus to the new tab
IupSetFocus( new_tab );
return IUP_CONTINUE;
}
int tabclose_cb( Ihandle* self, int pos )
{
// allow the old tab to be removed
return IUP_CONTINUE;
}
int main( int argc, char** argv )
{
IupOpen( &argc, &argv );
IupScintillaOpen();
IupImageLibOpen();
Ihandle* tabs = IupTabs( NULL );
IupSetAttribute( tabs, "SHOWCLOSE", "YES" );
IupSetCallback( tabs, "TABCHANGE_CB", (Icallback)tabchange_cb );
IupSetCallback( tabs, "TABCLOSE_CB", (Icallback)tabclose_cb );
IupSetHandle( "tabs", tabs );
Ihandle* dialog = IupDialog( tabs );
IupSetAttribute( dialog, "SIZE", "HALFxHALF" );
IupSetAttribute( dialog, "TITLE", "Tabs Demo" );
IupSetHandle( "dialog", dialog );
// Ctrl+N opens a new tab
IupSetCallback( dialog, "K_cN", (Icallback)new_cb );
// Ctrl+W closes the current tab
IupSetCallback( dialog, "K_cW", (Icallback)close_cb );
IupShowXY( dialog, IUP_CENTER, IUP_CENTER );
// add a new tab by default
new_cb( NULL );
IupMainLoop();
IupClose();
return EXIT_SUCCESS;
}
Screenshot: tabsdemo.png
A:
That was a bug in IUP. It is fixed now in SVN. Since today.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bug in Knockout JS with element inside foreach loop
I'm using Knockout JS to create a simple drop-down <select> box. I started by trying to use the example given in the Knockout JS docs:
<select data-bind="options: availableCountries"></select>
<script type="text/javascript">
var viewModel = {
availableCountries : ko.observableArray(['France', 'Germany', 'Spain'])
};
ko.applyBindings(viewModel);
</script>
This works perfectly.
However, if I place the <select> element INSIDE a foreach loop:
<div data-bind="foreach: [1,2,3]">
<select data-bind="options: availableCountries"></select>
</div>
<script type="text/javascript">
var viewModel = {
availableCountries : ko.observableArray(['France', 'Germany', 'Spain'])
};
ko.applyBindings(viewModel);
</script>
...now, all of a sudden, KnockoutJS is not able to find a reference to availableCountries. Chrome reports the following error in the console:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return [1,2,3] }"
Message: Unable to process binding "options: function (){return availableCountries }"
Message: availableCountries is not defined
This really looks like a bug in KnockoutJS... am I doing something wrong here, or is this simply a bug?
A:
Once you data-bind using a for-each, you are in the scope (also known as binding context) of the element of the for loop and it can't find a reference to availableCountries anymore.
Have you tried
$parent.availableCountries
If it's not its direct parent, the following might help (depending on your code):
$root.availableCountries
To learn more about binding context: http://knockoutjs.com/documentation/binding-context.html
| {
"pile_set_name": "StackExchange"
} |
Q:
What is wrong with Google Maps API?
I have an old application which used to work with the Google Maps API. I haven't changed the code since the last successful build but I am now unable to rebuild the app.
When I try to add a dependency to the "com.google.android.gms:play-service-maps:11.8.0" library, Android Studio tries to download the necessary files from the internet. Approximately when it reaches 50%, it displays the following error : "Could not find dependency "com.google.android.gms:play-services-maps:11.8.0".
Does anyone know why this happens and how to solve the problem?
A:
After changing implementation "com.google.android.gms:play-services:15.0.0" to implementation "com.google.firebase:firebase-invites:15.0.0, app build was successfull.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dividing in modular equation?
Does $ac\equiv ab \pmod{ad}$ always imply that $c\equiv b \pmod d$ ? If this is not always the case, then when is it ?
A:
$$ac\equiv ab \mod ad\iff\exists k\in\Bbb Z:ac-ab=adk\iff a(c-b)=a(dk)$$
then, if $a\neq 0$, cancellation of $a$ is valid, since $\Bbb Z$ is an integral domain. Thus, $c-b=dk\iff c\equiv b\mod d$.
A:
write your equation in the form $$ac=ab+kad$$ for some integer $k$ then we have
$$a(c-b-kd)=0$$ if $a=0$ then all is clear, and if not then we get
$$c=b+kd$$ and this is $$c\equiv b \mod d$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Launching Form B before form A. Why form A don't see user authentication information?
Simple synopsis: I have a program which needs authentication from user to get access or create file with user name and password. I have form A and form B; form A is a main window of my program which have a button pointing to form B, which is log in form. As of right now I must launch form A, and then click a button to go to form B because of necessary log in access to the files. My program is recognizing if person has logged in and it enables buttons that let me create a new file or access already created one (they are disabled by default, and only are enabled if authentication was first successful).
How can I make form to check for authentication before form A is opened?
Let me know if I am not clear enough...
Now, I have tried to initialize a form B before form A by doing this:
public MainWindow()
{
AuthenticationWindow login = new AuthenticationWindow();
login.ShowDialog();
InitializeComponent();
}
The problem is that when I do so that my program isn't enabling my buttons after authentication was in place.
I have tried to check for authentication before initializing my form by:
public MainWindow()
{
AuthenticationWindow login = new AuthenticationWindow();
login.ShowDialog();
if (storedAuth != null)
{
// Making Deleting and Adding possible
// when file was opened.
tsmiOpen.Enabled = true;
tsmiNew.Enabled = true;
}
InitializeComponent();
}
But still I can't open or create a file. Seems like program isn't checking for authenticated user.
This is my code which enables my buttons after authentication:
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
if (storedAuth != null)
{
tsmiOpen.Enabled = true;
tsmiNew.Enabled = true;
}
}
My shrinked code:
namespace Password_Manager
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
private HashPhrase hash = new HashPhrase();
private bool newSelected, openSelected;
public MainWindow()
{
AuthenticationWindow login = new AuthenticationWindow();
login.ShowDialog();
if (storedAuth != null)
{
// Making Deleting and Adding possible
// when file was opened.
tsmiOpen.Enabled = true;
tsmiNew.Enabled = true;
}
InitializeComponent();
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
// Displaying Authenticate Window.
// Not allowing switching between forms.
authWindow.ShowDialog();
storedAuth = authWindow.Result;
if (storedAuth != null)
{
// Making Deleting and Adding possible
// when file was opened.
tsmiOpen.Enabled = true;
tsmiNew.Enabled = true;
}
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
// Checking if the file is new or opened.
// This matter because we need to
// have appropriate path to the file.
if (openSelected)
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password,
ofdOpenFile.FileName);
// Displaying Add Entry Window.
// Not allowing switching between forms so I am using ShowDialog().
addWindow.ShowDialog();
}
if (newSelected)
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password,
sfdNewFile.FileName);
// Displaying Add Entry Window.
// Not allowing switching between
// forms so I am using ShowDialog().
addWindow.ShowDialog();
}
}
private void tsmiDeleteEntry_Click(object sender, EventArgs e)
{
// Checking if the file is new or opened.
// This matter because we need to
// have appropriate path to the file.
if (openSelected)
{
// When open file.
DeleteEntryWindow deleteEntyWindow = new DeleteEntryWindow
(this, storedAuth.UserName,
storedAuth.Password, ofdOpenFile.FileName);
deleteEntyWindow.ShowDialog();
}
else if (newSelected)
{
// When new file.
DeleteEntryWindow deleteEntyWindow = new DeleteEntryWindow
(this, storedAuth.UserName,
storedAuth.Password, sfdNewFile.FileName);
deleteEntyWindow.ShowDialog();
}
}
}
}
A:
My guess is that your InitializeComponent() code is resetting your buttons' .Enabled properties to false. The code in this method is the code that is created by the form designer in VS.
Try this...
public MainWindow()
{
InitializeComponent();
AuthenticationWindow login = new AuthenticationWindow();
login.ShowDialog();
storedAuth = login.Result;
if (storedAuth != null)
{
// Making Deleting and Adding possible
// when file was opened.
tsmiOpen.Enabled = true;
tsmiNew.Enabled = true;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using trim function with special characters
I have a column (A) of values that I would like to trim to the left. Each value in column A has a / in it which separates a word in German and it's English translation. For example one value would be "nein / no". (note there is a space between the two words.
What I want to do is write a trim function that starts after the space that follows the /. In othe words I want the value in my example to trim from "nein / no" to just "no". The part that confuses me is the fact that each value changes in size so I don't know how to tell excel where to trim from. My code should look something like this
For each cl in range("A1:A300"). Trim cl.value. Next cl
A:
Try below code :
Dim start As Long
For Each cl In Range("A1:A300")
str = c1
start = InStr(1, str, "/", vbTextCompare) + 1
strVal = Trim(Right(str, Len(str) - start))
msgbox strVal
Next cl
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento2 > Safely disable Add-To-Cart buttons
EDIT: This post apply to Magento 2.x
I would like to remove all add-to-cart button instances from my website.
I know I could do it from various way (removing that block with xml, removing from phtml...), while this is not an issue for me, I would like to know if there is a really safe way to do it in case I would have forgot to remove it from some place or the other. I want to completely remove the checkout and cart feature but wishlist and compare must stay.
Some specs:
Compare and wishlists are still enabled
Prices are listed
A:
You can do this by just changing the settings of the products.
For instance, set up a product to not be "saleable", or to have no stock and disable "out of stock" messages site-wide. Then configure the inventory module to still show products out of stock in their categories.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I build "Class::function()->function($parm)->function($parm);" methods in PHP and how it works?
I am wondering in Some of PHP frameworks uses methods like
Class::function()->function($parm)->function($parm);
for an example in Laravel
DB::table('users')->where('name', 'John')->value('email');
How these methods are internally working?
How can I build such Kind of method of my own?
Please help me out.
A:
Foo::function()->function Two() its a static call to a public function which returning a new instance.
Class foo{
Public static function (){
Return new class bar();
}
Class bar{
Public function functionTwo(){
//Some code
}
Keep in mind that this it is not always good because is violoting the Law of demeter https://en.m.wikipedia.org/wiki/Law_of_Demeter
| {
"pile_set_name": "StackExchange"
} |
Q:
fetch all members of a server inside a funtion | property members undefined | package: discord-giveaways
So i am using the package "discord-giveaways" and i want to use the "exemptMembers" option which is a function and with which i can set who is not allowed to take part in a giveaway and i want that people who haven't joined a specific server cannot take part but i am not sure if coded that right and also there is the error: TypeError: Cannot read property 'members' of undefined that i don't really know to fix, so it would be nice if someone can say me what i did wrong.
var server = require('./commands/giveaway/start-giveaway.js')
let guild = client.guilds.cache.get(server)
// Init discord giveaways
const { GiveawaysManager } = require('discord-giveaways');
client.giveawaysManager = new GiveawaysManager(client, {
storage: "./giveaways.json",
updateCountdownEvery: 5000,
default: {
botsCanWin: false,
embedColor: "0x0099ff",
embedColorEnd: "ff0000",
reaction: "",
exemptMembers: !guild.members.fetch()
}
});
If the function returns true then the member should not be able to take part in the giveaway: exemptMembers: !guild.members.fetch()
Please don't roast me to hard if i did it completely wrong .
The "start-giveaway" file:
run : async (message, client, args) => {
const ms = require('ms');
// Giveaway channel
let giveawayChannel = message.mentions.channels.first();
// If no channel is mentionned
if(!giveawayChannel){
return message.channel.send(':x: You have to mention a valid channel!');
}
// Giveaway duration
let giveawayDuration = args[1];
// If the duration isn't valid
if(!giveawayDuration || isNaN(ms(giveawayDuration))){
return message.channel.send(':x: You have to specify a valid duration!');
}
// Number of winners
let giveawayNumberWinners = args[2];
// If the specified number of winners is not a number
if(isNaN(giveawayNumberWinners)){
return message.channel.send(':x: You have to specify a valid number of winners!');
}
// Require members to join a server if author does not say "no"
if (args[3] !== 'no'){
var server = args[3]
console.log(server)
if(!server){
return message.channel.send(':x: You habe to specify a valid server ID or say "no"')
}
}
else {
console.log('User sayed no')
}
// Giveaway prize
let giveawayPrize = args.slice(4).join(' ');
// If no prize is specified
if(!giveawayPrize){
return message.channel.send(':x: You have to specify a valid prize!');
}
// Start the giveaway
client.giveawaysManager.start(giveawayChannel, {
// The giveaway duration
time: ms(giveawayDuration),
// The giveaway prize
prize: giveawayPrize,
// The giveaway winner count
winnerCount: giveawayNumberWinners,
// Who hosts this giveaway
hostedBy: true ? message.author : null,
// Messages
messages: {
giveaway: " **GIVEAWAY** ",
giveawayEnded: " **GIVEAWAY ENDED** ",
timeRemaining: "Time remaining: **{duration}**!",
inviteToParticipate: "React with to participate!",
winMessage: "Congratulations, {winners}! You won **{prize}**!",
embedFooter: "Giveaways",
noWinner: "Giveaway cancelled, no valid participations.",
hostedBy: "Hosted by: {user}",
winners: "winner(s)",
endedAt: "Ended at",
units: {
seconds: "seconds",
minutes: "minutes",
hours: "hours",
days: "days",
weeks: "weeks",
months: "months",
pluralS: false // Not needed, because units end with a S so it will automatically removed if the unit value is lower than 2
}
}
})
message.channel.send(`Giveaway started in ${giveawayChannel}!`);
}
A:
The issue is that start-giveaway.js file will not return any server id when you require it in the first code sample you gave. So let guild = client.guilds.cache.get(server) will always be undefined.
By looking at discord-giveaways documentation you can find out that in the options to start a giveaway you can define the exemptMembers property again, so this is what you should do :
Firstly, remove the exemptMembers property from the GiveawaysManager.
Then, modify start-giveaway.js file like below.
Warning - May 19 '20
exemptMembers property might not work properly right now, an issue is currently opened in the discord-giveaway GitHub about it!
run : async (message, client, args) => {
const ms = require('ms');
// Giveaway channel
let giveawayChannel = message.mentions.channels.first();
// If no channel is mentionned
if(!giveawayChannel){
return message.channel.send(':x: You have to mention a valid channel!');
}
// Giveaway duration
let giveawayDuration = args[1];
// If the duration isn't valid
if(!giveawayDuration || isNaN(ms(giveawayDuration))){
return message.channel.send(':x: You have to specify a valid duration!');
}
// Number of winners
let giveawayNumberWinners = args[2];
// If the specified number of winners is not a number
if(isNaN(giveawayNumberWinners)){
return message.channel.send(':x: You have to specify a valid number of winners!');
}
// Giveaway prize
let giveawayPrize = args.slice(4).join(' ');
// If no prize is specified
if(!giveawayPrize){
return message.channel.send(':x: You have to specify a valid prize!');
}
// Options for the giveaway
let giveawayStartOptions = {
// The giveaway duration
time: ms(giveawayDuration),
// The giveaway prize
prize: giveawayPrize,
// The giveaway winner count
winnerCount: giveawayNumberWinners,
// Who hosts this giveaway
hostedBy: true ? message.author : null,
// Messages
messages: {
giveaway: " **GIVEAWAY** ",
giveawayEnded: " **GIVEAWAY ENDED** ",
timeRemaining: "Time remaining: **{duration}**!",
inviteToParticipate: "React with to participate!",
winMessage: "Congratulations, {winners}! You won **{prize}**!",
embedFooter: "Giveaways",
noWinner: "Giveaway cancelled, no valid participations.",
hostedBy: "Hosted by: {user}",
winners: "winner(s)",
endedAt: "Ended at",
units: {
seconds: "seconds",
minutes: "minutes",
hours: "hours",
days: "days",
weeks: "weeks",
months: "months",
pluralS: false // Not needed, because units end with a S so it will automatically removed if the unit value is lower than 2
}
}
}
// Require members to join a server if author does not say "no"
if (args[3] !== 'no'){
let server = args[3];
console.log(server);
if(!server){
return message.channel.send(':x: You habe to specify a valid server ID or say "no"');
} else {
client.guilds.cache.get(server).members.fetch().then(otherServerMembers => {
// Who will be excluded from this giveaway if members have to join a specific server
giveawayStartOptions.exemptMembers = (member) => !otherServerMembers.has(member.id)
})
}
}
else {
console.log('User sayed no');
}
// Start the giveaway
client.giveawaysManager.start(giveawayChannel, giveawayStartOptions);
message.channel.send(`Giveaway started in ${giveawayChannel}!`);
}
Like this, exemptMembers will be defined only if the author gives a server id.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a data type in MsSQL bigger than float?
I am currently working with some ErlangC calculations to determine occupancy rates. I've got the functions I need working but when I start getting into higher numbers such as POWER(145,145), ~2.50242070x10^313, I get the following:
Arithmetic overflow error converting expression to data type float.
Is there anything in MsSQL I can use to handle these larger numbers? MS Excel can, but MsSQL can't?
A:
This is really hard. Not even Excel can handle this number. Excel can handle until 145^142 = 8.2084E+306. If you try 145^143 you will get an error.
CLR data types also do not handle this number, so CLR Data Type is not an option.
As ErlangC calculations are done for traffic modeling, I would review your process to see if you are using the correct units on your formula (minutes, seconds, etc). This number is really really big to be achieved in a Call Center if this is your case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery variable not defined error
I use the following jquery statements but i get error in this
function onGetDataSuccess(result) {
Iteratejsondata(result);
$(document).ready(function() {
$("#pager").pager({ pagenumber: 1, pagecount: 5, buttonClickCallback: PageClick });
});
PageClick = function(pageclickednumber) {
$("#pager").pager({ pagenumber: pageclickednumber, pagecount: 15, buttonClickCallback: PageClick });
$("#ResultsDiv").html("Clicked Page " + pageclickednumber);
}
}
}
Error:PageClick is not defined....
A:
I believe the way you create the PageClick function it could be parsed after the other code or the PageClick variable is not in scope.
Try this:
$(document).ready(function() {
var PageClick = function(pageclickednumber) {
$("#pager").pager({ pagenumber: pageclickednumber, pagecount: 15, buttonClickCallback: PageClick });
$("#ResultsDiv").html("Clicked Page " + pageclickednumber);
}
$("#pager").pager({ pagenumber: 1, pagecount: 5, buttonClickCallback: PageClick });
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Including a directory using Pyinstaller
All of the documentation for Pyinstaller talks about including individual files.
Is it possible to include a directory, or should I write a function to create the include array by traversing my include directory?
A:
Paste the following after a = Analysis() in the spec file to traverse a directory recursively and add all the files in it to the distribution.
##### include mydir in distribution #######
def extra_datas(mydir):
def rec_glob(p, files):
import os
import glob
for d in glob.glob(p):
if os.path.isfile(d):
files.append(d)
rec_glob("%s/*" % d, files)
files = []
rec_glob("%s/*" % mydir, files)
extra_datas = []
for f in files:
extra_datas.append((f, f, 'DATA'))
return extra_datas
###########################################
# append the 'data' dir
a.datas += extra_datas('data')
A:
I'm suprised that no one mentioned the official supported option using Tree():
https://stackoverflow.com/a/20677118/2230844
https://pythonhosted.org/PyInstaller/advanced-topics.html#the-toc-and-tree-classes
A:
What about just using glob?
from glob import glob
datas = []
datas += glob('/path/to/filedir/*')
datas += glob('/path/to/textdir/*.txt')
...
a.datas = datas
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I customize TableComparatorChooser to responds to single mouse clicks?
I have a GlazedList table, when i want to sort a column i should double click.
I want to change it to a single click.
Does anyone know how to do it?
A:
Just change the TableComparatorChooser.MULTIPLE_COLUMN_MOUSE to TableComparatorChooser.SINGLE_COLUMN
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending/receiving SMS using coldfusion
What are my options for sending an SMS using coldfusion? I've done a bit of research, but it's not a common language so I'm not finding a lot. So far, here are the three options I've come up with:
Sending an email to phone#@carrier.com. I don't want to do this, because I have to know my customer's carriers and I'm not sure I'd be able to receive replies.
Use a 3rd party gateway, such as Plivo. This may or may not be my best option. I was hoping to avoid any long-term costs in this project though.
Install a GSM Modem on my server - this is the one I'm curious about. Can coldfusion do this? Are there costs after the modem? How does it work exactly?
A:
CF has been able to send SMS via an Event Gateway for a while now.
https://helpx.adobe.com/coldfusion/developing-applications/using-external-resources/using-the-sms-event-gateway/configuring-an-sms-event-gateway.html
https://helpx.adobe.com/coldfusion/developing-applications/using-external-resources/using-the-sms-event-gateway/coldfusion-sms-development-tools.html
A:
I would suggest a service like Twilio that let you send SMS etc. With todays technology plus cloud based services, its better to use providers rather than reinventing the wheel.
HTH
AH.
| {
"pile_set_name": "StackExchange"
} |
Q:
Change length.out in ifelse function
I'm running a simple ifelse function
f <- function(x) {
ifelse(x==shift(x), x + 0.001* sd(x, na.rm = TRUE), x)
}
where shift is from the data.table package
which allows me to change, for each column in a dataframe (usig apply), a value which is exactly the same as the previous one. The problem is that the ifelse function returns a length which is equal to the length of the test. In this case, the length is the one of shift(x) and not x. Therefore I end up with the first element (or the last, if using type = "lead", instead of the default "lag") of each column turned into NA.
Here a MWE:
a <- c(1,2,2,3,4,5,6)
b <- c(4,5,6,7,8,8,9)
data <- data.frame(cbind(a,b))
f <- function(x) {
ifelse(x==shift(x), x + 0.001* sd(x, na.rm = TRUE), x)
}
apply(data, 2, f)
Therefore I thought I could change the ifelse function: I've done a few attempts to change the length.out but I haven't succeeded yet
function (test, yes, no)
{
if (is.atomic(test)) {
if (typeof(test) != "logical")
storage.mode(test) <- "logical"
if (length(test) == 1 && is.null(attributes(test))) {
if (is.na(test))
return(NA)
else if (test) {
if (length(yes) == 1 && is.null(attributes(yes)))
return(yes)
}
else if (length(no) == 1 && is.null(attributes(no)))
return(no)
}
}
else test <- if (isS4(test))
methods::as(test, "logical")
else as.logical(test)
ans <- test
ok <- !(nas <- is.na(test))
if (any(test[ok]))
ans[test & ok] <- rep(yes, length.out = length(ans))[test &
ok]
if (any(!test[ok]))
ans[!test & ok] <- rep(no, length.out = length(ans))[!test &
ok]
ans[nas] <- NA
ans
}
EDIT
My original code was:
copy <- copy(data)
for (j in 1: ncol(copy)) {
for (i in 2: nrow(copy)) {
if (copy[i,j] == copy[i-1,j] & !is.na(copy[i,j]) & !is.na(copy[i-1,j])) {
copy[i,j] <- copy[i-1,j] + (0.0001*sd(copy[,j], na.rm = T))
}
}
}
but using it with large matrices may cause slow running time. This deals with multiple repetitions.
The goal was to get to a vectorised, quicker method using a function and apply.
A:
As you mention, your approach leads to a NA in the first element of the vector returned by f. This first element is not similar to the previous (since there is none), so we would like to have the first value unchanged.
A straightforward approach is to do just that. Apologies, it does not answer your title question although it does solve your problem.
f <- function(x) {
# storing the output of ifelse in a variable
out <- ifelse(x==shift(x), x + 0.001* sd(x, na.rm = TRUE), x)
# changing the first element of `out` into first element of x
out[1] <- x[1]
# returning `out` -- in a R function,
# the last thing evaluated is returned
out
}
Note that this will not take care properly of elements repeated more than twice (e.g. c(1,2,2,2,3)). Also, this will change all your element the same way. So in c(1,2,2,1,2,2), all the second twos will be changed the same way. This may or mat not be something you want.
You could hack something (a comment suggests ?rle), but I suggest changing the way you randomize your data, if this makes sense with your particular data.
Instead of adding 0.001*sd, maybe you could add a gaussian noise with this standard dev? This depends on your application obviously.
f <- function(x) {
# adding gaussian noise with small sd to repeated values
# storing the output in a variable `out`
out <- ifelse(x==shift(x),
x + rnorm(length(x), mean=0,
sd=0.01*sd(x, na.rm = TRUE)),
x)
# changing the first element of `out` into first element of x
out[1] <- x[1]
# returning `out` -- in a R function,
# the last thing evaluated is returned
out
}
It depends on what is your purpose for getting rid of exact duplicated values.
| {
"pile_set_name": "StackExchange"
} |
Q:
In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?
You have an array of shape (a,b,c) and you want to multiply the second dimension by an array of shape (b)
A for loop would work, but is there a better way?
Ex.
A = np.array(shape=(a,b,c))
B = np.array(shape=(b))
for i in B.shape[0]:
A[:,i,:]=A[:,i,:]*B[i]
A:
Use broadcasting:
A*B[:,np.newaxis]
For example:
In [47]: A=np.arange(24).reshape(2,3,4)
In [48]: B=np.arange(3)
In [49]: A*B[:,np.newaxis]
Out[49]:
array([[[ 0, 0, 0, 0],
[ 4, 5, 6, 7],
[16, 18, 20, 22]],
[[ 0, 0, 0, 0],
[16, 17, 18, 19],
[40, 42, 44, 46]]])
B[:,np.newaxis] has shape (3,1). Broadcasting adds new axes on the left,
so this is broadcasted to shape (1,3,1). Broadcasting also repeats the items along axes with length 1. So when multiplied with A, it gets further broadcasted to shape (2,3,4). This matches the shape of A. Multiplication then proceeds element-wise, as always.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I force cabal to give me more meaningful error messages?
On trying to install Pandoc, I see:
....
/usr/local/bin/ghc --make -o dist/build/pandoc/pandoc -hide-all-packages -fbuilding-cabal-package -package-conf dist/package.conf.inplace -i -idist/build/pandoc/pandoc-tmp -isrc -idist/build/autogen -Idist/build/autogen -Idist/build/pandoc/pandoc-tmp -optP-include -optPdist/build/autogen/cabal_macros.h -odir dist/build/pandoc/pandoc-tmp -hidir dist/build/pandoc/pandoc-tmp -stubdir dist/build/pandoc/pandoc-tmp -package-id HTTP-4000.2.2-b514c58971c354891f971c2309e33000 -package-id base-4.5.0.0-f76ceb9607ba9bd4fcfb9c7b92d8cfe1 -package-id base64-bytestring-0.1.1.0-9a13565ae6900096f49fed9275055262 -package-id blaze-html-0.4.3.1-5d598387646df0193836b494a162a2d4 -package-id bytestring-0.9.2.1-4adca9710b1386944aaca5a7886ef98f -package-id citeproc-hs-0.3.4-cbb3e9b1b273d47e103e907ec1bdc35b -package-id containers-0.4.2.1-7c54595400348f577b3b4a45691c5afd -package-id directory-1.1.0.2-8b4f1910e60eb4e736abc40d5bcff870 -package-id extensible-exceptions-0.1.1.4-d27a1ac47e54880cae007cceceb41580 -package-id filepath-1.3.0.0-674b8a582fb49f1c9724f50a6a5d5768 -package-id highlighting-kate-0.5.0.5-a1ba824bf441c42c048d12abbb7076f2 -package-id json-0.5-95bdbc43daf81b2bce0748d1aaa9c3a3 -package-id mtl-2.0.1.0-e356d8b8100adb575c81fb037ade5369 -package-id network-2.3.0.11-aad575b3bc998a0814d4406663f72a07 -package-id old-locale-1.0.0.4-29bd50ed2bb4a20928338f52e4ab1b71 -package-id pandoc-types-1.9.1-861bbcdbc020a96a664261e3dea501f4 -package-id parsec-3.1.2-ddd167c649705555d9a0c4e2b3751077 -package-id process-1.1.0.1-91185c964ab744c1f3cbca1863d2ba45 -package-id random-1.0.1.1-3bece392c9f5221263ed25c90c28e1ec -package-id syb-0.3.6-05925f4440bc3fbb54d5c12bac109e49 -package-id tagsoup-0.12.6-57ca8a2db7339ea6237481f4729e5e0f -package-id temporary-1.1.2.3-e69a9bd7a2d9d49de929e9a0be4ed42a -package-id texmath-0.6.0.3-2e5a17474805a2f6b73558e3a71ad38b -package-id time-1.4-3e186a51d3674e5d65b5a7925db3d3a7 -package-id utf8-string-0.3.7-528cea24d4cad2c1cb19a75d1ad8976c -package-id xml-1.3.12-d665e5a084b52511c150438a3c9fb8d1 -package-id zip-archive-0.1.1.7-463904d956f1052cc58a2c9e5deeee2c -package-id zlib-0.5.3.3-9ed15628a121b3b57f97b7acc02bf5d9 -O -O2 -Wall -fno-warn-unused-do-bind -dno-debug-output -XHaskell98 -XCPP src/pandoc.hs
[39 of 42] Compiling Text.Pandoc.Readers.Markdown ( src/Text/Pandoc/Readers/Markdown.hs, dist/build/pandoc/pandoc-tmp/Text/Pandoc/Readers/Markdown.o )
cabal: Error: some packages failed to install:
pandoc-1.9.1.1 failed during the building phase. The exception was:
ExitFailure 11
If I try to run that command, it works without any problems. So why do I see ExitFailure 11? How do I get cabal to give me a decent error message?
As a side note: I love Haskell, but cabal is awful. We need a better package manager.
A:
Try using the --verbose=3 flag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between `share()` and `publish().refCount()`
What's the practical difference between observable.publish().refCount() and observable.share(). What would be an example of an scenario in which we don't want to use share?
A:
There is no practical difference, if you look at 'observable.prototype.share' you will see that it simply returns 'source.publish().refCount()'.
As to why you would want to use it, it is more a question of how much control you need over when your source starts broadcasting.
Since refCount() will attach the underlying observable on first subscription, it could very well be the case that subsequent observers will miss messages that come in before they can subscribe.
For instance:
var source = Rx.Observable.range(0, 5).share();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
Only the first subscriber will receive any values, if we want both to receive them we would use:
var source = Rx.Observable.range(0, 5).publish();
var sub1 = source.subscribe(x => console.log("Observer 1: " + x));
var sub2 = source.subscribe(x => console.log("Observer 2: " + x));
source.connect();
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I know all my tasks in Grand Central Dispatch finished?
I need to send multiple tasks to Grand Central Dispatch to run. Some tasks will finish first, while some will finish last.
How do I know all my tasks in Grand Central Dispatch finished?
Should I use a counter to record the number of tasks finished? Any smarter method?
A:
You can use dispatch groups to be notified when all tasks completed. This is an example from http://cocoasamurai.blogspot.com/2009/09/guide-to-blocks-grand-central-dispatch.html
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,queue,^{
NSLog(@"Block 1");
});
dispatch_group_async(group,queue,^{
NSLog(@"Block 2");
});
dispatch_group_notify(group,queue,^{
NSLog(@"Final block is executed last after 1 and 2");
});
A:
If you want to control one task to execute at the end,you can use dispatch_group_t,If you want one task not only to execute after some tasks but also to execute before some tasks,you can use dispatch_barrier_sync:
dispatch_queue_t queue = dispatch_queue_create("com.example.gcd", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{ printf("1");});
dispatch_async(queue, ^{ printf("2");});
dispatch_barrier_sync(queue, ^{ printf("3");});
dispatch_async(queue, ^{ printf("4");});
dispatch_async(queue, ^{ printf("5");});
it may print
12345 or 21354 or ... but 3 always after 1 and 2, and 3 always before 4 and 5
If your want to control the order exactly, you can use dispatch_sync or Serial Dispatch Queue,or NSOperationQueue.If you use NSOperationQueue,use the method of "addDependency" to control the order of tasks:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op 1");
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op 2");
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op 3");
}];
//op3 is executed last after op2,op2 after op1
[op2 addDependency:op1];
[op3 addDependency:op2];
[queue addOperation:op1];
[queue addOperation:op2];
[[NSOperationQueue mainQueue] addOperation:op3];
It will always print:
op1 op2 op3
| {
"pile_set_name": "StackExchange"
} |
Q:
Nil polynomial quotient ring
Is the ring $R$ described in this answer a nil ring?
It seems to me that any polynomial $f\in R$ of zero constant term is nilpotent, considering the greatest power $k$ of some $X_i$ existing in it, i.e., $f^k=0$. Thanks for any suggestion!
A:
It can't be a nil ring since it has a unit element different from $0$ (it contains a field), but the ideal $(X_2,\dots,X_n,\dots)$ is a nilideal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why am I getting a syntax error using Informix dbaccess?
I'm getting this syntax error in IBM Informix using the dbaccess utility:
root@guava:/opt/informix# bin/dbaccess - -
Your evaluation license will expire on 2015-12-22 00:00:00
> show databases;
201: A syntax error has occurred.
Error in line 1
Near character position 1
Any suggestions?
A:
You get the 'syntax error' because SHOW DATABASES is not a valid command in DB-Access. In fact, SHOW is not a valid keyword in either DB-Access or the underlying DBMS.
If anything was going to work, it would be INFO DATABASES; however, that is not actually supported in DB-Access (but it is in my SQLCMD program, which I use in preference to DB-Access, and have used since I first wrote it back in 1987).
There are other INFO commands to list tables, columns, etc.
INFO TABLES; -- List of user-defined tables and views
INFO COLUMNS FOR systables; -- Columns for a specific table
INFO INDEXES FOR systables; -- Indexes on a specific table
These commands are interpreted by DB-Access and not by the Informix database server, and translate into queries against the system catalog of the current database. The list of databases is, therefore, somewhat different because the information is not a part of the system catalog of the current database.
The list of databases is available from a table in the sysmaster database:
SELECT * FROM SysMaster:informix.sysdatabases;
Example output from one Informix server:
…
name mode_ansi
partnum 1048920
owner jleffler
created 2014-04-30
is_logging 1
is_buff_log 0
is_ansi 1
is_nls 0
is_case_insens 0
flags -12283
name utf8
partnum 1048988
owner jleffler
created 2014-04-30
is_logging 1
is_buff_log 1
is_ansi 0
is_nls 0
is_case_insens 0
flags -12285
…
Alternatively, if you run DB-Access in the curses-mode (either dbaccess or dbaccess dbname), then there is a menu option Databases which leads to a sub-menu that allows you to list, select, create, and drop databases.
| {
"pile_set_name": "StackExchange"
} |
Q:
python graph-tool load csv file
I'm loading directed weighted graph from csv file into graph-tool graph in python. The organization of the input csv file is:
1,2,300
2,4,432
3,89,1.24
...
Where the fist two entries of a line identify source and target of an edge and the third number is the weight of the edge.
Currently I'm using:
g = gt.Graph()
e_weight = g.new_edge_property("float")
csv_network = open (in_file_directory+ '/'+network_input, 'r')
csv_data_n = csv_network.readlines()
for line in csv_data_n:
edge = line.replace('\r\n','')
edge = edge.split(delimiter)
e = g.add_edge(edge[0], edge[1])
e_weight[e] = float(edge[2])
However it takes quite long to load the data (I have network of 10 millions of nodes and it takes about 45 min).
I have tried to make it faster by using g.add_edge_list, but this works only for unweighted graphs. Any suggestion how to make it faster?
A:
This has been answered in graph-tool's mailing list:
http://lists.skewed.de/pipermail/graph-tool/2015-June/002043.html
In short, you should use the function g.add_edge_list(), as you said, and and put the weights separately
via the array interface for property maps:
e_weight.a = weight_list
The weight list should have the same ordering as the edges you passed to
g.add_edge_list().
| {
"pile_set_name": "StackExchange"
} |
Q:
creating hyperlink dynamically
i am trying to create a hyperlink from code-behind, but it is not creating it where i want it to be.
if i look at my souce code is creating somewhere else and from .aspx page it seems like everything is in place where it needs to be.
.aspx
<div class="AZ">
<ol class="AZlist">
<asp:PlaceHolder runat="server" ID="AToZ"></asp:PlaceHolder>
</ol>
</div>
.codebehind
HyperLink links = new HyperLink();
links.Text = "<li>" + CheckMe.ToString() + "</li>";
links.NavigateUrl = "<a href='#'" + CheckMe.ToString() + ">";
ph.Controls.Add(links);
source code:
....
....
...
<div class="AZ">
<ol class="AZlist">
// I WANT HYPERLINK HERE....!!!!!!!!!!!
</ol>
<br />
</div>
</li>
but its creating outside the div area here
<a href="#A"><li>A</li></a>
A:
I dont think you should put those tags in the .text and .navigateurl properties. just put the link and the text in them. Put the <li> tags around the placeholder.
| {
"pile_set_name": "StackExchange"
} |
Q:
Autoboxing can't convert an int to an Integer
I am a complete beginner and I'm trying to learn java. I read about the concept of Autoboxing and Unboxing here.
I am working on java version 1.8.0_05 and using Eclipse.
The code is :
class Test {
public static void main(String[] args) {
Integer iob = 100; // shows error -> Type mismatch: Cannot convert from int to Integer
}
}
Thanks for the help.
A:
You need to have your language level set to at least 1.5/5.0 to take advantage of autoboxing/unboxing.
Change your settings in Project --> Properties --> Java Compiler, chances are, it's not set to the right level.
Note this is NOT directly tied to the version of the JDK you're using, it simply means the level in which your java code will be interpreted as if it were no higher than the language level version, using any particular version of the JDK that is at least at or higher than the given language level setting.
IE: you're using JDK 1.8+, setting your language level to 5.0 means you will only be able to use java features that are up to JDK 1.5.
| {
"pile_set_name": "StackExchange"
} |
Q:
C++) E0349 no operator matches these operands occured
I wanted to make scalar * vector operation like 5 * (2,3) = (10,15).
e0349 - no operator matches these operands has been occured after running as below.
But I don't know what's wrong in there.
Here's my code.
#include <iostream>
using namespace std;
class Vector {
public:
Vector();
Vector(float x, float y);
float GetX() const;
float GetY() const;
static Vector operator*(const float x, const Vector b); //Scalar * Vector operation
private:
float x;
float y;
};
int main() {
Vector a(2, 3);
Vector b = 5 * a; //Error's here !
cout << a.GetX() << ", " << a.GetY() << endl;
cout << b.GetX() << ", " << b.GetY() << endl;
}
Vector::Vector() : x(0), y(0) {}
Vector::Vector(float x, float y) : x(x), y(y) {}
float Vector::GetX() const { return x; }
float Vector::GetY() const { return y; }
Vector Vector::operator*(const float a, const Vector b) {
return Vector(a * b.x, a * b.y);
}
'''
A:
You should make operator* a non-member function here, and since you're accessing the private members in it, you can mark it as friend.
class Vector {
public:
Vector();
Vector(float x, float y);
float GetX() const;
float GetY() const;
friend Vector operator*(const float x, const Vector b); //Scalar * Vector operation
private:
float x;
float y;
};
...
Vector operator*(const float a, const Vector b) {
return Vector(a * b.x, a * b.y);
}
LIVE
Or (without making it friend)
class Vector {
public:
Vector();
Vector(float x, float y);
float GetX() const;
float GetY() const;
private:
float x;
float y;
};
Vector operator*(const float x, const Vector b); //Scalar * Vector operation
...
Vector operator*(const float a, const Vector b) {
return Vector(a * b.GetX(), a * b.GetY());
}
LIVE
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use data attributes with Font Awesome?
I want to convert a rel content into a Font Awesome CSS icon, so I won't have to write 20 lines for a simple menu.
Maybe some code would make it easier to understand.
I tried to do this:
a:before {content: "\(" attr(rel) ")"; font-family: 'FontAwesome';}
Basically I am trying to convert the value inside the rel and convert it to a working CSS rule.
So the link looks like this:
<a href="http://www.example.com" rel="f291">Example</a>
The end result should look something like:
a:before {content: "\f291")"; font-family: 'FontAwesome';}
A:
Although the question may duplicate to this post. In a simple word - you'll need to use HTML entity, or the unicode character itself, in order to use it in CSS content property.
However it's a very interesting idea to use the technique with Font Awesome, so I'm writing this answer, and adding the extra info for it.
I'd suggest to use data attributes data- instead of rel, as rel is designed for link types.
And on this page has a complete set of Font Awesome unicode tables. You can either copy/paste the unicode character, or the icon itself. Examples below:
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css");
a::before {
font-family: 'FontAwesome';
content: attr(data-fa-icon);
}
<p><a href="#" data-fa-icon=""> Unicode example</a></p>
<p><a href="#" data-fa-icon=""> Icon example</a></p>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to debug css in IE?
Is there a way to debug a css file in IE? I wish to see if a particular background-image is loaded or not.
This is in reference to the question:
extjs gridfilter icon not showing in IE but shows in Firefox
A:
Or for any version of IE, try FireBug Lite. You can simply bookmark the link given on that page (bookmarklet) and then, to open a FireBug like thingy whilst on IE, simply click on the bookmark you just added.
| {
"pile_set_name": "StackExchange"
} |
Q:
Today ExtensionでRealmデータの共有の書き方について
下記ページなどを参考にアプリとToday Extensionの間でRealmデータの共有をしたいのですが、
https://qiita.com/oidy/items/3bcb26d67a1c4c9d90c7
下記あたりのコードの書き方が分からなくて色々と試しているのですがアプリが落ちたりしています。
var config = Realm.Configuration()
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.example.MyApp")!
config.fileURL = url.appendingPathComponent("db.realm")
アプリ側のコードです。
// AppDelegate.swift
func setupRealm() {
var fileNum = 0
var config = Realm.Configuration.defaultConfiguration
var realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u0.realm")
let fileMng = FileManager.default
if !fileMng.fileExists(atPath: realmFileURL.path) {
realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u1.realm")
fileNum = 1
}
config.fileURL = realmFileURL
Realm.Configuration.defaultConfiguration = config
compaction(fileNum: fileNum)
}
func compaction(fileNum: Int) {
let config = Realm.Configuration.defaultConfiguration
let realmFileURL = config.fileURL!
var copyFileURL = realmFileURL.deletingLastPathComponent().appendingPathComponent("u1.realm")
if fileNum == 1 {
copyFileURL = realmFileURL.deletingLastPathComponent().appendingPathComponent("u0.realm")
}
let fileManager = FileManager()
if fileManager.fileExists(atPath: realmFileURL.path) {
autoreleasepool {
do {
let realm = try Realm(configuration: config)
try realm.writeCopy(toFile: (copyFileURL as NSURL) as URL)
} catch {
let _ = try? fileManager.removeItem(at: realmFileURL)
}
}
let _ = try? fileManager.removeItem(at: realmFileURL)
let _ = try? fileManager.moveItem(at: copyFileURL, to: realmFileURL)
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupRealm()
return true
}
Today Extension側のコードです。
// TodayViewController.swift
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
var config = Realm.Configuration.defaultConfiguration
var realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u0.realm")
let fileMng = FileManager.default
if !fileMng.fileExists(atPath: realmFileURL.path) {
realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u1.realm")
}
config.fileURL = realmFileURL
Realm.Configuration.defaultConfiguration = config
completionHandler(NCUpdateResult.newData)
}
環境はXcode 9.1、Swift 4です。
どうぞ、よろしくお願いいたします。
A:
下記のように修正することでエクステンション側でデータを取得できました。
アプリ側
// AppDelegate.swift
var fileNum = 0
var config = Realm.Configuration.defaultConfiguration
var realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u0.realm")
let fileMng = FileManager.default
if !fileMng.fileExists(atPath: realmFileURL.path) {
realmFileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("u1.realm")
fileNum = 1
}
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.sample.myapp")!
if fileNum == 0 {
config.fileURL = url.appendingPathComponent("u0.realm")
} else {
config.fileURL = url.appendingPathComponent("u1.realm")
}
Realm.Configuration.defaultConfiguration = config
エクステンション側
// TodayViewController.swift
var config = Realm.Configuration.defaultConfiguration
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.sample.myapp")!
var realmFileURL = url.appendingPathComponent("u0.realm")
let fileMng = FileManager.default
if !fileMng.fileExists(atPath: realmFileURL.path) {
realmFileURL = url.appendingPathComponent("u1.realm")
}
config.fileURL = realmFileURL
Realm.Configuration.defaultConfiguration = config
| {
"pile_set_name": "StackExchange"
} |
Q:
Word for bad legacy
Is there an individual word to describe a bad legacy in the English language. I'm looking for something that would fit sentences like:
"Hitler's ~word~ still haunts modern Germany"
"His ~word~ caused them to expatriate him"
While strictly maintaining the idea of "bad legacy"
A:
As @Dan Bron mentioned in the comments I think the word infamy works well
in the first example.
infamy
The state of being well known for some bad quality or deed
"Hitler's infamy still haunts modern Germany"
As for the second example there are a number of words that could fit. You could use the plural of infamy with a concentration on definition 1.1.
infamies
evil or wicked acts
"His infamies caused them to expatriate him"
But you could also use other words like disrepute etc. The comments section also brings up many alternatives.
A:
This depends upon which word you wish to emphasize.
Ignominious - (adjective) deserving or causing public disgrace or shame
Ignominy - (noun) shameful or dishonorable quality or conduct or an instance of this.
Infamous - (adjective) well known for some bad quality or deed
Infamy - (noun) an infamous act or circumstance.
If you pay careful attention, these are very close in meaning with subtle yet powerful differences interpreted when I encounter them in use.
If you wish to emphasize "bad" or "shameful" then forms of Ignominious are the better choice, to my ear.
If you wish to emphasize "legacy" or "perception" then forms of Infamous ring clearer.
So, to use your example sentences:
"Hitler's ignominy still haunts modern Germany"
"His ignominy caused them to expatriate him"
Each of these places emphasis on the deserving of shame without necessarily placing concern on the expanse of his notoriety.
"Hitler's infamy still haunts modern Germany"
"His infamy caused them to expatriate him"
Each of these places emphasis on the public opinion of perceived acts.
One can be infamous for things not done, but one cannot be "ignominious" without being deserving of the label. Ignominious is the stronger term here, because it directly asserts causation between acts and the label where infamy merely connotes a correlation between perceived acts and the label.
A:
I don't think there is a single word in English that captures the combined meaning of both words in the phrase "bad legacy".
'Legacy' itself is neutral, and is often used in negative context, such as "Pollution's legacy", so I think you could use simply 'legacy' in your example. No one would think you were commending him.
| {
"pile_set_name": "StackExchange"
} |
Q:
Include HTML in theme_pager_next $text variable?
Is it possible to include markup in the $text variable of theme_pager_next()? I find that whatever I set the variable to gets output as a string, rather than being rendered as HTML. Here's some example code as would be found in template.php:
function theme_pager_next($variables){
$text = '<span>test value</span>';
/* Remainder of function call goes here ...*/
return $output;
}
I would like be able to add an image to the pager text. I realize I could also use CSS background images, but would prefer to print markup to the page if at all possible.
Is there something I'm overlooking?
A:
If the rest of the code is the same used in theme_pager_next(), then it is not possible to add HTML tags to $text.
This is because theme_pager_next(), and theme_pager_last() call theme_pager_link(). theme_pager_next()'s code is the following one.
if ($page_new[$element] == ($pager_total[$element] - 1)) {
$output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters));
}
// The next page is not the last page.
else {
$output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters));
}
theme_pager_link() then contains the following code.
$attributes['href'] = url($_GET['q'], array('query' => $query));
return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
As it calls check_plain(), if $text contains HTML tags, they are shown as plain text.
To achieve what you are trying to do, you should override theme_pager_link() with a theme function that doesn't call check_plain(). filter_xss() could be a better function to use in this case, but remember to pass in $allowed_tags the list of the tags you want to allow.
As side note, when you want to alter the content of the $variables array a theme function gets, in Drupal 7 you can use its preprocess functions. Every theme function has preprocess functions, and in your theme that is THEME_preprocess_pager_next(). (Replace THEME with the short name of your theme.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to say 'It differs depending on the person'
Would the following sentence be correct?
人によってちがいます。
Or would it make more sense to use '人々'? As in;
人々によってちがいます。
A:
Your first sentence that uses 「人」 would be far more natural than your second with 「人々」.
There is no comparison here.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does designer create a Line widget?
In Qt Designer , you can drag a "Line" widget , which will create a line in your layout.
But I checked the document and headers , I didn't find the "Line" header / widget , what was it ?
A:
In Qt 5.7 the code generated by Qt Designer for a Horizontal Line (which can be checked in the menu using "Form/View Code...") is:
QFrame *line;
line = new QFrame(Form);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
This will create the lines you see in Qt Designer.
The current answers do not seem to give working solutions, here is a comparison of all answers (this solution is the first line):
Full code:
#include <QtWidgets>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QWidget widget;
auto layout = new QVBoxLayout;
widget.setLayout(layout);
widget.resize(200, 200);
auto lineA = new QFrame;
lineA->setFrameShape(QFrame::HLine);
lineA->setFrameShadow(QFrame::Sunken);
layout->addWidget(lineA);
QWidget *lineB = new QWidget;
lineB->setFixedHeight(2);
lineB->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
lineB->setStyleSheet(QString("background-color: #c0c0c0;"));
layout->addWidget(lineB);
auto lineC = new QFrame;
lineC->setFixedHeight(3);
lineC->setFrameShadow(QFrame::Sunken);
lineC->setLineWidth(1);
layout->addWidget(lineC);
QFrame* lineD = new QFrame;
lineD->setFrameShape(QFrame::HLine);
layout->addWidget(lineD);
widget.show();
return app.exec();
}
A:
I guess you mean a horizontal / vertical line widget: it's just a simple QWidget with a gray background color and the horizontal is a fix height (1-3 pixel) and expanding width widget, the vertical is a fix width expanding height widget.
Horizontal example code:
QWidget *horizontalLineWidget = new QWidget;
horizontalLineWidget->setFixedHeight(2);
horizontalLineWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
horizontalLineWidget->setStyleSheet(QString("background-color: #c0c0c0;"));
A:
It is a QFrame with height 3, sunken shadow and line width equal to 1.
You can see it if examine header generated by uic tool.
| {
"pile_set_name": "StackExchange"
} |
Q:
When debugging how do we know the frame of a UIView or how is it stored?
Take a look at the picture below
I am looking for UIView and I cannot find this so called _frame struct.
How internally exactly apple store a UIView frame? And what would be the easiest way to find that out during debugging?
A:
A UIView doesn't store its frame; it just returns its layer's frame.
A CALayer doesn't store its frame either. When you ask a layer for its frame, the layer computes the frame based on the layer's bounds, position, anchorPoint, and transform. (Possibly it caches the computed frame, but if you disassemble the -[CALayer frame] method you will find code for computing it from the other properties.)
And a CALayer doesn't store any of those properties in instance variables. Instead, it has a pointer to a CA::Layer instance, which is a private C++ object. That C++ object stores the layer's properties. The view->_layer->_attr.layer field is the pointer to the private CA::Layer instance.
If you want to see a view's frame in the debugger, you have to send it a message. You can ask it for its description:
po _topBubble
Or you can ask it for its frame:
p (CGRect)[_topBubble frame]
| {
"pile_set_name": "StackExchange"
} |
Q:
Generating readable ids for dynamoDB
When working with dynamoDB and have a need to generate unique ids for customers, products or other things that users will come in contact with what is the correct way of doing it?
Sure UUIDs are great but its not something you can expect a customer to use and if I want to make my own on my server I have to make pretty awkward database calls to make sure I either use the next one in some sequence, save some weird extra field or make random stabs in the dark.
So how can I go about solving this issue?
A:
I would argue that UUIDs are still the way to go. Especially if you are looking to architect a scalable solution, then you can't rely on a single "point of failure" to generate some sort of sequential unique identifiers - anything like that will require synchronization and availability which are the enemy of performance in a distributed system.
However, if you'd like to generate some more human friendly identifiers, you have a couple of options:
you could start with UUIDs and fold those in half (take the first 8 bytes and xor with the last 8 bytes), then take the resulting 64-bit number and encode using a base 62 encoding (numbers from 0-9 plus upper and lower -case letters) to generate a 11 character string that is somewhat more human-friendly then a typical UUID; if you're ok with less entropy you could fold the UUID twice, obtaining a 32-bit number which you could encode into a 6 character base 62 representation, or an 7 character base 32 encoding which only uses numbers and upper case letters
the second approach you could take is to use a combination of mac address, time stamp and pseudo random number generator to generate your own ids, following a certain rule, similar to how UUIDs are generated but with less entropy, again, so that you may encode the IDs such that they are user friendly
You can prevent issues that could arise in the case where the same ID is accidentally generated in two different places, you can take advantage of conditional writes to DynamoDB.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Integration with Struts .. Why?
Can Anyone please tell why we need to integrate springs with struts.. Wat is the use of doing so?
some are mentioned "dependency injection that can be useful to any framework" what does it really mean?
A:
Dependency Injection allows easy substitution of implementations. One of the greatest benefits comes during testing: I can inject implementations with known behavior and bypass other system components.
DI is available inside S2 already, via XWork--but considering how much of Spring's functionality is generally useful anyway, I almost always use Spring for essentially all my DI/IoC as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript Array with Dynamic Editable Objects and values
I have to track cars and car types/colors without a database and I'm looking for a way to create an array with objects that I can update and delete, then be able to call the array.
So maybe something like this where I can add/edit/delete any of the object properties by car:
let cars = [];
cars['ferrari'] = "red";
cars["lambo"] = "white";
cars["bentley"] = "silver";
I know how to get the value with this example:
showcolor = 'ferrari';
alert(cars[showcolor]);
Is it possible to push a new object into this array and/or update a single car and change the color for that car with a function that looks for the object value 'ferrari' and changes its color to 'black'? Also if I wanted to create an alert to show the contents of the array, how can I do that?
A:
Or use an array, but let each element of the array be an object.
let cars = [];
cars.push({ make: 'ferrari', color: 'red' });
cars.push({ make: 'lambo', color: 'white' });
cars.push({ make: 'bentley', color: 'silver' });
console.log(JSON.stringify(cars));
// Make the lambo black instead of white.
cars.find(car => car.make == 'lambo').color = 'black';
console.log(JSON.stringify(cars));
Output is:
[{"make":"ferrari","color":"red"},{"make":"lambo","color":"white"},{"make":"bentley","color":"silver"}]
[{"make":"ferrari","color":"red"},{"make":"lambo","color":"black"},{"make":"bentley","color":"silver"}]
Note the lambo color changed.
| {
"pile_set_name": "StackExchange"
} |
Q:
using keyboard with swtbot test
I'm trying to run SWTbot test case that uses keyboard short-cuts. I could not find any reference for how to do it.
I'm pretty sure that should not be that difficult. I'll appreciate it if someone can write a small snippet.
Thanks,
Ziv
A:
What about using the pressShortcut() methood?
For TreeItem:
final SWTBotTreeItem item = ...
item.select().pressShortcut(SWT.CTRL, 'F');
For TableItem:
final SWTBotTableItem item = ...
item.select().pressShortcut(SWT.CTRL, 'F');
For EclipseEditor
((SWTBotEclipseEditor)bot.activeEditor()).pressShortcut(SWT.CTRL, '1')
From Active Shell:
bot.activeShell().pressShortcut(
Keystrokes.CTRL, KeyStroke.getInstance("1"));
| {
"pile_set_name": "StackExchange"
} |
Q:
Union as sub query MySQL
I'm wanting to optimize a query using a union as a sub query. Im not really sure how to construct the query though. I'm using MYSQL 5
Here is the original query:
SELECT Parts.id
FROM Parts_Category, Parts
LEFT JOIN Image ON Parts.image_id = Image.id
WHERE
(
(
Parts_Category.category_id = '508' OR
Parts_Category.main_category_id ='508'
) AND
Parts.id = Parts_Category.Parts_id
) AND
Parts.status = 'A'
GROUP BY
Parts.id
What I want to do is replace this ( (Parts_Category.category_id = '508' OR Parts_Category.main_category_id ='508' ) part with the union below. This way I can drop the GROUP BY clause and use straight col indexes which should improve performance. Parts and parts category tables contains half a million records each so any gain would be great.
(
SELECT * FROM
(
(SELECT Parts_id FROM Parts_Category WHERE category_id = '508')
UNION
(SELECT Parts_id FROM Parts_Category WHERE main_category_id = '508')
)
as Parts_id
)
Can anybody give me a clue on how to re-write it? I've tried for hours but can't get it as I'm only fairly new to MySQL.
A:
SELECT Parts.id
FROM (
SELECT parts_id
FROM Parts_Category
WHERE Parts_Category.category_id = '508'
UNION
SELECT parts_id
FROM Parts_Category
WHERE Parts_Category.main_category_id = '508'
) pc
JOIN Parts
ON parts.id = pc.parts_id
AND Parts.status = 'A'
LEFT JOIN
Image
ON image.id = parts.image_id
Note that MySQL can use Index Merge and you can rewrite your query as this:
SELECT Parts.id
FROM (
SELECT DISTINCT parts_id
FROM Parts_Category
WHERE Parts_Category.category_id = '508'
OR Parts_Category.main_category_id = '508'
) pc
JOIN Parts
ON parts.id = pc.parts_id
AND Parts.status = 'A'
LEFT JOIN
Image
ON image.id = parts.image_id
, which will be more efficient if you have the following indexes:
Parts_Category (category_id, parts_id)
Parts_Category (main_category_id, parts_id)
| {
"pile_set_name": "StackExchange"
} |
Q:
Hooks placements in Drupal
I am trying to place some hooks, but I don't even think they are being called.
THEMENAME_menu_alter(&$items)
and
THEMENAME_user_view_access($account)
are the hooks I am placing in my template.php file. However, they don't seem to be reacting to it. And yes, I am converting the dummy THEMENAME placeholder to the name of my theme in use.
But my real question is: are these hooks just for use in Custom Modules? Or can they be called in from template.php too?
If its just for custom modules then I guess that would explain why it's not reacting. But even so how is one suppose to know if a certain hook is only for a module or not?
P.S: I have also tried clearing the cache several times.
A:
By Default you can consider all hooks can be extendible using custom modules...
Hook Documentation says
Hooks are how modules can interact with the core code of Drupal. They
make it possible for a module to define new urls and pages within the
site (hook_menu), to add content to pages (hook_block, hook_footer,
etc.), to set up custom database tables (hook_schema), and more.
In template.php you can override functions which are exposed by hook_theme or functions like theme_*
There exists a good documentation that explains which functions you can override using template.php..
| {
"pile_set_name": "StackExchange"
} |
Q:
How to implement thread-safe container with natural looking syntax?
Preface
Below code results in undefined behaviour, if used as is:
vector<int> vi;
...
vi.push_back(1); // thread-1
...
vi.pop(); // thread-2
Traditional approach is to fix it with std::mutex:
std::lock_guard<std::mutex> lock(some_mutex_specifically_for_vi);
vi.push_back(1);
However, as the code grows, such things start looking cumbersome, as everytime there will be a lock before a method. Moreover, for every object, we may have to maintain a mutex.
Objective
Without compromising in the syntax of accessing an object and declaring an explicit mutex, I would like to create a template such that, it does all the boilerplate work. e.g.
Concurrent<vector<int>> vi; // specific `vi` mutex is auto declared in this wrapper
...
vi.push_back(1); // thread-1: locks `vi` only until `push_back()` is performed
...
vi.pop () // thread-2: locks `vi` only until `pop()` is performed
In current C++, it's impossible to achieve this. However, I have attempted a code where if just change vi. to vi->, then the things work as expected in above code comments.
Code
// The `Class` member is accessed via `->` instead of `.` operator
// For `const` object, it's assumed only for read purpose; hence no mutex lock
template<class Class,
class Mutex = std::mutex>
class Concurrent : private Class
{
public: using Class::Class;
private: class Safe
{
public: Safe (Concurrent* const this_,
Mutex& rMutex) :
m_This(this_),
m_rMutex(rMutex)
{ m_rMutex.lock(); }
public: ~Safe () { m_rMutex.unlock(); }
public: Class* operator-> () { return m_This; }
public: const Class* operator-> () const { return m_This; }
public: Class& operator* () { return *m_This; }
public: const Class& operator* () const { return *m_This; }
private: Concurrent* const m_This;
private: Mutex& m_rMutex;
};
public: Safe ScopeLocked () { return Safe(this, m_Mutex); }
public: const Class* Unsafe () const { return this; }
public: Safe operator-> () { return ScopeLocked(); }
public: const Class* operator-> () const { return this; }
public: const Class& operator* () const { return *this; }
private: Mutex m_Mutex;
};
Demo
Questions
Is using the temporary object to call a function with overloaded operator->() leads to undefined behavior in C++?
Does this small utility class serve the purpose of thread-safety for an encapsulated object in all the cases?
Clarifications
For inter-dependent statements, one needs a longer locking. Hence, there is a method introduced: ScopeLocked(). This is an equivalent of the std::lock_guard(). However the mutex for a given object is maintained internally, so it's still better syntactically.
e.g. instead of below flawed design (as suggested in an answer):
if(vi->size() > 0)
i = vi->front(); // Bad: `vi` can change after `size()` & before `front()`
One should rely on below design:
auto viLocked = vi.ScopeLocked();
if(viLocked->size() > 0)
i = viLocked->front(); // OK; `vi` is locked till the scope of `viLocked`
In other words, for the inter-dependent statements, one should be using the ScopeLocked().
A:
Don't do this.
It's almost impossible to make a thread safe collection class in which every method takes a lock.
Consider the following instance of your proposed Concurrent class.
Concurrent<vector<int>> vi;
A developer might come along and do this:
int result = 0;
if (vi.size() > 0)
{
result = vi.at(0);
}
And another thread might make this change in between the first threads call to size() and at(0).
vi.clear();
So now, the synchronized order of operations is:
vi.size() // returns 1
vi.clear() // sets the vector's size back to zero
vi.at(0) // throws exception since size is zero
So even though you have a thread safe vector class, two competing threads can result in an exception being thrown in unexpected places.
That's just the simplest example. There are other ways in which multiple threads attempting to read/write/iterate at the same time could inadvertently break your guarantee of thread safety.
You mentioned that the whole thing is motivated by this pattern being cumbersome:
vi_mutex.lock();
vi.push_back(1);
vi_mutex.unlock();
In fact, there are helper classes that will make this cleaner, namely lock_guard that will take a mutex to lock in its constructor and unlock on the destructor
{
lock_guard<mutex> lck(vi_mutex);
vi.push_back(1);
}
Then other code in practice becomes thread safe ala:
{
lock_guard<mutex> lck(vi_mutex);
result = 0;
if (vi.size() > 0)
{
result = vi.at(0);
}
}
Update:
I wrote a sample program, using your Concurrent class to demonstrate the race condition that leads to a problem. Here's the code:
Concurrent<list<int>> g_list;
void thread1()
{
while (true)
{
if (g_list->size() > 0)
{
int value = g_list->front();
cout << value << endl;
}
}
}
void thread2()
{
int i = 0;
while (true)
{
if (i % 2)
{
g_list->push_back(i);
}
else
{
g_list->clear();
}
i++;
}
}
int main()
{
std::thread t1(thread1);
std::thread t2(thread2);
t1.join(); // run forever
return 0;
}
In a non-optimized build, the program above crashes in a matter of seconds. (Retail is a bit harder, but the bug is still there).
A:
This endeavor is fraught with peril and performance problems. Iterators generally depend on the state of the whole data structure and will usually be invalidated if the data structure changes in certain ways. This means that iterators either need to hold a mutex on the whole data structure when they're created, or you'll need to define a special iterator that carefully locks only the stuff it's depending on in the moment, which is likely more than the state of the node/element it's currently pointing at. And this would require internal knowledge of the implementation of what's being wrapped.
As an example, think about how this sequence of events might play out:
Thread 1:
void thread1_func(Concurrent<vector<int>> &cq)
{
cq.push_back(1);
cq.push_back(2);
}
Thread 2:
void thread2_func(Concurrent<vector<int>> &cq)
{
::std::copy(cq.begin(), cq.end(), ostream_iterator<int>(cout, ", "));
}
How do you think that would play out? Even if every member function is nicely wrapped in a mutex so they're all serialized and atomic, you're still invoking undefined behavior as one thread changes a data structure another is iterating over.
You could make creating an iterator also lock a mutex. But then, if the same thread creates another iterator, it should be able to grab the mutex, so you'll need to use a recursive mutex.
And, of course, that means that your data structure can't be touched by any other threads while one thread is iterating over it, significantly decreasing concurrency opportunties.
It's also very prone to race conditions. One thread makes a call and discovers some fact about the data structure that it's interested in. Then, assuming this fact is true, it makes another call. But, of course, the fact is no longer true because some other thread has poked it's nose in in between getting the fact and using the fact. The example of using size and then deciding whether or not to iterate over it is just one example.
A:
Is using the temporary object to call a function with overloaded operator->() leads to undefined behavior in C++
No. Temporaries are only destroyed at the end of the full expression that made them spring to life. And using a temporary object with an overloaded operator-> to "decorate" member access is exactly why the overloaded operator is defined the way it is. It is used for logging, performance measurement in dedicated builds and, like you self discovered, locking all member accesses to an encapsulated object.
The range based for loop syntax is not working in this case. It gives compilation error. What is the correct way to fix it?
Your Iterator function doesn't return an actual iterator as far as I can tell. Compare Safe<Args...>(std::forward<Args>(args)...); with the argument list Iterator(Class::NAME(), m_Mutex). What is Base when the argument in Args is deduced from Class::NAME()?
Does this small utility class serve the purpose of thread-safety for an encapsulated object in all the cases?
It looks fairly safe for simple value types. But of course that is contingent on all access being done via the wrapper.
For more complex containers, where iterator invalidation comes into consideration, then making a single member access atomic will not necessarily prevent race conditions (as was noted in the comments). I suppose you may create an iterator wrapper that locks the container for the duration of its lifetime... but then you lose most of the useful container API.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery unbind not working as i expected
I have this jquery
$('input#application_submit.bigbutton[value=Agree]').click(function(e){
e.preventDefault();
var reason = $('.agree_reason:visible');
var reason_text = $('.agree_reason:visible textarea');
if(reason.length == 0){
$('.agree').show();
}else{
if(reason_text.val() == ''){
$('.agree').show();
$('#application_agree').css('border', '1px solid #CC0000');
$('.agree_validation_message').show();
}else{
$('input#application_submit.bigbutton[value=Agree]').unbind();
$('input#application_submit.bigbutton[value=Agree]').click();
}
}
});
and all is great up until the unbind....what i need it to do is remove this handler and do the normal click event but its freezing up my browser because its in a infinite loop i guess....i ever tried the jQuery die fundtion and also no luck...any ideas
A:
You have to pass the event type to unbind
$('input#application_submit.bigbutton[value=Agree]').unbind("click");
Also, based on PeeHaa's comment, application_submit is the element id, and since elements in the dom are unique (or at least better be), you can simplify this to
$('#application_submit').unbind("click");
You're almost always better off selecting by a simple id like this, since jQuery can defer to the native document.getElementById under the covers.
Another improvement would be:
var reason = $('.agree_reason:visible');
var reason_text = $('textarea', reason); // it is faster to let jQuery search in context
| {
"pile_set_name": "StackExchange"
} |
Q:
Different stylesheet for different device
I have a question: how to automatically change website look based on device type? I know there is something like
@media screen and (max-width:720px){/*code for mobile here*/}
@media screen and (min-width:1280px) {/*code for PC here*/}
but I think it can cause problems on big resolution mobile devices and low resolution desktop monitors.
So I wonder is there any way of changing css file/selecting exact part of css code based on device type, like smartphone, tablet or PC?
Anything that works will help. If something is not clear, I will try to explain it better. If I'm wrong, correct me.
A:
You can use these:
// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
| {
"pile_set_name": "StackExchange"
} |
Q:
How to save a opened file in richtext box
txt file in my richtextbox and want to save the orginal file rather than save a new file (SaveAs). here is my code for saving the file
private void SaveMyFile_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
}
}
any help pleaseeee
A:
You should try adding the file name or FileInfo from which the rich text is loaded from. If the file has not been saved, prompt to save the file. Otherwise, save to the file info cached.
partial class YourForm : Form
{
string filePath;
private void SaveMyFile_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(filePath))
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
filePath = saveFile1.FileName;
}
else return;
}
try
{
richTextBox1.SaveFile(filePath, RichTextBoxStreamType.PlainText);
}
catch (Exception ee)
{
// Put exception handling code here
}
}
}
As per comment below, if you'd like a save as button, you can try the following:
partial class YourForm : Form
{
Button saveFileAsButton; // Add this using the Forms Designer
private void saveFileAsButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
try
{
richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
filePath = saveFile1.FileName;
}
catch (Exception ee)
{
// Put exception handling code here (e.g. error saying file cannot be saved)
}
}
}
}
Note how the setting of filePath is in the try block. In case the save failed, you don't want to lose your original file path.
If you form has a MenuStrip, I recommend moving the save functions into the menus.
(BTW, the type name for RTF in your filter would be better as "Rich Text Document".)
| {
"pile_set_name": "StackExchange"
} |
Q:
What insect is in the PHP bugs logo?
Well, maybe this is a question more suited to Stack Overflow, but anyway, I am curious, which insect is the one in the logo of the PHP bugs site? Is it an actual insect or just a generic "bug"?
It seems like some kind of Hemiptera for me, probably some kind of "true bug". A quick google search about these insects and I found the Hemiptera suborder Heteroptera, and this critter is probably from this group.
I tried to search by the image in google images, but only found the logo itself, in the same low resolution is the image above (I was not able to find a better version of it). I tried to remove the background from the image then, but still I didn't get any photo of the possible species of this logo.
EDIT: this was the PHP bugs logo up until 24th July 2017; the next day it was changed to another different "bug". This question is about the former logo, not the current one.
A:
It is an actual insect, Lethocerus americanus, also known as Giant Water Bug. See:
Matches the colors, body shape and small eyes and head. And yes, they are very annoying. As expected from real bugs. You know, like the first one.
A:
Most probably it is Boxelder bug, since their other logo clearly depicts it as seen here
As per wikipedia
The boxelder bug (Boisea trivittata) is a North American species of true bug.
Trivittata is from the Latin tri (three) + vittata (banded).
Their congregation habits and excreta can annoy people; for this reason, they are considered nuisance pests.
| {
"pile_set_name": "StackExchange"
} |
Q:
MFC: CButton highlighting for a group of radio buttons
I know that I can create an integer variable for a group of radio buttons, set it to an integer, and then call UpdateData(FALSE) to make the window highlight the appropriate radio button control. However, I would like to perhaps use a CButton control instead, but I don't know how to set the CButton state so that a particular radio button of the group is checked. Is it even possible to do so for MFC? Thanks in advance.
A:
As I only need to set the states upon startup or reset states, I linked the CButton control with the appropriate id flag for the CButton control before switch them to on. The CButton control can later contain other values as onclicked() handlers are used for me to map selected radio button values properly.
void UserControls::DoDataExchange(CDataExchange* pDX)
{
...
// Mapping the integer variables to the Radio control for proper
// displaying
// not the id of the first radio button of the group for both of them
DDX_Control(pDX, IDC_NOBTL, nobCtrl);
DDX_Control(pDX, IDC_UIHARD, uiCtrl);
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
controller function in angular js module doesn't work for the delete operation
I am developing a new library management software with spring boot,angular js, and MongoDB as backend. I want to perform crud operation on MongoDB with that application and for that I referring some open source project with that I can perform create and read operations successfully but can't perform delete and update operations so how can perform I also made some changes for delete update but can't perform with that so tell me the changes have to perform in order to perform delete.I added this as my own in mybooks.html but the element is not deleting.for that made some changes in mybooks.html and hello.js for delete operation but the element is not deleting
<td><form ng-submit="controller.delete()">
<div class="form-group">
<input type="submit" class="btn btn-default btn-lg" value="Delete">
</div>
</form></td>
bookrestcontroller.java
package com.sezin.controller;
import com.sezin.model.Book;
import com.sezin.repository.BookRepository;
import com.sezin.repository.UserAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;
import java.util.List;
/**
* Created by sezin on 3/23/16.
*/
@RestController
@RequestMapping("/api/books")
public class BookRestController {
@Autowired
BookRepository repository;
@Autowired
UserAccountRepository userAccountRepository;
@RequestMapping(method = RequestMethod.GET)
public List<Book> getAllBooks(){
return repository.findAll();
}
@RequestMapping(value = "/getByTitle/{title}", method = RequestMethod.GET)
public Book getBookByTitle(@PathVariable String title){
return repository.findByTitle(title);
}
@RequestMapping(value = "/getByAuthor/{author}", method = RequestMethod.GET)
public List<Book> getBooksByAuthor(@PathVariable String author){
return repository.findByAuthor(author);
}
@RequestMapping(value ="/getAll/{userName}", method = RequestMethod.GET)
public List<Book> getBooksByUserName(@PathVariable String userName){
return repository.findByUserName(userName);
}
@RequestMapping(value ="/add", method = RequestMethod.POST)
public @ResponseBody Book create(@RequestBody Book book){
if( userAccountRepository.findByUsername(book.getUserName()) != null &&
repository.findByTitle(book.getTitle()) == null){
return repository.save(book);
}
else
return null;
}
@RequestMapping(method = RequestMethod.DELETE, value = "{id}")
public void delete(@PathVariable String id){
repository.delete(id);
}
@RequestMapping(method = RequestMethod.PUT, value = "{id}")
public Book update(@PathVariable String id, @RequestBody Book book){
Book updated = repository.findOne(id);
updated.setAuthor(book.getAuthor());
updated.setTitle(book.getTitle());
updated.setYear(book.getyear());
return repository.save(book);
}
}
securitycontroller.java
@Override
protected void configure(HttpSecurity http) throws Exception {
/* http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/", "/register.html", "/account").permitAll()
.anyRequest().authenticated().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);*/
http.authorizeRequests().antMatchers("/index.html", "/home.html", "/login.html", "/", "/register.html", "/account", "/api","/delete").permitAll()
.anyRequest().fullyAuthenticated().and().
httpBasic().and().
csrf().disable();
}
mybooks.html
<tr>
<th>BooK_id</th>
<th>BooK_title</th>
<th>BooK_author</th>
<th>BooK_year</th>
<th>update</th>
</tr>
<tr ng-repeat="message in controller.messages">
<td>{{message.id}}</td>
<td>{{message.title}}</td>
<td>{{message.author}}</td>
<td>{{message.year}}</td>
<td><form ng-submit="remove(message.id)" ng-controller="books">
<div class="form-group">
<input type="submit" class="btn btn-default btn-lg" value="Delete">
</div>
</form></td>
</tr>
hello.js
/**
* Created by sezin on 3/22/16.
*/
angular.module('hello', ['ngRoute', 'ngResource', 'ngCookies'])
.config(function($routeProvider, $httpProvider){
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs: 'controller'
}).when('/login', {
templateUrl : 'login.html',
controller : 'navigation',
controllerAs: 'controller'
}).when('/register', {
templateUrl : 'register.html',
controller : 'register',
controllerAs: 'controller'
}).when('/mybooks', {
templateUrl : 'mybooks.html',
controller : 'books',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
})
.controller('home', function($http, $cookies) {
var self = this;
$http.get('/resource/').success(function(data){
self.greeting = data;
self.currentUserName = $cookies.get("username");
//self.messages = [];
self.saveBook = function(){
//var BookRecord = $resource('/account/', {username : self.currentUserName});
//BookRecord.save(self.book);
var request = {
userName: self.currentUserName,
title: self.book.title,
author: self.book.author,
year: self.book.year
};
$http.post('api/books/add', request).success(function(data){
if(data){
self.success = true;
} if(data == null){
self.success = false;
}
console.log(data);
//self.messages.push({type:'success', msg: 'Book Saved!'});
}). error(function(err){
console.log(err);
});
};
});
})
.controller('books', function($http, $cookies){
var self = this;
self.messages = [];
self.currentUserName = $cookies.get("username");
$http.get('api/books/getAll/' + self.currentUserName).success(function(data){
self.messages = data;
console.log(data);
});
self.remove = function(messageId){
$http.delete('messageId');
};
})
.controller('navigation', function($rootScope, $http, $location, $cookies) {
var self = this;
var authenticate = function(credentials, callback) {
var headers = credentials ? {authorization: "Basic "
+ btoa(credentials.username + ":" + credentials.password)} :{};
$http.get('/user/', {headers : headers}).success(function(data){
if(data.name){
$rootScope.authenticated = true;
$rootScope.username = data.username;
if (typeof callback == "function") {
callback() && callback();
}
} else{
$rootScope.authenticated = false;
if (typeof callback == "function") {
callback() && callback();
}
}
})
};
authenticate();
self.credentials = {};
self.login = function(){
authenticate(self.credentials, function () {
if($rootScope.authenticated){
$location.path("/");
$rootScope.username = self.credentials.username;
$cookies.put("username", $rootScope.username);
self.error = false;
} else{
$location.path("/login");
self.error = true;
}
});
};
self.logout = function(){
$http.post('logout', {}).finally(function(){
$rootScope.authenticated = false;
$location.path("/");
});
}
})
.controller('register', function($resource, $rootScope, $location){
var self = this;
self.register = function(){
var User = $resource('/account');
User.save(self.user, function(data){
self.success = data;
});
};
});
A:
Change the DELETE method as GET, pass id param in pathvariable, find the entity by it's id from DB. then delete the entity.
Controller
@RequestMapping(value="/delete/{id}", method = RequestMethod.GET)
public void delete(@PathVariable String id){
Book book = repository.findById(id);
repository.delete(book);
}
JS
$http.get('api/books/delete/'+yourBookId).success(function(data){
// success
}). error(function(err){
// error
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular New Router remove /# from URL
I'm on angular 1.4.6 and new router version 0.5.3 and wanted to remove the '/#' from the url. Can't seem to find anything about it on the Internet.
Edit: $locationProvider.html5mode(true);
gives the following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
TypeError: $locationProvider.html5mode is not a function
A:
You can remove Hashtag from URLs only in browsers that support HTML5 History API. As you can see here, it's not supported in IE9, so in that case it will fallback to Hashtags.
Having said that, to make your URLs pretty in browsers that do support, you can enable html5Mode using $locationProvider config like below.
angular.module('myApp', [])
.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
In addition to this, you need to define the base URL of your application for the angular-router to identify the routes. If your URL is
http://localhost:8080/myApp/#showLogin
http://localhost:8080/myApp/#showHomePage
then you need to define the base URL using <base> tag like below
<head>
<base href="/myApp">
</head>
Hope this helps :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating a generic reference table: is a collection the right method?
I've created a pair of reusable subroutines that work together to save a file in different extensions as the occasion warrants.
The first Sub receives the directory path, the file name, and the desired Excel extension. It then calls the second Sub to find the correct Excel FileFormat number and use it to save the file in the new format:
Sub SaveFileWithNewExtension(DirectoryPath As String, NameOfFile As String, ExtensionToUse As String)
Dim ExcelFileFormatNumber As String
GetExcelFormatNumber ExtensionToUse, ExcelFileFormatNumber
ActiveWorkbook.SaveAs DirectoryPath & "\" & NameOfFile & ExtensionToUse, FileFormat:=ExcelFileFormatNumber
End Sub
The second sub is mostly a reference for Excel FileFormats I will use. For the FileFormat reference I've stored both the FileFormat Number and Name in an arrays keyed to the different file extensions, all stored in a collection I can add to as needed:
Sub GetExcelFormatNumber(Extension As String, Optional Number As String, Optional ExcelFormat As String)
'http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
'http://www.rondebruin.nl/mac/mac020.htm
Dim ExtensionReference As New Collection
ExtensionReference.Add Array("51", "xlOpenXMLWorkbook"), ".xlsx"
ExtensionReference.Add Array("52", "xlOpenXMLWorkbookMacroEnabled"), ".xlsm"
ExtensionReference.Add Array("50", "xlExcel12"), ".xlsb"
ExtensionReference.Add Array("56", "xlExcel8"), ".xls"
On Error GoTo NoMatch:
ExcelFormat = ExtensionReference.Item(Extension)(1)
Number = ExtensionReference.Item(Extension)(0)
Exit Sub
NoMatch:
msgbox "No Matching Extension was Found in the ExcelExtensionsAndNumbers Collection"
End Sub
Keeping arrays in a collection like this seems rather clunky and inelegant, which makes me think I've done this the hard way.
Here's my question:
Is there a better way to store information like for use by other subs? Or phrased another way: Do you have a favorite way of abstracting data (like the FileFormat codes in this example) so it can be used repeatedly without remembering and rewriting it every time?
Code has been revised to use Cases rather than a collection and to better handle errors (as gently suggested by Siddharth Rout's rewrite of the code). This works, and the case structure makes more sense to my eye:
Public Sub SaveFileWithNewExtension(DirectoryPath As String, NameOfFile As String, ExtensionToUse As String)
Dim ExcelFileFormatNumber As String
GetExcelFormatNumber ExtensionToUse, ExcelFileFormatNumber
If ExcelFileFormatNumber <> "" Then
ActiveWorkbook.SaveAs DirectoryPath & "\" & NameOfFile & ExtensionToUse, FileFormat:=ExcelFileFormatNumber
Else
msgbox "Invalid file extension. Case does not exist."
End If
End Sub
Public Sub GetExcelFormatNumber(ExtensionToFind As String, Optional Number As String, Optional ExcelFormat As String)
'reference - http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
'reference - http://www.rondebruin.nl/mac/mac020.htm
Select Case ExtensionToFind
Case ".xlsx": Number = "51"
ExcelFormat = "xlOpenXMLWorkbook"
Case ".xlsm": Number = "52"
ExcelFormat = "xlOpenXMLWorkbookMacroEnabled"
Case ".xlsb": Number = "50"
ExcelFormat = "xlExcel12"
Case ".xls": Number = "56"
ExcelFormat = "xlExcel8"
Case ".csv": Number = "6"
ExcelFormat = "xlCSV"
Case Else: Number = ""
ExcelFormat = ""
End Select
End Sub
A:
I agree. For just 4 Extns, array would be an overkill. I would rather use Select Case in a function. See the below
UNTESTED
Sub SaveFileWithNewExtension(DirectoryPath As String, _
NameOfFile As String, _
ExtensionToUse As String)
Dim ExcelFileFormatNumber As Long
ExcelFileFormatNumber = GetExcelFormatNumber(ExtensionToUse)
If ExcelFileFormatNumber <> 0 Then
ActiveWorkbook.SaveAs _
DirectoryPath & _
"\" & _
NameOfFile & ExtensionToUse, _
FileFormat:=ExcelFileFormatNumber
Else
MsgBox "Invalid Extenstion:"
End If
End Sub
Function GetExcelFormatNumber(Extn As String) As Long
'~~> FileFormat
Select Case UCase(Extn)
Case "XLS": GetExcelFormatNumber = 56
Case "XLSX": GetExcelFormatNumber = 51
Case "XLSM": GetExcelFormatNumber = 52
Case "XLSB": GetExcelFormatNumber = 56
'~~> Add for more... like csv etc
End Select
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Call to undefined relationship in Eloquent, Laravel 5.7
I am four hours in this. I just cannot see the problem. I using Postgres not Mysql.
class ValorVariacao
public $table = 'valores_variacoes';
protected function tipoVariacao()
{
return $this->belongsTo('App\TipoVariacao', 'tipo_atributo_id', 'id');
}
The other class of the relationship.
class TipoVariacao
public $table = 'tipos_variacoes';
public function valorVariacao() {
return $this->hasMany('App\ValorVariacao', 'id', 'tipo_atributo_id');
}
The relevant structure of the table
valores_variacoes tipos_variacoes
id id
tipo_atributo_id
Calling this I get undefined relationship:
return ValorVariacao::with('tipoVariacao')->get();
error:
Call to undefined relationship [tipoVariacao] on model [App\ValorVariacao].
A:
The relationship method has to be public:
public function tipoVariacao()
{
return $this->belongsTo('App\TipoVariacao', 'tipo_atributo_id', 'id');
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Couldn't match expected type ‘Integer’ with actual type ‘m0 Integer’
So I'm new to Haskell and I'm writing a basic function which takes 3 integers as arguments and returns how many are equal.
howManyEqual :: Int->Int->Int->Integer
howManyEqual x y z =
if x == y && x == z then return 3
else if x == y && x /= z then return 2
else if x == z && x /= y then return 2
else if y == z && y /= x then return 2
else return 0
But Im getting the following error:
Prelude> :load ex4.1_2.hs
[1 of 1] Compiling Main ( ex4.1_2.hs, interpreted )
ex4.1_2.hs:11:34:
Couldn't match expected type ‘Integer’
with actual type ‘m0 Integer’
In the expression: return 3
In the expression:
if x == y && x == z then
return 3
else
if x == y && x /= z then
return 2
else
if x == z && x /= y then
return 2
else
if y == z && y /= x then return 2 else return 0
I have same error at return 2 and return 0 as well.
What kind of data type is m0 Integer and what do I need to do to fix this?
Any help would be appreciated. Cheers!!
A:
Delete all the return keywords:
howManyEqual :: Int -> Int -> Int -> Integer
howManyEqual x y z =
if x == y && x == z then 3
else if x == y && x /= z then 2
else if x == z && x /= y then 2
else if y == z && y /= x then 2
else 0
In Haskell, return isn't a keyword, but a function with the type Monad m => a -> m a. It's mainly used from within code blocks in do notation to return values 'wrapped' in a Monad instance.
The howManyEqual method doesn't return a monadic value, but rather a normal, scalar Integer, so return isn't required. When you use return anyway, the compiler expects the returned value to be part of some Monad instance that it calls m0 in the error message, but since the function has the explicitly declared return type Integer, there's no way to reconcile these.
By the way, you can relax the type declaration to:
howManyEqual :: (Eq a, Num t) => a -> a -> a -> t
A:
Some further off topic information about the haskell syntax:
There is nothing wrong with using else if in haskell, but it's not common. Haskell supports guards | which is some what equivalent to else if. However, if x then y else z is mosty used for a binary condition, not to gather several different conditions.
| x == y = 5 = if x ==y then 5
Therefore your code could be expressed in the following and more preferable way
howManyEqual :: Int -> Int -> Int -> Integer
howManyEqual x y z
| x == y && x == z = 3
| x == y && x /= z = 2
| x == z && x /= y = 2
| y == z && y /= x = 2
| otherwise = 0
| {
"pile_set_name": "StackExchange"
} |
Q:
POST http://localhost:3000/api/courses/[object%20Object]/units 404 (Not Found)
(Only my 3rd post here, so please excuse any blatant issues).
The following is my Unit component, a child of a Course component (courses has_many units).
import React from 'react';
import { connect } from 'react-redux';
import { getUnits, addUnit, updateUnit } from '../reducers/units';
import { Container, Header, Form } from 'semantic-ui-react';
class Units extends React.Component {
initialState = { name: ''}
state = { ...this.initialState }
componentDidUpdate(prevProps) {
const { dispatch, course } = this.props
if (prevProps.course.id !== course.id)
dispatch(getUnits(course.id))
}
handleSubmit = (e) => {
debugger
e.preventDefault()
debugger
const unit = this.state
const { dispatch } = this.props
if (unit.id) {
debugger
dispatch(updateUnit(unit))
} else {
debugger
dispatch(addUnit(unit))
this.setState({ ...this.initialState })
}
}
handleChange = (e) => {
const { name, value } = e.target
this.setState({ [name]: value })
}
units = () => {
return this.props.units.map( (unit, i) =>
<ul key={i}>
<li key={unit.id}> {unit.name}</li>
<button>Edit Module Name</button>
<button>Delete Module</button>
</ul>
)
}
render() {
const { name } = this.state
return (
<Container>
<Header as="h3" textAlign="center">Modules</Header>
{ this.units() }
<button>Add a Module</button>
<Form onSubmit={this.handleSubmit}>
<Form.Input
name="name"
placeholder="name"
value={name}
onChange={this.handleChange}
label="name"
required
/>
</Form>
</Container>
)
}
}
const mapStateToProps = (state) => {
return { units: state.units, course: state.course }
}
export default connect(mapStateToProps)(Units);
The following is its reducer:
import axios from 'axios';
import { setFlash } from './flash'
import { setHeaders } from './headers'
import { setCourse } from './course'
const GET_UNITS = 'GET_UNITS';
const ADD_UNIT = 'ADD_UNIT';
const UPDATE_UNIT = 'UPDATE_UNIT';
export const getUnits = (course) => {
return(dispatch) => {
axios.get(`/api/courses/${course}/units`)
.then( res => {
dispatch({ type: GET_UNITS, units: res.data, headers: res.headers })
})
}
}
export const addUnit = (course) => {
return (dispatch) => {
debugger
axios.post(`/api/courses/${course}/units`)
.then ( res => {
dispatch({ type: ADD_UNIT, unit: res.data })
const { headers } = res
dispatch(setHeaders(headers))
dispatch(setFlash('Unit added successfully!', 'green'))
})
.catch( (err) => dispatch(setFlash('Failed to add unit.', 'red')) )
}
}
export const updateUnit = (course) => {
return (dispatch, getState) => {
const courseState = getState().course
axios.put(`/api/courses/${course.id}/units`, { course })
.then( ({ data, headers }) => {
dispatch({ type: UPDATE_UNIT, course: data, headers })
dispatch(setCourse({...courseState, ...data}))
dispatch(setFlash('Unit has been updated', 'green'))
})
.catch( e => {
dispatch(setHeaders(e.headers))
dispatch(setFlash(e.errors, 'red'))
})
}
}
export default (state = [], action) => {
switch (action.type) {
case GET_UNITS:
return action.units;
case ADD_UNIT:
return [action.unit, ...state]
case UPDATE_UNIT:
return state.map( c => {
if ( c.id === action.unit.id )
return action.unit
return c
})
default:
return state;
}
};
Note: My reducer is working for my getUnits and rendering the units properly.
Note also: when I try to submit a new unit, it ignores all of the debuggers in my handleSubmit and the debuggers in my addUnits (in the reducer), but somehow renders the flash message of "Failed to add units".
Then the console logs the error seen in the title of this post.
I raked my routes and my post is definitely supposed to go to the route as it is.
I have tried passing in the unit and the course in various ways without any change to the error.
How can it hit the flash message without hitting any of the debuggers?
How do I fix this [object%20Object]issue?
Thanks in advance!
A:
The variable course in the following line
axios.get(`/api/courses/${course}/units`)
is an object. When you try to convert an object to a string in JavaScript, [object Object] is the result. The space is then converted to %20 for the URL request.
I would look at the contents of the course variable. Likely, what you actually want in the URL is something inside of course. Perhaps course.id.
If you are still having issues, you'll need to explain what value should go in the URL between /courses/ and /units, and where that data exists.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как правильно подключать js код при помощи require
Из-за недостаточного опыта я не могу в полной мере описать вопрос, но надеюсь, что Вы поймете.
В file.js я подключаю другой файл
var test = require('./test.js');
var test1 = new test.Test1();
var test2 = new test.Test2();
А в test.js пишу типа
module.exports = {
Test1: Test1,
Test2: Test2
};
var Test1 = function(){
};
var Test2 = function(){
};
Но я не совсем уверен, что так делать правильно... Можно так делать или я смысл не понимаю?
Дополнение:
// у меня в коде написано вот так
modele.exports = {
Test: Test
};
var Test = function(){
// ...
};
// но Вы делаете вот так -
module.exports = {
Test: Test
};
function Test(){
//...
};
// и при этом делаете акцент на этом различии,
// говоря, что нужно делать, как у Вас.
//
// И я спрашиваю, а в чем различия между
// var Test и function Test ?
A:
может new test() ?
| {
"pile_set_name": "StackExchange"
} |
Q:
"May I help the next customer on line."
Leaving aside the regional dialect that might cause someone to say "on line" or "in line," isn't the line what establishes who the next customer is -- and so therefore redundant? Wouldn't a simple "May I help the next customer?" suffice?
I know line-forming is not something done in all cultures, but I'm fairly certain it is in most predominantly English-speaking ones. We form lines without being told or prompted. Even very small children can do this.
A:
I'd say it is nearly redundant; and this is why I often see people just say "I can help the next customer" without adding "in line" (quite common in Canada).
I can think of at least one reason you might, though. By adding "in line" they are indicating to all customers that the line is functioning as the queuing system, and that this is how the next customer should be determined.
It fully establishes that the next person being served comes from the lineup of people, so it isn't acceptable for a random person to walk up and try to cut in. It is still basically redundant though, because most people are aware of the implicit "in line" after the phrase "I can help the next customer".
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I get the list of strings obtained by deleting one character from a given string?
Giving a string I want to create a list of strings in which I have all the strings formed after deleting one character from the initial string. Ex mama -> [ama, mma, maa, mam].
I tried this :
delete1 :: String -> [String]
delete1 xs = [delete c (c:xs) |c <- xs]
but it does not change anything. How can I do this ?
A:
This should work for you:
delete :: String -> [String]
delete [] = []
delete (x:xs) = xs : map (x:) (deleted1 xs)
| {
"pile_set_name": "StackExchange"
} |
Q:
Arduino Mega and LP621024D70LL
I'm intending to try a LP621024D70LL (128 KB SRAM memory, 32 pins) on an Arduino Mega.
However, I now see there is no library for it ... I wonder how hard it is to access it? I can miss 32 digital pins (the Mega has enough), however, I'm a bit worried about having to write a library, especially since I do not have any gear like an oscilloscope.
Would it be easy to use the library of the more knwn 32K256 or 23LC1024 as basis? (where I also have no experience with btw).
A:
That's so old I can't find a datasheet for it. If you know the pinout then you know more than me at the moment. Chances are it's a standard 8-bit CPU interface.
Writing:
Set the address on the address pins, set the data to write on the data pins, enable the chip, and pulse WR.
Reading:
Set the address on the address pins, enable the chip, and while pulsing the OE pin read the data pins.
And no, you can't really use a serial SRAM chip library as a basis - the operation is completely different.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using REST and GraphQL in different parts of a single web app
I'm creating a web app and I'm wondering if it's possible to create it using both REST and GraphQl. I don't mean I wan't to wrap REST in graphql. It is a web app with a variety of functionalities and graphql would be best suited towards the blog portion of the app but we've already constructed the rest of it using REST. Would it be possible/bad practice to use them for the respective parts of the app?
A:
I don't see any problem with that. Just make sure to create a single API abstraction that would internally handle both cases so that the app itself is not concerned about that (in case you'll want to go all-in with GraphQL at some point).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to NSLog only the string that I pass, not the other info?
NSLog(@"example");
will ouput :
2012-09-13 04:54:48.128 MyApp[94652:a0f]: example
on the console.
Is there a way I can get it to only output:
example
A:
If you define this macro and use it instead of NSLog it will only output what you specify.
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
| {
"pile_set_name": "StackExchange"
} |
Q:
Triggering a subroutine for a shared mailbox in a macro inside Outlook 2010
I have a code that triggers the subroutine Items_ItemAdd when emails come in. It works perfectly for my own personal email inbox. Here is the code I use, it's written in the default Outlook module called ThisOutlookSession:
Option Explicit
Public WithEvents Items As Outlook.Items
Public Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Public Sub Items_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
MsgBox "Replace the code for this message with your subroutine"
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
The problem is that I have tried countless ways to make this work for a shared email inbox which my boss just added me into the group. F.y.i. after he had added me to the list of users of this shared email I had to add it by File->Info->Account Settings->Account Settings->Change->More Settings->Advanced->add and there I had to write the name of the shared email-After trying all kinds of solutions to make the subroutine work for the shared email, e.g.
http://social.msdn.microsoft.com/Forums/office/en-US/b85f08f0-4f6b-4663-a75e-272350c07d2c/vba-outlook-2010-how-to-detecte-the-new-email-in-shared-mailbox?forum=outlookdev
http://www.slipstick.com/developer/code-samples/process-items-shared-mailbox/
http://www.outlookcode.com/article.aspx?id=62
non of it was helpful for me because when I implement it don't get any error messages, it's like it's impossible for me to have an event triggered for this shared email inbox. My most hopeful attempt is where I figured out by using the vba debugger watch how to locate the Items for the shared email inbox and I replaced the line below:
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
with a new line to point to the Items of the shared email inbox:
Set Items = objNS.Folders.Item(4).Items.Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
To me it seems to be the right Items so I thought this would defiantly work, but the same story, nothing happens. The problem is, I have a code that works perfectly for my email's inbox, why can't I make it work for a shared email's inbox?
A:
What I don't see is any calls to NameSpace.GetSharedDefaultFolder. If you pass the Inbox owner's email address as an argument to that method, you will then get the proper Folder object for that shared folder. Then you can get Folder.Items and thus access the Items.ItemAdd event.
NameSpace.GetSharedDefaultFolder Method (Outlook)
http://msdn.microsoft.com/en-us/library/office/ff869575(v=office.15).aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
PRAW: can you receive data from two seperate keyword lists in the same message?
I currently have a reddit bot that receives keywords from a subreddit and then sends me a notification on Slack.
The current code for sending me the notification is
for kw in keywords:
if kw.lower() in comment.body.lower(): # case insensitive check
already_alerted_submissions.append(comment.submission.id)
msg = '[Keyword *{0}* detected](http://www.reddit.com{1})'.format(
kw, comment.permalink)
slack_data = {'text': msg, 'mrkdwn': True}
So it is currently getting a list of keywords from
keywords = ['camera', 'nikon', 'canon', 'campus'] # case insensitive
I was wondering if it was possible to have two separate keyword lists in the file such as the following
keywords = ['camera', 'nikon', 'canon', 'campus'] # case insensitive
keywords_color = ['red', 'blue', 'green', 'black'] # case insensitive
And if the word "camera" was detected in a thread, it would post a message just like it does currently.
But if in the same comment, it detected a keyword from both
keywords AND and keywords_color
It could post the same message in slack but with another line saying something similar to "Color was detected"
So in the examples above the message in slack would look like the following.
1. [Keyword *camera* detected]
(http://www.reddit.com/r/camera/comments/9yg8mt/goodcameras
I just got a great CAMERA today, it is awesome
Or if it detected both "keywords" and "keywords_color" it would look like the following
2. 1. [Keyword *camera* detected]
(http://www.reddit.com/r/camera/comments/9yg8mt/goodcameras
I just got a great CAMERA today, it is a RED one and its awesome
**Colour was detected**
Would this be possible? any help would be appreciated!
The full scrip for the file is here:
def main():
alerted_comments = get_list_from_pickle('alerted_comments.pickle')
try:
for comment in comment_stream:
if comment.id in alerted_comments:
continue
if comment.author: # if comment author hasn't deleted
if comment.author.name in ignore_users:
continue
for kw in keywords:
if kw.lower() in comment.body.lower(): # case insensitive check
alerted_comments.append(comment.id)
while len(alerted_comments) > 100:
del alerted_comments[0]
with open('alerted_comments.pickle', 'wb') as fp:
pickle.dump(alerted_comments, fp)
for kw in keywords:
if kw.lower() in comment.body.lower(): # case insensitive check
alerted_comments.append(comment.submission.id)
msg = '[Keyword *{0}* detected](http://www.reddit.com{1})'.format(
kw, comment.permalink)
slack_data = {'text': msg, 'mrkdwn': True}
response = requests.post('https://hooks.slack.com/services/BE72P09A9/xxxxxxxxx78',
data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
if response.status_code != 200:
raise ValueError('Request to slack returned an error %s, the response is:\n%s' % (
response.status_code, response.text))
except Exception as e:
print('There was an error: ' + str(e))
sleep(60) # wait for 60 seconds before restarting
main()
if __name__ == '__main__':
main()
A:
This is untested, but here you go:
import json
import time
import requests
class SlackError(Exception):
# This isn't quite how I would handle this, so for now it's
# just a hint of more to learn.
pass
MSG_TEMPLATE = """[Keyword *{keyword}* detected]
(https://www.reddit.com{permalink})
{comment_body}"""
SLACK_WEBHOOK = 'https://hooks.slack.com/services/BE72P09A9/xxxxxxxxx78'
def main(*, save_path):
keywords = ...
color_keywords = ...
ignore_users = ...
comment_stream = ...
with open(save_path, 'r') as fp:
alerted_comments = json.load(fp)
for comment in comment_stream:
if comment.id in alerted_comments:
continue
if comment.author: # if comment author hasn't deleted
if comment.author.name in ignore_users:
continue
if any(kw.lower() in comment.body.lower() for kw in keywords):
found_kws = [kw for kw in keywords if kw.lower() in comment.body.lower()]
msg = MSG_TEMPLATE.format(
keyword=found_kws[0],
permalink=permalink,
comment_body=comment.body
)
if any(kw.lower() in comment.body.lower() for kw in color_keywords):
msg += "\nColour was detected"
slack_data = {'text': msg, 'mrkdwn': True}
response = requests.post(
SLACK_WEBHOOK,
data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code == 200:
# Moving this here so you don't miss a comment
# because of an error. It does mean other errors
# could potentially cause a repeat message. There
# are ways to handle that.
alerted_comments.append(comment.id)
if len(alerted_comments) > 100:
alerted_comments = alerted_comments[-100:]
with open(save_path, 'w') as fp:
json.dump(alerted_comments, fp)
else:
# You'll probably want to be more discerning than "not 200",
# but that's fine for now.
raise SlackError(
'Request to Slack returned an error %s, the response is:\n%s' % (
response.status_code, response.text))
if __name__ == '__main__':
while True:
try:
main(save_path='alerted_comments.json')
except Exception as e:
print('There was an error: {}'.format(str(e)))
time.sleep(60) # wait for 60 seconds before restarting
Let me know if you have any questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the centroid of the boomarang shaped region for the parabolas $y^2=-4(x-1)$ and $y^2=-2(x-2)$
I know the formulas, I only need assistance setting up the initial integral.
So my order of integration must be $\mathrm{d}x$ $\mathrm{d}y$. Then if we solve the parabola for $x$ the new integral we get is:
$\int_{-2}^2 \int_{(-y^2/{2})+2}^{(y^2/{2})+2}\mathrm{d}x$ $\mathrm{d}y$.
I'm pretty confident this is correct but some reassurance would be helpful! I'm graphing the parabolas on my calculator but its still a bit confusing to see..
A:
The centroid $(\bar{x},\bar{y})$ of a region bounded by the graphs of continuous functions $f$ and $g$ such that $f(y)\ge g(y)$ on the interval $[a,b]$, $a\le y\le b$, is given by
$$\begin{cases}
\bar{x}=\frac{1}{A}\int_{a}^{b}\left[\frac{f(y)+g(y)}{2}\right]\left[f(y)-g(y)\right]\mathrm{d}y\\
\bar{y}=\frac{1}{A}\int_{a}^{b}y\left[f(y)-g(y)\right]\mathrm{d}y,
\end{cases}$$
where $A$ is the area of the region (given by $A=\int_{a}^{b}\left[f(y)-g(y)\right]\mathrm{d}y$). This is in complete analogy to the formulas for the coordinates of the centroid of a region bounded by graphs of functions of $x$ as opposed to $y$, described here.
For the sake of this problem, $f(y)=2-\frac{y^2}{2}$, $g(y)=1-\frac{y^2}{4}$, $a=-2$, and $b=2$. The area is then:
$$\begin{align}
A
&=\int_{-2}^{2}\left[f(y)-g(y)\right]\mathrm{d}y\\
&=\int_{-2}^{2}\left[\left(2-\frac{y^2}{2}\right)-\left(1-\frac{y^2}{4}\right)\right]\mathrm{d}y\\
&=\int_{-2}^{2}\left(1-\frac{y^2}{4}\right)\mathrm{d}y\\
&=\frac83.
\end{align}$$
By symmetry the $y$-coordinate of the centroid is $\bar{y}=0$. The $x$-coordinate is:
$$\begin{align}
\bar{x}
&=\frac{1}{A}\int_{a}^{b}\left[\frac{f(y)+g(y)}{2}\right]\left[f(y)-g(y)\right]\mathrm{d}y\\
&=\frac38\int_{-2}^{2}\left[\frac{3-\frac{3y^2}{4}}{2}\right]\left(1-\frac{y^2}{4}\right)\mathrm{d}y\\
&=\frac{9}{16}\int_{-2}^{2}\left(1-\frac{y^2}{4}\right)^2\mathrm{d}y\\
&=\frac65.
\end{align}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to factor $9x^2-80x-9$?
How do I factor a trinomial like this? I'm having a lot of difficulty. How do I deal with the $9x^2$?
A:
Hint $\ \ $ Reduce to factoring a polynomial that is $\,\rm\color{#c00}{monic}\,$ (lead coeff $=1)$ as follows:
$$\quad\ \ \begin{eqnarray}
f &\,=\,& \ \ 9\ x^2-\ 80\ x\ -\,\ 9\\
\Rightarrow\ 9f &\,=\,& (9x)^2\! -80(9x)-81\\
&\,=\,& \ \ \ \ \color{#c00}{X^2\!- 80\ X\ -\,\ 81},\,\ \ X\, =\, 9x\\
&\,=\,& \ \ \ \,(X-81)\ (X+\,1)\\
&\,=\,& \ \ \ (9x-81)\,(9x+1)\\
\Rightarrow\ f\,=\, 9^{-1}(9f) &\,=\,& \ \ \ \ \ (x\ -\ 9)\,(9x+1)\\
\end{eqnarray}$$
If we denote our factoring algorithm by $\,\cal F,\,$ then the above transformation is simply
$$\cal F f\, = a^{-1}\cal F\, a\,f\quad\,$$
Thus we've transformed by $ $ conjugation $\,\ \cal F = a^{-1} \cal F\, a\ \,$ the problem of factoring non-monic polynomials into the simpler problem of factoring monic polynomials.
This is sometimes called the AC method. It works for higher degree polynomials too. As above, we can reduce the problem of factoring a non-monic polynomial to that of factoring a monic polynomial by scaling by a $ $ power of the lead coefficient $\rm\:a\:$ then changing variables: $\rm\ X = a\:x$
$$\begin{eqnarray} \rm\: a\:f(x)\:\! \,=\,\:\! a\:(a\:x^2 + b\:x + c) &\,=\,&\rm\: X^2 + b\:X + \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\smash[t]{\overbrace{ac}^{\rm\qquad\ \ \ \ \ {\bf AC-method}}}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! =\, g(X),\ \ \ X = a\:x \\
\\
\rm\: a^{n-1}(a\:x^n\! + b\:x^{n-1}\!+\cdots+d\:x + c) &\,=\,&\rm\: X^n\! + b\:X^{n-1}\!+\cdots+a^{n-2}d\:X + a^{n-1}c
\end{eqnarray}$$
After factoring the monic $\rm\,g(X)\, =\, a^{n-1}f(x),\,$ we are guaranteed that the transformation reverses to yield a factorization of $\rm\:f,\ $ since $\rm\ a^{n-1}$ must divide into the factors of $\rm\ g\ $ by Gauss' Lemma, i.e. primes $\,p\in\rm\mathbb Z\,$ remain prime in $\rm\,\mathbb Z[X],\,$ so $\rm\ p\ |\ g_1(x)\:g_2(x)\,$ $\Rightarrow$ $\,\rm\:p\:|\:g_1(x)\:$ or $\rm\:p\:|\:g_2(x).$
This method also works for multivariate polynomial factorization, e.g. it applies to this question.
Remark $\ $ Those who know university algebra might be interested to know that this works not only for UFDs and GCD domains but also for integrally-closed domains satisfying
$\qquad\qquad$ Primal Divisor Property $\rm\ \ c\ |\ AB\ \ \Rightarrow\ \ c = ab,\ \ a\ |\: A,\ \ b\ |\ B$
Elements $c$ satisfying this are called primal. One easily checks that atoms are primal $\!\iff\!$ prime. Also products of primes are also primal. So "primal" may be viewed as a generalization of the notion "prime" from atoms (irreducibles) to composites.
Integrally closed domains whose elements are all primal are called $ $ Schreier rings by Paul Cohn (or Riesz domains, because they satisfy a divisibility form of the Riesz interpolation property). In Cohn's Bezout rings and their subrings
he proved that if $\rm\:D\:$ is Schreier then so too is $\rm\,D[x],\:$ by using a primal analogue of Nagata's Lemma: an atomic domain $\rm\:D\:$ is a UFD if some localization $\rm\:D_S\:$ is a UFD, for some monoid $\rm\:S\:$ generated by primes. These primal and Riesz interpolation viewpoints come to the fore in a refinement view of unique factorization, which proves especially fruitful in noncommutative rings (e.g. see Cohn's 1973 Monthly survey Unique factorization domains).
In fact Schreier domains can be characterized equivalently by a suitably formulated version of the above "factoring by conjugation" property. This connection between this elementary AC method and Schreier domains appears to have gone unnoticed in the literature.
A:
You can do it like this:
First, write the polynomial like this:
$$\frac{9(9x^2-80x-9)}{9}$$
Then expand the numerator as
$$81x^2-720x-81$$
which can be written in the form
$$(9x)^2-80(9x)-81$$
If we let $y=9x$, then the polynomial becomes
$$\frac{y^2-80y-81}{9}$$
Can you continue from here?
A:
Use the fact that: $$-80 = 1 - 81 = 1 -9\times9$$
In general, if you want to find $A,B$ such that $(ax+A)(x+B) = ax^2+bx+c$, you need them to satisfy:
$$aB + A= b,\ AB = c$$
If you assume integer factors, you can see $A,B$ must be either $3,-3$ or $\pm 9,\mp 1$. Only of of these three options gives $b = -80$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap core javascript suddenly not working
I'm a beginner here, and currently developing a web application. My situation is for few months i had using this Bootstrap core javascript source and suddenly today the console shows error which I completely dont know how to solve it and it is affecting and messing up my web application page.
This is the Bootstrap js source that i'm using
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
This is the image of the error from the web console
A:
My problem above is solved by inserting new links for the CSS and JS of bootstrap latest update. You can refer here for the guide on using latest bootstrap 4.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could a hacker replace Bitcoin QT in some Linux repository and steal Bitcoins?
Bitcoin QT, being a Linux application, is updated regularly when the application in the repository is being updated (For example, apt-get upgrade on Debian).
Theoretically, if a hacker could get into some Linux repository, he could replace the application with a malicious one that steals both the private key and the wallet file and send it to a remote server (effectively stealing all the Bitcoins from most the users).
If possible, even through social engineering, the incentive for such hack is enormous.
How likely/unlikely that to happen?
A:
You know you don't have to trust the repo. The developers of Bitcoin-QT actually recommend using their binaries rather than the distro's. So you can just keep up to date with those. Official binaries are signed with a Bitcoin-QT developer's PGP keys.
A:
Software distributors typically have authentication mechanisms to prevent an attacker from inserting malicious versions of their software.
In the case of Debian and its derivatives, there are two steps.
The binaries and data for bitcoin-qt are distributed as a .deb file. A cryptographic hash (currently md5, sha1 and sha256) of this file is contained in the Packages list that apt-get uses to determine which packages are available. If an attacker modifies the .deb file, say by breaking into one of the Debian mirror servers, the hash will not match and apt-get will refuse to install the package.
The Packages file is also distributed by the same servers, so an attacker could modify it so that the hash listed there matches the malicious .deb. However, the Packages file is accompanied by a signature produced with Debian's master private key, so this signature would not match and apt-get would refuse to proceed.
Thus in order to pull this off, the attacker would not only have to get access to a Debian mirror server, but also to the Debian master signing key, which should be well protected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display current user metadata on Wordpress page
So I have a Wordpress website, and I want to be able to display the current logged in user's data on a page. Previously, I had been able to find a snippet of code that would go go in functions.php and I would be able to use a shortcode like [currentuser_(specific_metadata_tag)] and it would display it. I cannot find the stack exchange question that had this code. Is it possible for anyone to repost the link to that question, or maybe give me a piece of code to implement into the functions file so I can use a shortcode to access current user data? I think it should be fairly straightforward, the function would just get current user id then look under a specific metadata and pull data, then the short code would just display.
In any sense, I am not fully familiar with coding in PHP and so if I can receive any help, I would really appreciate it!
A:
You can try below snippet of code. i have develop shortcode you can take reference from it.
function current_user_data_func( $atts ) {
extract( shortcode_atts( array(
'metakey' => '',
'user_field' => '',
), $atts) );
ob_start();
if(is_user_logged_in())
{
$current_user = wp_get_current_user();
$c_user_id = $current_user->ID;
if(!empty($metakey))
{
$value = get_user_meta( $c_user_id, $metakey, true);
echo $value;
}
if(!empty($user_field))
{
echo $current_user->{"$user_field"};
}
}
else
{
echo "User Not Logged In";
}
return ob_get_clean();
}
add_shortcode( 'current_user_data', 'current_user_data_func' );
How to use :
User_fields :
user_login
user_email
user_firstname
user_lastname
display_name
# In template
echo do_shortcode( '[current_user_data metakey="nickname"]' );
echo do_shortcode( '[current_user_data user_field="user_email"]' );
#in content
[current_user_data metakey="first_name"]
[current_user_data user_field="user_email"]
meta key return only single value if you have stored array value in meta key then you have to remove 'true' from get_user_meta( $c_user_id, $metakey, true); and get value from that array variable $value.
Let me know if this helps to you!
| {
"pile_set_name": "StackExchange"
} |
Q:
PDO Query Update with multi conditions?
I need your help with a little problem that has caused me to get stuck on that project for 2 days now.
I have a query like this:
UPDATE table SET name='$name', surname='$surname'
WHERE cid=$cid AND counter=$count";
and I need to write it in PDO syntax. Now, I know how to do it with one condition but I cant get it to work with multi-conditions (like WHERE cid=$cid AND counter=$count)
Can someone help me out how to make this work if i have more than one condition on the query?
Thanks.
A:
Try this, I think it should work:
$query = "UPDATE table SET name='$name', surname='$surname' WHERE cid = :cid AND counter = :counter";
$stmt = $db->prepare($query);
$stmt->BindValue(':cid', $cid, PDO::PARAM_STR);
$stmt->BindValue(':counter', $counter, PDO::PARAM_STR);
$stmt->execute();
Edit: $db is where you call your function to connect to your database.
| {
"pile_set_name": "StackExchange"
} |
Q:
Preg match forward slashes
I am trying to match 008/
preg_match('/008\\//i', '008/', $matches);
preg_match('/008\//i', '008/', $matches);
My question is why do both of the regular expressions work. I would expect the second to work, but why does the double backslash one work?
A:
Because \\ in PHP strings means "escape the backslash". Since \/ doesn't mean anything it doesn't need to be escaped (even though it's possible), so they evaluate to the same.
In other words, both of these will print the same thing:
echo '/008\\//i'; // prints /008\//i
echo '/008\//i'; // prints /008\//i
The backslash is one of the few characters that can get escaped in a single quoted string (aside from the obvious \'), which ensures that you can make a string such as 'test\\' without escaping last quote.
| {
"pile_set_name": "StackExchange"
} |
Q:
Add button column in a databound datagridview
i have a datagridview. i bound it to a list. now i want to show a column at the end of it. but that column apprear in wrong possition.
this is my code
grdPatientAppointment.DataSource = lst;
grdPatientAppointment.Columns["ID"].Visible = false;
//grdPatientAppointment.Columns["AdmitDate"].Visible = false;
//grdPatientAppointment.Columns["DischargeDate"].Visible = false;
grdPatientAppointment.Columns["AppointmentID"].Visible = false;
grdPatientAppointment.Columns["PatientrName"].DisplayIndex = 0;
grdPatientAppointment.Columns["Age"].DisplayIndex = 1;
grdPatientAppointment.Columns["Address"].DisplayIndex = 2;
grdPatientAppointment.Columns["ContactNo"].DisplayIndex = 3;
grdPatientAppointment.Columns["Dieseas"].DisplayIndex = 4;
grdPatientAppointment.Columns["AppointmentDate"].DisplayIndex = 5;
DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn();
btnColumn.HeaderText = "Treat";
btnColumn.Text = "Treat";
btnColumn.UseColumnTextForButtonValue = true;
grdPatientAppointment.Columns.Insert(6,btnColumn);
here is output:
but i want that button to the end of datagrid view
A:
Add column instead of inserting it to the GridView. It will automaticallyy append it to the end of column collection.
grdPatientAppointment.Columns.Add(btnColumn);
| {
"pile_set_name": "StackExchange"
} |
Q:
Using AngularJS dependency inside a template
I would like to set the max-height of a div to be $window.innerHeight. The following code fails:
<div ng-style="{'max-height': $window.innerHeight}" style="overflow-y: auto">
My walk-around was to use a scope variable:
$scope.divnHeight = $window.innerHeight;
<div ng-style="{'max-height': divHeight}" style="overflow-y: auto">
Is there any way to achieve a ng-style to $window binding?
Thanks
A:
You're missing 'px' in the ng-style
See Plunker: http://plnkr.co/edit/eqKz9wgyzm8LOz6pZAN0?p=preview
To answer your question, no... any variable you wish to use in HTML must be a scope variable.
If the window height is changing, then you can use a watcher to bind the variable to the window height:
$scope.$watch(function(){
return $window.innerHeight; // the thing to watch
}, function(newValue, oldValue) { // the function to run when the value changes
console.log(newValue);
$scope.divnHeight = $window.innerHeight;
});
Update:
try adding this into your controller, this just registers a function to fire when you resize:
window.onresize = function(event) {
console.log("Fire resize");
$scope.divnHeight = $window.innerHeight;
};
Also, the size may stay the same because you are using max-height rather than height, in which case the height depends on the content, try using height and see if that makes a difference:
<div ng-style="{'height': divHeight + 'px'}" style="overflow-y: auto">
| {
"pile_set_name": "StackExchange"
} |
Q:
Resizing images in jquery not working on all images
I want it to scale all instances of the td img.standingslogo but it's not working properly
jsfiddle - https://jsfiddle.net/ze5ebnw7/13/
$(window).load(function(){
image = []
$('td img.standingslogo').each(function() {
imageWidth = $(this).width();
image[$(this).index()] = imageWidth;
});
$(window).resize(function() {
$('td img.standingslogo').hide();
$('td img.standingslogo').each(function() {
tdWidth = $(this).parent().width();
imgWidth = image[$(this).index()];
if (imgWidth>=tdWidth) {$(this).css({width:tdWidth});} else {$(this).css({width:imgWidth});}
$(this).show();
});
}).resize();
});
A:
This working now
$(window).load(function(){
image = [];
i=0;
$('.standingslogo').each(function() {
imageWidth = $(this).width();
image[i] = imageWidth;
i++
});
$(window).resize(function() {
$('.standingslogo').hide();
i=0;
$('.standingslogo').each(function() {
tdWidth = $(this).parent().width();
imgWidth = image[i];
if (imgWidth>=tdWidth) {$(this).css({width:tdWidth});} else {$(this).css({width:imgWidth});}
$(this).show();
i++
});
}).resize();
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Fixed width table with second column dynamic width and ellipsis
I need a two column table that has only one row. The data in the first column should always display in full, but the second column should resize and the data in it should ellipse if it can't fit in the cell. If the first column expands to fit its data, the second column should contract, all while keeping the table width the same.
I tried to fix width of table and all kinds of ways to achieve this with CSS, but I couldn't figure out. It does seem like it's something that should be achievable.
This is how the table should behave with different data in the first column:
.ellipsis {
width: 190px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
<h3>table width always the same</h3>
<table border="1">
<tr>
<th>
Column1
</th>
<th>
Column2
</th>
</tr>
<tr>
<td>
<label>Display in full</label>
</td>
<td>
<label class="ellipsis">Ellipsis this if length is too long</label>
</td>
</tr>
</table>
A:
Like I mention in the comments, it can be achieved using flex-box.
.parent has display: flexbox
Column 1 has white-space: nowrap to make it fit its content.
Column 2 has flex-grow so it will take all the remain space.
.parent {
display: flex;
width: 350px;
border: 1px solid;
}
.header {
text-align: center;
font-weight: bold;
border-bottom: 1px solid;
}
.parent > div:first-child {
white-space: nowrap;
border-right: 1px solid;
}
.parent > div:last-child {
flex-grow: 1;
}
.parent div:last-child {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.parent > div > div {
padding: 1px;
}
<div class="parent">
<div>
<div class="header">Column1</div>
<div>Display in full</div>
</div>
<div>
<div class="header">Column 2</div>
<div>Ellipsis this if length is too long</div>
</div>
</div>
https://jsbin.com/ferixiq/3/edit?html,css,output
| {
"pile_set_name": "StackExchange"
} |
Q:
Optimizing mysql my.cnf - memory usage is dangerously high
I have tunet up mysql by following some tips on the internet.
but the websites are loading slow and time time-to-first-byte is very high. therefore i started investigation and as far as i see, it is casued by mysql and high memory usage
every time i make changes to the my.cnf according to the suggestions i get from
./mysqltuner.pl AND ./tuning-primer.sh
it gives another suggestions. Actually some values should have balance to each other. I hope someone have an idea how to get high performance usage of mysql and in the same time, take care of the server health
MariaDB server version: 10.0.20-MariaDB-log MariaDB Server
Server information:
Intel Core i7-3770
2x HDD 3,0 TB SATA
4x RAM 8192 MB DDR3
Cloudlinux + Cpanel installed
Apache/2.4.16 + eAccelerator + mod_pagespeed
SLOW QUERIES
Error: slow_query_log_file=/var/log/mysql/log-slow-queries.log
Current long_query_time = 10.000000 sec.
You have 1944 out of 25401054 that take longer than 10.000000 sec. to complete
**Your long_query_time seems to be fine**
BINARY UPDATE LOG
The binary update log is NOT enabled.
**You will not be able to do point in time recovery**
See http://dev.mysql.com/doc/refman/10.0/en/point-in-time-recovery.html
WORKER THREADS
Current thread_cache_size = 8
Current threads_cached = 6
Current threads_per_sec = 0
Historic threads_per_sec = 0
**Your thread_cache_size is fine**
MAX CONNECTIONS
Current max_connections = 151
Current threads_connected = 6
Historic max_used_connections = 43
The number of used connections is 28% of the configured maximum.
**Your max_connections variable seems to be fine.**
No InnoDB Support Enabled!
MEMORY USAGE
Max Memory Ever Allocated : 20.96 G
Configured Max Per-thread Buffers : 24.81 G
Configured Max Global Buffers : 13.89 G
Configured Max Memory Limit : 38.70 G
Physical Memory : 31.12 G
**Max memory limit exceeds 90% of physical memory**
KEY BUFFER
Current MyISAM index space = 29 M
Current key_buffer_size = 384 M
Key cache miss rate is 1 : 870
Key buffer free ratio = 78 %
**Your key_buffer_size seems to be fine**
QUERY CACHE
Query cache is enabled
Current query_cache_size = 512 M
Current query_cache_used = 222 M
Current query_cache_limit = 1.00 G
Current Query cache Memory fill ratio = 43.41 %
Current query_cache_min_res_unit = 4 K
**MySQL won't cache query results that are larger than query_cache_limit in size**
SORT OPERATIONS
Current sort_buffer_size = 16 M
Current read_rnd_buffer_size = 8 M
**Sort buffer seems to be fine**
JOINS
./tuning-primer.sh: line 402: export: `2097152': not a valid identifier
Current join_buffer_size = 128.00 M
You have had 10199 queries where a join could not use an index properly
join_buffer_size >= 4 M
**This is not advised
You should enable "log-queries-not-using-indexes"
Then look for non indexed joins in the slow query log.**
OPEN FILES LIMIT
Current open_files_limit = 16162 files
The open_files_limit should typically be set to at least 2x-3x
that of table_cache if you have heavy MyISAM usage.
**Your open_files_limit value seems to be fine**
TABLE CACHE
Current table_open_cache = 8000 tables
Current table_definition_cache = 8000 tables
You have a total of 7347 tables
You have 8000 open tables.
**Current table_cache hit rate is 21%
, while 100% of your table cache is in use
You should probably increase your table_cache**
TEMP TABLES
Current max_heap_table_size = 16 M
Current tmp_table_size = 16 M
Of 592173 temp tables, 36% were created on disk
**Perhaps you should increase your tmp_table_size and/or max_heap_table_size
to reduce the number of disk-based temporary tables
Note! BLOB and TEXT columns are not allow in memory tables.
If you are using these columns raising these values might not impact your
ratio of on disk temp tables.**
TABLE SCANS
Current read_buffer_size = 16 M
Current table scan ratio = 74 : 1
**read_buffer_size is over 8 MB there is probably no need for such a large read_buffer**
TABLE LOCKING
Current Lock Wait ratio = 1 : 4366
**You may benefit from selective use of InnoDB.
If you have long running SELECT's against MyISAM tables and perform
frequent updates consider setting 'low_priority_updates=1'
If you have a high concurrency of inserts on Dynamic row-length tables
consider setting 'concurrent_insert=ALWAYS'.**
root@my [~]# ./mysqltuner.pl
>> MySQLTuner 1.4.0 - Major Hayden <[email protected]>
>> Bug reports, feature requests, and downloads at http://mysqltuner.com/
>> Run with '--help' for additional options and output filtering
[!!] Currently running unsupported MySQL version 10.0.20-MariaDB-log
[OK] Operating on 64-bit architecture
-------- Storage Engine Statistics -------------------------------------------
[--] Status: +ARCHIVE +Aria +BLACKHOLE +CSV +FEDERATED +InnoDB +MRG_MyISAM
[--] Data in MyISAM tables: 82M (Tables: 925)
[--] Data in InnoDB tables: 7G (Tables: 6334)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 52)
[--] Data in MEMORY tables: 0B (Tables: 2)
[!!] Total fragmented tables: 159
-------- Security Recommendations -------------------------------------------
[OK] All database users have passwords assigned
-------- Performance Metrics -------------------------------------------------
[--] Up for: 14h 42m 18s (25M q [480.374 qps], 81K conn, TX: 71B, RX: 6B)
[--] Reads / Writes: 98% / 2%
[--] Total buffers: 13.9G global + 168.3M per thread (151 max threads)
**[!!] Maximum possible memory usage: 38.7G (124% of installed RAM)**
[OK] Slow queries: 0% (1K/25M)
[OK] Highest usage of available connections: 28% (43/151)
[OK] Key buffer size / total MyISAM indexes: 384.0M/29.8M
[OK] Key buffer hit rate: 99.9% (12M cached / 14K reads)
[OK] Query cache efficiency: 44.9% (20M cached / 44M selects)
**[!!] Query cache prunes per day: 2013573**
[OK] Sorts requiring temporary tables: 0% (1K temp sorts / 1M sorts)
**[!!] Joins performed without indexes: 10207
[!!] Temporary tables created on disk: 58% (345K on disk / 592K total)**
[OK] Thread cache hit rate: 98% (1K created / 81K connections)
[OK] Table cache hit rate: 21% (8K open / 38K opened)
[OK] Open file limit used: 12% (1K/16K)
[OK] Table locks acquired immediately: 99% (10M immediate / 10M locks)
[OK] InnoDB buffer pool / data size: 10.0G/7.7G
[OK] InnoDB log waits: 0
-------- Recommendations -----------------------------------------------------
General recommendations:
**Run OPTIMIZE TABLE to defragment tables for better performance
Reduce your overall MySQL memory footprint for system stability
Increasing the query_cache size over 128M may reduce performance
Adjust your join queries to always utilize indexes
When making adjustments, make tmp_table_size/max_heap_table_size equal
Reduce your SELECT DISTINCT queries without LIMIT clauses**
Variables to adjust:
*** MySQL's maximum memory usage is dangerously high ***
*** Add RAM before increasing MySQL buffer variables ***
query_cache_size (> 512M) [see warning above]
join_buffer_size (> 128.0M, or always use indexes with joins)
tmp_table_size (> 16M)
max_heap_table_size (> 16M)
And here is the my.cnf settings which i have set
[mysqld]
#http://blog.secaserver.com/2011/08/mysql-recommended-my-cnf-settings-innodb-engine/
# GENERAL #
default-storage-engine=InnoDB
tmpdir=/tmp_mysql
group_concat_max_len=10000000
local-infile=1
# LOGGING #
slow_query_log = 1
slow_query_log_file=/var/log/mysql/log-slow-queries.log
long_query_time = 10
log-error = /var/log/error.log
log-queries-not-using-indexes
# CACHES AND LIMITS AND SAFETY #
max_allowed_packet = 512M #16
query_cache_size = 512M
query_cache_limit = 1024M
thread_cache_size = 8
table_definition_cache = 8000
table_open_cache = 8000
sort_buffer_size = 16M
read_buffer_size = 16M #2
read_rnd_buffer_size = 8M
join_buffer_size = 128M
thread_concurrency = 0 # Try number of CPU's*2 for thread_concurrency
key_buffer = 256M
# INNODB #
innodb_file_per_table=1
innodb_file_format = Barracuda
innodb_sort_buffer_size = 128M
innodb_data_home_dir = /var/lib/mysql
innodb_log_group_home_dir = /var/lib/mysql
innodb_thread_concurrency=0
innodb_flush_method=O_DIRECT
innodb_lock_wait_timeout = 120
innodb_buffer_pool_size=10G
innodb_log_file_size = 1536M # Set .. innodb_log_file_size to 25 % of innodb_buffer_pool_size -You can set .. innodb_buffer_pool_size up to 50 - 80 %
innodb_log_buffer_size = 3072M
innodb_additional_mem_pool_size = 20M
#innodb_read_io_threads=16
#innodb_write_io_threads=16
#innodb_io_capacity=500
#innodb_flush_log_at_trx_commit=1
#sync_binlog=1
#innodb_data_file_path = ibdata1:2000M;ibdata2:10M:autoextend
# MyISAM #
key_buffer_size = 384M
myisam_sort_buffer_size = 64M
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
[myisamchk]
key_buffer_size = 256M
sort_buffer_size = 256M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
A:
Summary
Don't worry about the memory "problem"
Look at the slowlog - you have some serious optimizations to deal with
Why thousands of tables? This is probably a design flaw.
Ignore the comments about fragmentation.
Convert the rest of your tables to InnoDB.
Details
Your long_query_time seems to be fine
No, crank long_query_time down to 2 and keep an eye on the slow queries.
No InnoDB Support Enabled!
[--] Data in InnoDB tables: 7G (Tables: 6334)
Those statments contradict each other!
InnoDB is the preferred engine. The other outputs seem to say that InnoDB is in use. (Bug in the script?)
Max memory limit exceeds 90% of physical memory
[!!] Maximum possible memory usage: 38.7G (124% of installed RAM)
There is no forumla without flaws. You are probably OK.
Your key_buffer_size seems to be fine
The key_buffer should be the largest memory usage in a MyISAM_only server. But you have a tiny database, so no problem.
The innodb_buffer_pool_size should be the largest memory user when using InnoDB.
Your current values are good:
innodb_buffer_pool_size = 10G
key_buffer_size = 384M
Current query_cache_size = 512 M
[OK] Query cache efficiency: 44.9% (20M cached / 44M selects)
[!!] Query cache prunes per day: 2013573
The 512M hurts performance; limit it to 50M.
The other two lines say that the QC is not that useful, and has a lot pruning overhead.
Conclusion: Cautiously try
query_cache_size = 0
query_cache_type = OFF
./tuning-primer.sh: line 402: export: `2097152': not a valid identifier
Bug in the script?
You should enable "log-queries-not-using-indexes"
No, it just clutters the slowlog.
A one-line table with no index, or even a 100-row table with no index is likely to be "fast enough".
Instead, look at the existing slow queries to decide what should be worked on.
You have a total of 7347 tables
(Tables: 6334)
That's a design flaw in your database.
Of 592173 temp tables, 36% were created on disk
Again, the slowlog can help identify the worst queries. Then we can work on fixing them, either by adding an index or by reformulating the query.
[!!] Total fragmented tables: 159
Run OPTIMIZE TABLE to defragment tables
Ignore -- virtually all tables are virtually always fragmented. No action item here.
[480.374 qps]
A good reason to go to InnoDB.
[!!] Joins performed without indexes: 10207
[!!] Temporary tables created on disk: 58% (345K on disk / 592K total)**
Gotta see the slowlog entries. Let's start with the 10 second ones you have already caught.
#innodb_flush_log_at_trx_commit=1
Suggest setting to 2.
(This is the first time I have seen tuning-primer.sh; I am not impressed.)
These two blogs are likely to be useful:
MyISAM to InnoDB
Cookbook for creating INDEXes
| {
"pile_set_name": "StackExchange"
} |
Q:
.css() for 'animation-delay' attribute cannot be set with variable
I cannot use a variable to change the 'animation-delay' css property.
Note: This will work for something like background color or other animation attributes. The animation-delay will also work with a string '10s' but not a variable--even when the variable is explicitly set to a string.
var animationDelayTime = '10s'
$('.my-animation-class').css({
'animation-delay' : animationDelayTime
})
The this other method also does not work:
$('.my-animation-class').css(
'animation-delay', animationDelayTime
)
This currently works:
$('.my-animation-class').css({
'animation-delay' : '10s'
})
jsfiddle
A:
I created jsfiddle - this is working for me. Maybe you have an issue elsewhere?
<div class="my-animation-class"></div>
JS
$(document).ready(function(){
var animationDelayTime = '10s'
$('.my-animation-class').css({
'animation-delay' : animationDelayTime
});
});
CSS
.my-animation-class{
width:200px;
height:200px;
background:#ff0000;
-webkit-animation: mymove 5s infinite;
-webkit-animation-delay: 2s;
animation: mymove 5s infinite;
position:relative;
}
@-webkit-keyframes mymove {
from {left: 0px;}
to {left: 200px;}
}
@keyframes mymove {
from {left: 0px;}
to {left: 200px;}
}
http://jsfiddle.net/sthAngels/3bc30t9k/
| {
"pile_set_name": "StackExchange"
} |
Q:
MessageBox in Windows Phone 8.1
I want to show a MessageBox to the user when the back button has been pressed on the hardware, but it's simply doesn't work. I tried these variations, but I never see the MessageBox:
// VARIATION 1
IAsyncResult mbResult = Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox("Warning", "Are you sure you want to leave this page?",
new string[] { "Yes", "No" }, 0, Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, null, null);
mbResult.AsyncWaitHandle.WaitOne();
int? yesNo = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(mbResult);
if (yesNo.HasValue)
{
if (yesNo.Value == 0)
{
// Yes pressed
}
else
{
// No pressed
}
}
// VARIATION 2
MessageBoxResult mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning", MessageBoxButton.OKCancel);
if(mbr == MessageBoxResult.OK)
{
// OK pressed
}
else
{
// Cancel pressed
}
If I write e.Cancel = true to the OnBackKeyPress event then I can't leave the page, so the code is executing, but I never see the MessageBox:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
What can be the problem, or what I'm doing wrong?
A:
As I can see you are targeting Windows Phone 8.1 Silverlight, then answer to this question is still actual, as at MSDN"
Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows Phone OS 7.1
In Windows Phone 8, if you call Show in OnBackKeyPress(CancelEventArgs) or a handler for the BackKeyPress event, the app will exit.
The solution is also given at MSDN. Shortly - run your Messeagebox.Show on Dispatcher:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBoxResult mbr = MessageBox.Show("Are you sure you want to leave this page?", "Warning", MessageBoxButton.OKCancel);
if(mbr == MessageBoxResult.OK)
{ OK pressed }
else
{ Cancel pressed }
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Split a listview into multiple columns
I am populating a ListView with a DataTable from the code behind. The problem is, that the ListView is becoming too long with too many items.
I am wondering, how can I make this:
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6
Into this:
Item 1 Item 4
Item 2 Item 5
Item 3 Item 6
Maybe I'm overlooking something, but I can't seem to find the answer.
Please not that I want to keep it in one ListView, so I'm not looking to split the items and put them into multiple ListViews.
Solution: Use a DataList in stead of a ListView. See Tim's answer.
A:
Use a DataList instead. It has a RepeatDirection and RepeatColumns properties. The former would be RepeatDirection.Vertical and the latter 2 in your case.
Gets or sets the number of columns to display in the DataList control.
| {
"pile_set_name": "StackExchange"
} |
Q:
Advice on "Factory" Pattern Implementation
I'm refactoring some code around a couple of ASP.NET Web Forms pages and decided to try out a variation of the Abstract Factory pattern of my own design. I need to create an implementer of an abstract class based on what query string value is available.
Here's (a simplified version of) what I have right now:
internal static class Factory
{
public static AbstractClass Create(NameValueCollection queryString)
{
if (queryString["class1"] != null)
{
return new Class1(queryString["class1"]);
}
if (queryString["class2"] != null)
{
return new Class2(queryString["class2"]);
}
if (queryString["class3"] != null)
{
return new Class3(queryString["class3"]);
}
return null;
}
}
I don't know how I feel about this implementation. It certainly is better than what was there before, but I have a strong sense this could be improved some how.
So now, in the relevant pages, I can simply do this:
AbstractClass item = Factory.Create(Request.QueryString);
item.DoStuff();
Does anyone have any suggestions? Or would this be considered good as-is?
A:
I Think you should do it more generic:
public static class Factory
{
static Dictionary<String, Func<String, Abstract>> classes;
public static Abstract GetInstance(String s){
if(!classes.ContainsKey(s)) throw new Exception();
Func<String, Abstract> create=classes[s];
return create(s);
}
static Factory ()
{
classes=new Dictionary<String, Func<String, Abstract>>(){
{"class1", (x)=>new Class1(x)},
{"class2", (x)=> new Class2(x)}
};
}
}
This code is way more readable.
You have the static constructor block, where you register the factory methods according to the keys. And the GetInstance-Method shrinks to 3 lines, of which one is a purely guarding clause.
Edit: modified after Mat's Mug's hint.
P.S: Oh, I forgot to mention, that you really never should return null.
Better a) throw an Exception or b) use a NullObject.
A:
Passing a query string, or any string really, to the factory is troubling.
Why I avoid strings:
typos
CasEinG
Presumed encoding/structure can be problematic.
IMHO the ideal will be to pass a parameter to the factory that unambiguously tells what to construct. As is, the factory is making gross assumptions about the content & validity of the incoming query string. But there is no telling what free-form text is in it.
The client code should evaluate & validate the query string and then pass the appropriate thing to the factory. And IMHO do not pass a string. Use enums. enums are:
type safe
avoid typos
self documenting - all the possible class-types are defined here.
Query string validation - now that we have a definitive list of all possible class-types we can verify the query string contents against the enum
intelisense in visual studio
Design thoughts
Below is not the Abstract Factory Pattern per se. We are not creating factories of factories. The point of a factory is to separate "complex construction (code)" from the using class. The more complex the constructions "the more factory we need".
Simple? then a static (or not) method w/in the client class is ok.
Longish & somewhat complex? a separate class.
Use the Factory in many places? a separate class might be best.
Many variations of each class-type? Perhaps a full-blown abstract factory design. etc., etc, and etc.
IMHO, making the Factory class an instance, static, or singleton is your call.
The Dictionary Examples
Other examples using a dictionary are interesting. I'd use an enum for the key, not strings. overall it feels like the reflection/abstraction aspects are wasted as it's all internal and you still have to "open the factory", i.e. modify it, to add/delete class-types.
The dictionary is necessary only because we pass the entire query string to the factory. Again, Tell the factory what to build don't make it try to guess (see above about "gross assumptions"). The calling client is the absolute best place with the proper context to decide what to build.
Making the factory parse the query string - and therefore handle problems - is violating the single responsibility principle.
.
internal public class Factory{
public AbstractClass Create(abstracts makeThis) {
AbstractClass newClass;
switch(makeThis) {
case abstracts.class1:
newClass = BuildClass1();
break;
case abstracts.class2:
newClass = BuildClass2();
break;
// and so on.
default:
throw new NotImplementedException();
break;
}
return newClass;
}
// build methods here.
}
public enum abstracts {class1, class2, class3}
public class Client{
AbstractClass factoryBuiltThing;
Factory classFactory = new Factory();
// put some error handling in here
protected bool ParseQueryString(string queryString, out buildThis) {}
// put some error handing here too.
protected abstracts DeriveAbstractEnum(string theDesiredClass){};
public void BuildSomething(string queryString) {
string buildThis = string.Empty;
abstracts whatToBuild;
if (ParseQueryString (queryString, out buildThis)) {
whatToBuild = DeriveAbstractEnum(buildThis);
factoryBuiltThing = classFactory.Create(whatToBuild);
}else {
throw new NotImplementedException(
string.format("The query string is crap: {0}", queryString));
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Fill nulls until certain column value in Pandas
I have the following time series dataframe. I would like to fill the missing values with the previous value. However i would only want to fill the missing values until a certain value is reached. This value is recorded in a different column. So the columns i wanna fill will be different for each row. How can i do this?
So, given this dataframe.
import numpy as np
import pandas as pd
df = pd.DataFrame([[1, 2 ,np.nan,np.nan,np.nan , 2009], [1, 3 , np.nan , np.nan , np.nan , 2010], [4, np.nan , 7 , np.nan,np.nan , 2011]], columns=[2007,2008,2009,2010,2011 , fill_until])
Input dataframe
2007 2008 2009 2010 2011 fill_until
1 2 NaN NaN NaN 2009
1 3 NaN NaN NaN 2010
4 Nan 7 NaN NaN 2011
Output dataframe:
2007 2008 2009 2010 2011
1 2 2 NaN NaN
1 3 3 3 NaN
4 4 7 7 7
A:
Use ffill + where -
m = df.columns[:-1].values <= df.fill_until.values[:, None]
df.iloc[:, :-1].ffill(axis=1).where(m)
2007 2008 2009 2010 2011
0 1.0 2.0 2.0 NaN NaN
1 1.0 3.0 3.0 3.0 NaN
2 4.0 4.0 7.0 7.0 7.0
Details
Use NumPy's broadcasting to obtain a mask of values to be filled upto based on the fill_until column.
m = df.columns[:-1].values <= df.fill_until.values[:, None]
Or,
m = (df.columns[:-1].values[:, None] <= df.fill_until.values).T
m
array([[ True, True, True, False, False],
[ True, True, True, True, False],
[ True, True, True, True, True]], dtype=bool)
Now, slice out all but the last column, and call ffill along the first axis -
i = df.iloc[:, :-1].ffill(axis=1)
i
2007 2008 2009 2010 2011
0 1.0 2.0 2.0 2.0 2.0
1 1.0 3.0 3.0 3.0 3.0
2 4.0 4.0 7.0 7.0 7.0
Now, use the previously computed mask m to mask the values of i using df.where -
i.where(m)
2007 2008 2009 2010 2011
0 1.0 2.0 2.0 NaN NaN
1 1.0 3.0 3.0 3.0 NaN
2 4.0 4.0 7.0 7.0 7.0
Alternatively, use mask, inverting m -
i.mask(~m)
2007 2008 2009 2010 2011
0 1.0 2.0 2.0 NaN NaN
1 1.0 3.0 3.0 3.0 NaN
2 4.0 4.0 7.0 7.0 7.0
A:
You can use:
first create index from column fill_until
create mask by numpy broadcasting
use mask and apply fillna with method ffill (same as ffill)
last reset_index and for same order of columns add reindex
df = pd.DataFrame([[1, 2 ,np.nan,np.nan,10 , 2009],
[1, 3 , np.nan , np.nan , np.nan , 2010],
[4, np.nan , 7 , np.nan,np.nan , 2011]],
columns=[2007,2008,2009,2010,2011 , 'fill_until'])
print (df)
2007 2008 2009 2010 2011 fill_until
0 1 2.0 NaN NaN 10.0 2009
1 1 3.0 NaN NaN NaN 2010
2 4 NaN 7.0 NaN NaN 2011
df1 = df.set_index('fill_until')
m = df1.columns.values <= df1.index.values[:, None]
print (m)
[[ True True True False False]
[ True True True True False]
[ True True True True True]]
df = df1.mask(m, df1.ffill(axis=1)).reset_index().reindex(columns=df.columns)
print (df)
2007 2008 2009 2010 2011 fill_until
0 1 2.0 2.0 NaN 10.0 2009
1 1 3.0 3.0 3.0 NaN 2010
2 4 4.0 7.0 7.0 7.0 2011
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX VBox and HBox layouts
I'm working on a JavaFX application which has a layout generated from an external data structure, composed of
displaying components that know their own aspect ratios (height as a dependent of width)
2 types of structural components that
display all children with an equal width across their page, each child up as much vertical space as needed
display all children down the page using the full width and taking as much vertical space as needed
But I'm finding things aren't displaying as I expect. I've made a simplified case that demonstrates the problem.
The code is below, and the problem is that v3 doesn't get displayed, and I can't for the life of me work out why. I guess there's some facet of VBoxes and HBoxes that I haven't understood.
I'd really appreciate any help or ideas. Thanks in advance!
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.Random;
public class Test extends Application {
static Random rand = new Random();
public static void main(String args[]) {
Application.launch("something");
}
@Override
public void start(Stage mainStage) throws Exception {
testVBoxes(mainStage);
}
private void testVBoxes(Stage mainStage) {
VBox root = new VBox();
Scene one = new Scene(root, 800, 600, Color.WHITE);
FixedAspectRatioH h1 = new FixedAspectRatioH();
FixedAspectRatioH h2 = new FixedAspectRatioH();
FixedAspectRatioH h3 = new FixedAspectRatioH();
FixedAspectRatioV v1 = new FixedAspectRatioV();
FixedAspectRatioV v2 = new FixedAspectRatioV();
FixedAspectRatioV v3 = new FixedAspectRatioV();
h1.prefWidthProperty().bind(root.widthProperty());
h2.add(v2);
v1.add(h3);
v1.add(h2);
h1.add(v1);
h1.add(v3);
root.getChildren().add(h1);
mainStage.setScene(one);
mainStage.show();
}
private class FixedAspectRatioV extends VBox {
public FixedAspectRatioV() {
Rectangle r = new Rectangle();
r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
r.widthProperty().bind(widthProperty());
r.heightProperty().bind(r.widthProperty().divide(3));
getChildren().add(r);
}
public void add(Region n) {
n.prefWidthProperty().bind(widthProperty());
getChildren().add(n);
}
}
private class FixedAspectRatioH extends HBox {
public FixedAspectRatioH() {
Rectangle r = new Rectangle();
r.setFill(Color.rgb(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
r.widthProperty().bind(widthProperty().divide(4));
r.heightProperty().bind(r.widthProperty());
getChildren().add(r);
}
public void add(Region n) {
HBox.setHgrow(n, Priority.ALWAYS);
getChildren().add(n);
}
}
}
A:
its 2 years but the solution is you forgot
Node.setPrefSize(width,height);
and also add this to your constructor Hbox.setFillHeight(true);
| {
"pile_set_name": "StackExchange"
} |
Q:
Stripe native PHP library vs using plain cURL
So I'm about to implement stripe payments to one of our projects and I've read the documentation of their API which stands as:
The Stripe API is organized around REST. Our API is designed to have
predictable, resource-oriented URLs and to use HTTP response codes to
indicate API errors. We use built-in HTTP features, like HTTP
authentication and HTTP verbs, which can be understood by
off-the-shelf HTTP clients, and we support cross-origin resource
sharing to allow you to interact securely with our API from a
client-side web application (though you should remember that you
should never expose your secret API key in any public website's
client-side code). JSON will be returned in all responses from the
API, including errors (though if you're using API bindings, we will
convert the response to the appropriate language-specific object).
They have a good pack of ready-to-use API libraries for popular languages so you import them to your favorite language and just start using their API, including PHP, which is what we are using for this project.
Now, their API is large and they have a lot of objects. We are not actually going to use the whole set of features so my initial thought was to just wrap around their HTTP RESTFul interface around simple cURL code so I don't have to load their whole set of classes for the sake of performance.
Now, before I actually implemented my own cURL client arount their HTTP API I took a couple of minutes to look at the sources of their PHP libraries and they seem to do exactly that: wrap around cURL functions, throw errors, expose objectified responses, etc.
Then the question is: Is it worth to just use their library even when I know I'll be loading a lot of clases I won't use, or should I write my own wrapper with cURL around their REST API?
Consider that this question came to my mind sice we are using other services (TangoCard, for instance) and most of them have deprecated "native" libraries favoring the use of whatever is your favorite HTTP client library and just use the REST API.
Thanks!
A:
Loading classes is almost a non-issue in terms of performance, especially if you are using APC. I think the time saved by using what they give you completely justifies the slight performance loss due to loading their classes.
However, if their code is well written you shouldn't load any classes you don't actually use.
Also, if they maintain their library it will be easier to receive updates as time goes on. For instance, we used to roll our own Facebook APIs that used curl and had to stop due to their high number of updates and breaking changes over time.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the Alternatives to Google Analytics
I need to Track Unique Visitor count in my web application. I would really like to use Google Analytics but due to the Load limitations that google imposes I will not be able to use them. I am expecting WAY over 10,000 requests a day. This is the limitation that Google web analytics API imposes. Is there another company that has the same features as google analytics that is paid or free?
A:
There definitely are.
Here are two open source and free solutions that are very polished:
Piwik - Designed as a direct competitor to Google Analytics (it looks just as nice) that you host on your own servers
Open Web Analytics
A:
the 10,000 request apply to the Data API, not to the actual data collection.
Like you can have an unlimited number of users seeing your website. On the other hand if you use the API to extract data from their database, you can do 10k request a day only.
check this link for more details
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript library for line charting with very specific demands
I have read numerous topics and went(at first) with jqplot but it lacked with some essential functions which I needed even though I find it to be a very good tool.
Now I'm in the crossroads, does someone know something more suitable for my specific demands or should I start writing my own JS library for charting?
Requirements:
Possibility to change axes scales(x-axis, y-axis etc)
dynamically, not just at the initializing part(currently jqplot only
has the possibility to resetScales-boolean if I want to replot
again, can't scale like I would like to -> ugly results);
Zooming into the chart(with mouse as you select desired section), keep the current view depth even after the replot(with possiblity to change x-axis), possible in the replotted diagram to zoom out again to default view;
Format axes values into suitable formats if wanted(jqplot had
it);
IE 8+ compatible;
Customizable grid lines;
At least two Y-axes.
If possible then please don't recommend libraries which cost.
Thank you for your time.
EDIT:
I found something called Flot. Is there anything much more capable than Flot-> http://www.flotcharts.org/?
A:
I went with Flot chart. Matches my demands very well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to inject carbon dioxide into hard candy, to make popping rocks?
I have a great idea for a unique candy recipe, but to achieve this I need to be able to make pop rocks. The pop rocks would be inside the candy.
Doing some research I have learned that pop rocks have pressurized carbon dioxide gas inside each tiny rock. I would not have any problem trying batch after batch and getting the ingredients right to make these pop rocks. But it would be useless if I can't get the CO2 inside.
Does anyone knows of an easy way of doing this at home? If not, what type of machinery do you need?
A:
Looks like it takes about 600psi CO2 to treat the liquid candy.
Patent search should reveal more detail: US patent 3012893
Patent links are notorious for decaying over a short time frame.
If the second link is dead go http://www.uspto.gov/patents-application-process/search-patents or here to find find out how the inventors did it.
Patents before 1976, are in image format, and are hard to look through, sometimes Google is a better choice than USPTO on these.
See also US Patent 4289794 (1981)
Gasified candy which produces a more pronounced popping sensation is prepared by maintaining a sugar melt at a temperature of below about 280° F. ... Such a candy is made by a process which comprises melting crystalline sugar, contacting such sugar with gas at a pressure of 50 to 1,000 psig for a time sufficient to permit incorporation in said sugar of 0.5 to 15 cm3 of gas per gram of sugar, maintaining the temperature of said sugar during said absorption above the solidification temperature of the melted sugar, and cooling said sugar under pressure to produce a solid amorphous sugar containing the gas. Upon the release of the pressure, the solid gasified candy fractures into granules of assorted sizes.
High temperature, high pressure. Even as a hard candy, the stuff has a short shelf life.
Baking soda/acid mixture candies are just Fizzies in disguise. Feel weird when they bubble in your mouth, but they do not explode like pop rocks.
A:
There are recipes on the internet for making home made pop rocks.
Some of them call for using baking soda plus an acid, so that you generate carbon dioxide in the syrup, rather than injecting it as a pressurized gas.
I would assume that you could also use baking powder if you can't find powdered acids.
A:
Applied Science, a YouTube channel, had a video about making carbonated candy a la Pop Rocks: https://www.youtube.com/watch?v=qsSwvmNEr0Q
Here's a broad outline:
Craft a mixing chamber that can hold 600 psi (40 bar), has an inlet for CO2, and a rotary pressure seal with a mixing/whisk attachment.
Make a hard candy (280 °F/137 °C) on the stove
Preheat the chamber to avoid the candy solidifying too quickly
Pour molten candy into the chamber
Close and pressurize to 600 psi.
Mix (with drill or whatever) for 3-4 minutes
Let cool while under pressure
Depressurize and open chamber, remove candy with mallet, chisel, and/or hammer.
Enjoy!
| {
"pile_set_name": "StackExchange"
} |
Q:
JPQL select from multiple tables
I'm new to JPQL and having some trouble with what I think might be quite a simple query. Please could someone explain if the following is possible.
I have two unrelated tables: 'customers' and 'merchants'. They both contain a field called 'username'. Is there a query that would return me a 'username' record that appears in either table and that matches a value I supply?
Query query = entityManager.createQuery("select c from Customers c where c.username = :username");
query.setParameter("username", username_);
Something like this but for both tables.
A:
It sounds like you want to match a given username to either a Customer or a Merchant. Since the two tables are unrelated, to do this with a single query, I believe you would need to form a cartesian product (join every row of one table with every row in the other). As you might imagine, this could be very inefficient. You're better off doing two simple queries:
try {
Customer c = em.createQuery("SELECT c FROM Customer c WHERE c.username = :username", Customer.class)
.setParameter("username", username)
.getSingleResult();
// ... do something with the customer ...
} catch (NoResultException e) {
// user wasn't found in the customer table, try merchant:
try {
Merchant m = em.createQuery("SELECT m FROM Merchant m WHERE m.username = :username", Merchant.class)
.setParameter("username", username)
.getSingleResult();
// ... do something with the merchant ...
} catch (NoResultException e) {
// user wasn't found in either table
}
}
Note: I'm assuming that username is unique within Customer and Merchant.
Notice that this approach will only execute the second query if we don't find the user with the first. If you don't need to return the object (i.e. just need to check if it exists) then you could simplify the above with two count queries. Count queries always return a result, so you wouldn't need to catch the NoResultExceptions
| {
"pile_set_name": "StackExchange"
} |
Q:
How to explain mortgage monthly payment formula using school math?
$P = L*\frac{x*(1+x)^n}{(1+x)^n - 1}$
where
P - monthly payment
L - loan amount
x - monthly interest rate
n - number of payments
Here is in Wikipedia explanation but it is complicated by using a cyclotomic polynomial approach. I answer my own question.
A:
OK. Let me state the problem here.
We have a loan amount $L$, number of payments $n$, interest rate per year $Y$. What will a monthly payment $P$ be?
Usually loan has interest rate per year $Y$ and payments made by month, so we need to convert $Y$ to monthly interest rate $x = \frac{Y}{12} (1)$.
Let's calculate the loan reminder after the 1st payment, we used all loan $L$ money for a month.
$L_1 = L*(1+x) - P (2)$
Let's calculate the loan reminder after the 2nd payment, we used the loan after the 1st payment $L_1$ money for a month. Use formula (2) to simplify and to open parenthesis.
$L_2=L_1*(1+x) - P = [L*(1+x) - P]*(1+x) - P = L*(1+x)^2 -P*(1+x) -P = L*(1+x)^2 -P*[(1+x) + 1] (3)$
Let's calculate the loan reminder after the 3rd payment, we used the loan after the 2nd payment $L_2$ money for a month. Use formula (3) to simplify and to open parenthesis.
$L_3=L_2*(1+x) - P = {L*(1+x)^2 -P*[(1+x) + 1]}*(1+x) - P = L*(1+x)^3 -P*(1+x)^2 P*(1+x) -P = L*(1+x)^3 -P*[(1+x)^2 + (1+x) + 1] (4)$
We can see a pattern now and can write the expression for $L_n$.
$L_n=L_{n-1}*(1+x) - P = L*(1+x)^n - P*[(1+x)^{n-1}+ ... + (1+x)^2 + (1+x) + 1] (5)$
I also want to state that after last payment $L_n$ we are no longer own any amount on the loan.
Or $L_n = 0 (6)$ or using (5) in (6)
$L*(1+x)^n - P*[(1+x)^{n-1}+ ... + (1+x)^2 + (1+x) + 1] = 0(6')$
Let's simplify $(1+x)^{n-1}+ ... + (1+x)^2 + (1+x) + 1$. We know from school mathematical curriculum about geometric progression. Each element of geometric progression can be expressed as $a_k=a*r^{k-1}$. Assume $a=1$ and $r=(1+x)$, so $(1+x)^0, (1+x)^1, (1+x)^2, ..., (1+x)^{n-1}$. And the sum of geometric progression is calculated by formula $S = a*\frac{1-r^k}{1-r}$
Let's apply is to our case: $(1+x)^{n-1}+ ... + (1+x)^2 + (1+x) + 1= \frac{1-(1+x)^n}{1-(1+x)} = \frac{1-(1+x)^n}{1-1-x)} = -\frac{1-(1+x)^n}{x}(7)$
or after opening parenthesis. $(1+x)^{n-1}+ ... + (1+x)^2 + (1+x) + 1=-\frac{1-(1+x)^n}{x}(7')$
Now use (7') in (6')
$L*(1+x)^n - P* [-\frac{1-(1+x)^n}{x}]= 0 (8)$
Solving (8) to find $P$
$L*(1+x)^n = P* [-\frac{1-(1+x)^n}{x}] (8')$
$L*(1+x)^n = P* [\frac{(1+x)^n - 1}{x}] (8'')$
$P = L*[\frac{x*(1+x)^n}{(1+x)^n-1}](9)$
Here's the small piece of Python code to calculate monthly payment:
Y=float(input("Enter the yearly interest rate (in percent):"))
n=int(input("Enter the number of payments:"))
L=float(input("Loan amount?"))
x=Y/(12*100)
r=1+x
r1=r**n
P=L*x*r1/(r1-1)
print("The monthly payment ", P)
Test results:
Enter the yearly interest rate (in percent):4
Enter the number of payments:360
Loan amount?100000
The monthly payment 477.4152954654538
Questions, comments, edits ?
| {
"pile_set_name": "StackExchange"
} |
Q:
Save multiple times at almost the same time in workligth JSONStore
I want to add to JSONStore by using a for cycle
so i call the saveToJSON() function inside the for with a length more than 500, but it doesnt add, and in console it shows succes but when i look in the jsonstore theres nothing,and number of the cycle for times that i called to add to jsonstore is in a red bubble in console.
function saveToJSON(object) {
var data ={
title : object.title,
subtitle: object.subtitle,
};
var options = {}; //default
WL.JSONStore.get('MyDataCollection').add(data, options)
.then(function () {
//handle success
console.log("add JSONStore success");
})
.fail(function (errorObject) {
//handle failure
console.log("add JSONStore failure");
});
}
A:
Try creating an array with the data you want to add and then passing that to JSONStore's add API. Remember to make sure that WL.JSONStore.init has finished successfully before calling the add API.
Example pseudocode:
//This is the data you want to add, you probably get this from a network call
var someData = [{title: 'hello'}, {title: 'world'}];
//This is an array that you will pass to JSONStore's add API
var someArray = [];
//Populate the array with data you want to pass to JSONStore's add API
for (var i = 0; i < someData.length; i++) {
someArray.push(someData[i]);
}
//Add data inside someArray to the collection called: MyDataCollection
WL.JSONStore.get('MyDataCollection').add(someArray)
.then(function () {
//Do a find all operation on the collection called: MyDataCollection
return WL.JSONStore.get('MyDataCollection').findAll();
})
.then(function (res) {
//Print all the data inside the collection called: MyDataCollection
console.log(JSON.stringify(res));
});
//You may want to add .fail(function(){...}) to handle errors.
| {
"pile_set_name": "StackExchange"
} |
Q:
How ArrayList work with unsupportedOperationException?
I am assigned to implement my own Arraylist and Linkedlist that works very similarly to Java's provided ArrayList and LinkedList in Java.util.*, but not all of methods but some of them.
Assignment description says following:
So it sounds like that I have to implement above code into my code for every methods that I am not going to implement. However, my source code works fine without implementing above thing. I just simply do not even mention those methods that I am not assigned to implement.
My question is, I wonder why my code works fine without mentioning above requirement in assignment description. And how can I have above function with throw new exception into my code? (to satisfy that assignment requirement anyway)
Following is my class declaration currently:
public class A1ArrayList<E>
{
...
}
Do I have to extends or implements something from Java's list API to work with that function with exception throwing?
A:
Yes, you need to implement the List interface.
public class A1ArrayList<E> implements List<E>
{
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
hamburger dropdown not displaying in ie11
first post here, but I'm getting increasingly frustrated with this.
Basically, I have a hamburger menu I have added to a site I'm working on and it works fine in chrome and edge, but not in IE11. I have tried and it displays fine in IE10.
We have a significant amount of people using IE11 unfortunately so I really would like this to work.
I have checked the css on the https://caniuse.com/ site and can't see anything that should be creating a problem...
Any helps would be appreciated!
Doesn't help that the CMS we use just removes the and links when I include them which is super helpful
css:
.menu-item, .menu-open-button {
background : #177b57;
margin-bottom : 0;
border-radius : 100%;
width : 70px;
height : 70px;
position : fixed;
top : 180px;
right : 90px;
color : #FFFFFF;
text-align : center;
line-height : 70px;
transform : translate3d(0,0,0);
transition : transform 200ms ease-out;
}
#menu-open {
display : none;
margin-bottom : 0;
background : #4CAF50;
}
.faq-menu {
margin : auto;
top : 0;
position : fixed;
top : 180px;
right : 90px;
left : 0;
right : 0;
width : 70px;
height : 70px;
text-align : center;
box-sizing : border-box;
font-size : 26px;
font-family : "BCGHenSansLight", "Helvetica Neue", Verdana, Arial, sans-serif;
}
.menu-item:hover {
background : #4CAF50;
}
.menu-item:nth-child(6) {
transition-duration : 180ms;
}
.menu-item:nth-child(7) {
transition-duration : 180ms;
}
.menu-item:nth-child(8) {
transition-duration : 180ms;
}
.menu-item:nth-child(9) {
transition-duration : 180ms;
}
.menu-open-button {
z-index : 2;
transition-timing-function : cubic-bezier(0.175,0.885,0.32,1.275);
transition-duration : 400ms;
transform : scale(1.1,1.1) translate3d(0,0,0);
cursor : pointer;
box-shadow : 3px 3px 0 0 rgb(0, 0, 0, 0.14);
}
.menu-open-button:hover {
transform : scale(1.2,1.2) translate3d(0,0,0);
}
.menu-open:checked + .menu-open-button {
transition-timing-function : linear;
transition-duration : 200ms;
transform : scale(0.8,0.8) translate3d(0,0,0);
}
.menu-open:checked ~ .menu-item {
transition-timing-function : cubic-bezier(0.935,0,0.34,1.33);
}
.menu-open:checked ~ .menu-item:nth-child(3) {
transition-duration : 180ms;
transform : translate3d(0.08361px,104.99997px,0);
}
.menu-open:checked ~ .menu-item:nth-child(4) {
transition-duration : 280ms;
transform : translate3d(-90.86291px,52.62064px,0);
}
.menu-open:checked ~ .menu-item:nth-child(5) {
transition-duration : 680ms;
transform : translate3d(-91.03006px,-52.33095px,0);
}
.faq-green {
background-color : #177b57;
box-shadow : 2px 2px 0 0 rgb(0, 0, 0, 0.14);
text-shadow : 1px 1px 0 rgb(0, 0, 0, 0.12);
}
.blue:hover {
color : #4CAF50;
text-shadow : none;
}
.email-green {
background-color : #177b57;
box-shadow : 2px 2px 0 0 rgb(0, 0, 0, 0.14);
text-shadow : 1px 1px 0 rgb(0, 0, 0, 0.12);
}
.green:hover {
color : #4CAF50;
text-shadow : none;
}
.email-purple {
background-color : #177b57;
box-shadow : 2px 2px 0 0 rgb(0, 0, 0, 0.14);
text-shadow : 1px 1px 0 rgb(0, 0, 0, 0.12);
}
.purple:hover {
color : #4CAF50;
text-shadow : none;
}
</style>
and html:
<title>Info menu</title>
<div>
<input type="checkbox" class="menu-open" name="menu-open" id="menu-open">
<label for="menu-open" class="menu-open-button">
<img src="/data/00001225_question_mark.png" style="width:70px; height:70px; padding-bottom:5px; ">
</label>
<a href="http://trackingkate.weebly.com" class="menu-item email-purple" title="Contact"> <img src="/img" style="width:40px; height:50px; padding-bottom:3px; "> </a>
<a href="mailto:[email protected]?body=For any questions or issues please contact us." class="menu-item email-green" title="Email"><img src="/img" style="width:40px; height:40px; "> </a>
<a href="http://trackingkate.weebly.com" class="menu-item faq-green" title="FAQs"> <center> FAQs </center></a>
</div>
</div>
</div>
</div>
on codepen:
https://codepen.io/kateseabra/pen/OJyNaBN -this is the link to the code in codepen (looks a bit funky as I had to remove the images and links etc)
A:
This is now done. Thanks for the help.
Turns out the image I was using was covering too much of the button in IE11 which meant the clickable surface around the image was too small. Chose a smaller image and increased the size of the checkbox and now it works well on both chrome and ie11.
| {
"pile_set_name": "StackExchange"
} |
Q:
ODP.NET deployment without installation
I want to deploy a client application that uses Oracle's ODP.net but I don't want to install ODP.net on every machine. Rather I'd like to copy the managed dll oracle.dataaccess.dll on every machine and have the native dlls on which it depends available, on a shared disk.
By decompiling the oracle.dataaccess.dll code I have seen that it calls a method that gets the location of the native dlls from the registry. So, in addition to copying the oracle.dataaccess.dll on every machine I would have to add the registry keys that would point to the native dlls on the shared disk.
My question: does one foresee any problem arising from that technique of odp.net deployment?
A:
The only files you need from the latest client are:
Oracle.DataAccess.dll
oci.dll
oraociicus11.dll
OraOps11w.dll
Just make sure they get copied to the output directory and everything will work. Nothing needs to be registered anywhere. You will however need to make separate x86 and x64 builds with the respective architecture's DLLs since an Any CPU .NET application will run in 32-bit mode on a 32-bit OS and in 64-bit mode on a 64-bit OS.
A:
1) ODP.NET is currently a mixture of managed and unmanaged DLL's. It also relies on lower level unmanaged DLLs from the Oracle client - eg for networking, etc.
2) You will need all these required ODP.NET and client DLLs on each machine you deploy to.
3) One potential solution to make this easier on you is to look into the "XCOPY" deployment package. See the ODP.NET download page. This is a smaller install and allows you to write your own custom installer. You can include these XCOPY files as part of your own install.
4) Oracle will be doing a beta of a fully managed provider in 2012 which will make this situation much better (and the total size will be a couple megabytes only).
Christian Shay
Oracle
| {
"pile_set_name": "StackExchange"
} |
Q:
Processing 32 bit integers on 32 bit hardware and on 64bit hardware, which is faster?
I am programming C on linux, and which is faster in the following conditions?
1.processing 32bit integers on 32bit hardware and 64bit hardware
2.processing 64bit integers on 32bit hardware and 64bit hardware
A:
You should tell on what exact hardware, and what kind of processing.
And more importantly, you should benchmark your application, taking into account that premature optimization is evil.
Standard C99 provides you with the <stdint.h> with the fastint_t type (and others, e.G. intptr_t or int32_t...); there is also a <inttypes.h> standard header.
I believe you should not bother at first. If you know that some integer data type is very crucial to your application, you might use your own typedef, eg.
typedef intfast_t myimportantint_t;
Then you develop your application using appropriately myimportantint_t, and benchmark it. You can then easily change that typedef. (So changing the size of your important integers would be easy, just changing that typedef and perhaps defining a MYIMPORTANT_MAX preprocessor constant, etc.).
See this question very related to yours.
I believe you should not care that much.
Of course, 64 bits arithmetic on many 32 bits processors is more costly than 32 bits arithmetic.
| {
"pile_set_name": "StackExchange"
} |
Q:
how can i avoid the increasing of verion by adding relations?
i have following domain class schema:
class A { static hasMany=[abRelations: AB] }
class B { static hasMany=[abRelations: AB] }
//relation table
class AB{
A a
B b
String someAttribute
}
in some cases i definitely need the abRelations association, e.g. hql queries, criterias, ...
my problem is that when i create a new AB entry with
new AB(a: a, b: b, someAttribute: "hello").save()
the version field of A and B gets increased. can i avoid this by adding a special mapping option or something like this? i'm using the afterUpate event in some classes and this event is also fired when a add new relations -> thats my main problem!
A:
You can remove the version field completely by adding the following to the domain class
static mapping = {
version false
}
My understanding is that there's no way to exercise fine-grained control over when the version field gets incremented. You either have a version field and it automatically gets incremented every time a domain object is updated, or you don't have it at all.
| {
"pile_set_name": "StackExchange"
} |
Q:
python `for i in iter` vs `while True; i = next(iter)`
To my understanding, both these approach work for operating on every item in a generator:
let i be our operator target
let my_iter be our generator
let callable do_something_with return None
While Loop + StopIteratioon
try:
while True:
i = next(my_iter)
do_something_with(i)
except StopIteration:
pass
For loop / list comprehension
for i in my_iter:
do_something_with(i)
[do_something_with(i) for i in my_iter]
Minor Edit: print(i) replaced with do_something_with(i) as suggested by @kojiro to disambiguate a use case with the interpreter mechanics.
As far as I am aware, these are both applicable ways to iterate over a generator, Is there any reason to prefer one over the other?
Right now the for loop is looking superior to me. Due to: less lines/clutter and readability in general, plus single indent.
I really only see the while approach being advantages if you want to handily break the loop on particular exceptions.
A:
the third option is definitively NOT the same as the first two. the third example creates a list, one each for the return value of print(i), which happens to be None, so not a very interesting list.
the first two are semantically similar. There is a minor, technical difference; the while loop, as presented, does not work if my_iter is not, in fact an iterator (ie, has a __next__() method); for instance, if it's a list. The for loop works for all iterables (has an __iter__() method) in addition to iterators.
The correct version is thus:
my_iter = iter(my_iterable)
try:
while True:
i = next(my_iter)
print(i)
except StopIteration:
pass
Now, aside from readability reasons, there in fact is a technical reason you should prefer the for loop; there is a penalty you pay (in CPython, anyhow) for the number of bytecodes executed in tight inner loops. lets compare:
In [1]: def forloop(my_iter):
...: for i in my_iter:
...: print(i)
...:
In [57]: dis.dis(forloop)
2 0 SETUP_LOOP 24 (to 27)
3 LOAD_FAST 0 (my_iter)
6 GET_ITER
>> 7 FOR_ITER 16 (to 26)
10 STORE_FAST 1 (i)
3 13 LOAD_GLOBAL 0 (print)
16 LOAD_FAST 1 (i)
19 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
22 POP_TOP
23 JUMP_ABSOLUTE 7
>> 26 POP_BLOCK
>> 27 LOAD_CONST 0 (None)
30 RETURN_VALUE
7 bytecodes called in inner loop vs:
In [55]: def whileloop(my_iterable):
....: my_iter = iter(my_iterable)
....: try:
....: while True:
....: i = next(my_iter)
....: print(i)
....: except StopIteration:
....: pass
....:
In [56]: dis.dis(whileloop)
2 0 LOAD_GLOBAL 0 (iter)
3 LOAD_FAST 0 (my_iterable)
6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
9 STORE_FAST 1 (my_iter)
3 12 SETUP_EXCEPT 32 (to 47)
4 15 SETUP_LOOP 25 (to 43)
5 >> 18 LOAD_GLOBAL 1 (next)
21 LOAD_FAST 1 (my_iter)
24 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
27 STORE_FAST 2 (i)
6 30 LOAD_GLOBAL 2 (print)
33 LOAD_FAST 2 (i)
36 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
39 POP_TOP
40 JUMP_ABSOLUTE 18
>> 43 POP_BLOCK
44 JUMP_FORWARD 18 (to 65)
7 >> 47 DUP_TOP
48 LOAD_GLOBAL 3 (StopIteration)
51 COMPARE_OP 10 (exception match)
54 POP_JUMP_IF_FALSE 64
57 POP_TOP
58 POP_TOP
59 POP_TOP
8 60 POP_EXCEPT
61 JUMP_FORWARD 1 (to 65)
>> 64 END_FINALLY
>> 65 LOAD_CONST 0 (None)
68 RETURN_VALUE
9 Bytecodes in the inner loop.
We can actually do even better, though.
In [58]: from collections import deque
In [59]: def deqloop(my_iter):
....: deque(map(print, my_iter), 0)
....:
In [61]: dis.dis(deqloop)
2 0 LOAD_GLOBAL 0 (deque)
3 LOAD_GLOBAL 1 (map)
6 LOAD_GLOBAL 2 (print)
9 LOAD_FAST 0 (my_iter)
12 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
15 LOAD_CONST 1 (0)
18 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
21 POP_TOP
22 LOAD_CONST 0 (None)
25 RETURN_VALUE
everything happens in C, collections.deque, map and print are all builtins. (for cpython) so in this case, there are no bytecodes executed for looping. This is only a useful optimization when the iteration step is a c function (as is the case for print. Otherwise, the overhead of a python function call is larger than the JUMP_ABSOLUTE overhead.
A:
The for loop is the most pythonic. Note that you can break out of for loops as well as while loops.
Don't use the list comprehension unless you need the resulting list, otherwise you are needlessly storing all the elements. Your example list comprehension will only work with the print function in Python 3, it won't work with the print statement in Python 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server 2008 Installation and Service Account option
When Installing SQL Server 2008, it asks for Service accounts. Which one to select from the list? and which are the most suitable at the development time?
A:
See the answers on this question:
What accounts to use when installing SQL Server 2008 Developer
Bottom line is that if you are installing on your dev machine, and are developing client software to talk directly to your local instance of SQL server, you don't really need to worry about the extra stuff mentioned in that question/answer (surface area configuration).
It probably is a good idea to use an account with bare minimum security for your sql server instance. In that case, you can do what the second answer states and create a new user account to use before you install.
If you've already installed, you can do the following:
Create your new user account for sql server
Add it to the appropriate User group (it will probably be named something like SqlServerMSSQLUser) This will give the user account all necessary rights to run SQL server
Update the SQL service to use the new account in the Services tab/option under Administrative Tools
Any time you run into security permissions (say you are exporting files to a share) you can just update the user you created for sql server.
| {
"pile_set_name": "StackExchange"
} |
Q:
local variable referenced before assignment
import DBUtil
def insert_sql(*args, **kw):
for k, v in kw:
SQL_INSERT = "insert into nostray(%s) values(%s)" % (k, v)
return SQL_INSERT
sql = insert_sql("userid", "02")
DBUtil.excute(sql)
I wrote a util to connect db, and execute sql, an error occured:
Traceback (most recent call last):
File "test.py", line 8, in <module>
sql = insert_sql("userid", "02").
File "test.py", line 6, in insert_sql.
return SQL_INSERT.
UnboundLocalError: local variable 'SQL_INSERT' referenced before assignment
How to fix this, thx.
A:
You're not calling this function with any keyword arguments; you just pass positional arguments. So, kw is empty and the loop is never executed.
I think you meant to use userid as the key and 02 as the value, so you should do this:
sql = insert_sql(userid="02")
Note, there are other problems with this code; for example, if you use more than one kwarg, your SQL will only ever contain one of them.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.