text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Работа с объектами в VirtualTreeView
Как правильно заполнять записи с объектами?
Как правильно считывать такие записи в событии OnGetText?
Запись для работы с VST(VirtualStringTree)
type
PLessonRec = ^TLessonRec;
TLessonRec = record
Lesson: TLesson;
end;
Описание типа TLesson
TLesson = class
private
FId, FIndex: Integer;
FName: String;
FExercises: TExercises;
public
property Id: Integer read FId write FId;
property Index: Integer read FIndex write FIndex;
property Name: String read FName write FName;
property SubItems: TExercises read FExercises write FExercises;
constructor Create;
end;
Описание типа TExercises
TExercises = class
private
FExercises: TExercisesItems;
FCount: Integer;
function GetItem(AIndex: Integer): TExercise;
procedure SetItem(AIndex: Integer; AValue: TExercise);
function GetCount: Integer;
public
property Items[AIndex: Integer]: TExercise read GetItem write SetItem; default;
property Count: Integer read GetCount;
function Add(const AName, AContent: String; AType: TExerciseType): TExercise;
procedure Clear;
procedure Delete(Index: Integer);
destructor Destroy; override;
end;
Описание типа TExercise
TExercise = class
private
FId, FIndex: Integer;
FName, FContent: String;
FType: TExerciseType;
public
property Id: Integer read FId write FId;
property Index: Integer read FIndex write FIndex;
property Name: String read FName write FName;
property Content: String read FContent write FContent;
property ExType: TExerciseType read FType write FType;
end;
Загрузка данных в запись LessonRec: PLessonRec
procedure FillTree();
var
LessonRec: PLessonRec;
RootNode, ChildNode: PVirtualNode;
ExerciseIndex: Integer;
begin
RootNode := VST.AddChild(nil);
LessonRec := VST.GetNodeData(RootNode);
LessonRec.Lesson := TLesson.Create();
{ Получаю урок вместе со всеми упражнениями }
LessonRec.Lesson := objLessons[PreviewIndex];
for ExerciseIndex := 0 to objLessons[PreviewIndex].SubItems.Count - 1 do // to LessonRec.Lesson.SubItems.Count - 1 do
begin
ChildNode := VST.AddChild(RootNode);
LessonRec := VST.GetNodeData(ChildNode);
...
{ Как правильно заполнить запись, которая имеет объект с вложенными объектами? }
end;
end;
Событие OnGetText
procedure TfrmList.vstLessonGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
LessonRec: PLessonRec;
begin
if Column = 1 then // Column = 0 типа CheckBox
begin
LessonRec := Sender.GetNodeData(Node);
case Sender.GetNodeLevel(Node) of
0: CellText := LessonRec.Lesson.Name;
1: CellText := ''; // Как обратиться к данным упражнений?
end;
end;
end;
A:
При работе с VT record`ы, как дополнительные контейнеры, не нужны, раз все данные уже лежат в объектах (т.е. уже имеют свой контейнер).
Для добавления объекта в VT можно использовать такой код:
// лучше, конечно, это сделать методом формы/фрейма, на котором лежит VT
function AddItem(Item: TObject; ParentNode: PVirtualNode = nil): PVirtualNode;
begin
Result := VT.InsertNode(ParentNode, amAddChildLast, Item);
end;
Получение любого объекта из нода:
function GetItem(Node: PVirtualNode): TObject;
var
NodeData: Pointer;
begin
Result := nil;
if not Assigned(Node) then
exit;
NodeData := VT.GetNodeData(Node);
if Assigned(NodeData) then
Result := TObject(NodeData^);
end;
И уже потом приводить результат GetItem к нужному типу, используя (к примеру) as и is:
myObject := GetItem(Node);
if myObject is TLesson then
CellText:=TLesson(myObject).Content;
P.S. не забудьте, что если VT выступает основным хранилищем данных (а я не вижу причин, зачем нужно хранить данные в VT и еще в каком-нибудь списке), то во избежание утечек памяти нужно задействовать VT.OnFreeNode:
procedure TSomeForm.vtFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
GetItem(Node).Free;
end;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
update value after form submit in modal and update page without reload
I will try to be as clear as I can.
I'm creating a simple example page where employee can review there age.
On the page user have the choice to click on a button to change there age.
The page load the age from a use in a Database.
So I select from the table employee the age matching the $name value.
<?php
$query = "SELECT * FROM employee";
$rs = mysql_query($query);
while ($row = mysql_fetch_assoc($rs)) {
echo "Name " . $row['name'] . "<br/>Age " . $row['age'] . "<br/>";
}
?>
Under that I have a bootstrap modal button so the employee can click and update there age.
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title" id="myModalLabel">Change your age</h4>
</div>
<div class="modal-body">
<?php
$name = "Mathieu";
$query = sprintf("SELECT age From employee Where name = '%s'",
mysql_real_escape_string($name));
$rs = mysql_query($query);
while ($row = mysql_fetch_object($rs)) {
$age = $row->age;
}
?>
<form action="update.php" method="post"class="form-inline">
<input class="form-control" id="disabledInput" type="text" placeholder="<?php echo $name; ?>" disabled>
<br/><br/>
<input type="text" class="form-control" placeholder="<?php echo $age; ?>" value="<?php echo $age; ?>">
<br/><br/>
<button type="submit" class="processing btn">Update</button>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<div class="bs-example" style="padding-bottom: 24px;">
<a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Update your age</a>
</div>
I have 2 problem.
1. What is the best way to update the value in my database then close the modal.
2. How do I refresh my page without a reload.
I did some trial and error but nothing work at all.
A:
The best way for me to update the value from the database without reloading is
that you should be using a Live Edit Using Jquery & ajax hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check if parent has text outside of its children
I have an XML similar to this one:
<parent>
<child>child's text</child>
<child>other child's text</child>
parent's text
</parent>
Note that it's allowed to have multiple child elements.
I'd like to know if the parent element has text outside of its children.
I've come up with this solution:
<xsl:if test="normalize-space(parent/child[1]) = normalize-space(parent)">
<xsl:text>No parent text</xsl:text>
</xsl:if>
I use parent/child[1] because the normalize-space function doesn't accept a sequence as it's argument.
Is there a better way to do this?
(I've found this question on the topic but the answer is incorrect or the question is different)
A:
Use text() to explicitly refer to text nodes.
The better way to do this is:
<xsl:if test="parent/text()[not(parent::child)]">
<!--This parent element has text nodes-->
</xsl:if>
Or else, you could write a separate template:
<xsl:template match="text()[parent::parent]">
<xsl:text>parent element with text nodes!</xsl:text>
</xsl:template>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Service Container Alias only for a certain environment
Symfony 2.8.7 I have a simple alias definition in my services.yml:
h4cc_alice_fixtures:
alias: h4cc_alice_fixtures.manager
This works perfectly in DEV because in my AppKernel h4cc is registered:
public function registerBundles()
{
$bundles = [
//...
];
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new h4cc\AliceFixturesBundle\h4ccAliceFixturesBundle();
}
return $bundles;
}
In PROD now I get an dependency injection error because of course h4cc_alice_fixtures.manager cannot be resolved.
I want to have h4ccAliceFixturesBundle only in DEV and TEST but currently I have only one services.yml.
Is there a way to define the alias only for DEV and TEST?
UPDATE:
As there is something like:
my_service:
class: Acme\AcmeBundle\Services\MyService
arguments: [ '@tenant_user_service', '@?debug.stopwatch' ]
which is only injecting Stopwatch when App is in debug-mode...
I thought there might be existing something similar for Alias, too.
A:
You can have separate services.yml similar what you have already with your routing_dev.yml. In the imports section of your config_dev.yml and config_test.yml you can replace the existing line:
imports:
- { resource: config.yml }
with following entry:
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services_dev.yml }
like you have it in your global config.yml already. Just add your suffix to the files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Detect Shift + Enter on physical keyboard in Android
In preparing my Android App for Chromebooks and use with physical keyboards I want to distinguish in an EditText between receiving an "Enter" (keyEvent 66) and an "Shift+Enter" (also keyEvent 66 apparently) from a physical keyboard. I have tried a number of different solutions, such as
dispatchKeyEvent(KeyEvent event) in the activity. The event.getModifiers() however always return 0, as do event.getMetaState(). keyEvent.isShiftPressed() always returns false.
onKeyDown(int keyCode, KeyEvent keyEvent) in the activity with the same result. keyEvent.isShiftPressed() always returns false as well.
I have not found a way either using onKeyUp(), onKeyPreIme(), editText.setOnKeyListener(...), or with a editText.addTextChangedListener(new TextWatcher() {...}). I have not had any problems acquiring the Enter event, however a Shift+Enter is in all the ways I have tried indistinguishable from the Enter event. So my question is this: did any other Android Dev find a way to properly capture the Shift+Enter from a physical keyboard?
A:
i had the same problem and I fixed it by detecting "Shift" down and "Shift" up events, and define a boolean that store the state.
this is my code, hope help you.
final boolean[] isPressed = {false};
inputEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
if (isPressed[0]) {
// Shift + Enter pressed
return false;
} else {
// Enter pressed
return true;
}
}
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
isPressed[0] = true;
return false;
}
if ((event.getAction() == KeyEvent.ACTION_UP) &&
(keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
isPressed[0] = false;
return false;
}
return false;
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Undefined reference error to one class/file
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I have a game program and I am getting VERY frustrated. Everything was running fine, and I decided to clean up my program by making separate files for each set of functions. The code is very long with multiple files, but heres the basic idea:
Im on Windows XP using the Code::Blocks IDE
In my entity.h Ive declared all of my functions and variables for that class. In my entity.cpp Ive included it, as well as in all my other files. But Im still getting a huge list of errors that tell me I have an undefined reference to all of the methods in entity.h as well as all my other header files. For example, I have a function call print() to make it easier to print out things, and thats the first method I call from the entity.h file. I get this error:
Heres the code for print():
void print(string f) {
cout<<f<<endl;
}
How Im calling it:
void Player::win(){
entity e;
e.print("You have defeated the orc");
}
The error:
In function 'ZN6Player3winEv': undefined reference to 'entity::print(std::string)'
And yes, I do have an object of entity.
Its also happening for every single other function in the entity class and file.
A:
void print(string f) {
cout<<f<<endl;
}
should be
void entity::print(string f) {
cout<<f<<endl;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What do I need to import/mixin to make "noException" available in a scalatest?
I'd like to write a test of the form noException should be thrownBy myFunc() as described in Using Matchers
I can't figure out what class I need to import to put noException in scope. I'm currently mixing in Flatspec with ShouldMatchers, and I've tried also doing it with Matchers
What am I missing?
In case it matters, I'm using scalatest 1.9.1 with scala 2.9:
scalaVersion := "2.9.3"
[...]
"org.scalatest" %% "scalatest" % "1.9.1" % "test",
A:
Scalatest 2.0 added thrownBy, and presumably noException came with it. You'll need to upgrade scalatest to a 2.x release, which also means upgrading scala to 2.10+
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add controller to UITabBarController without new item appearing in the tab bar
I have an application with UITabBarController as its main controller.
When user taps a button(not in the tab bar, just some other button), I want to add new UIViewController inside my UITabBarController and show it, but I don't want for new UITabBarItem to appear in tab bar. How to achieve such behaviour?
I've tried to set tabBarController.selectedViewController property to a view controller that is not in tabBarController.viewControllers array, but nothing happens. And if I add view controller to tabBarController.viewControllers array new item automatically appears in the tab bar.
Update
Thanks to Levi, I've extended my tab bar controller to handle controllers that not present in .viewControllers.
@interface MainTabBarController : UITabBarController
/**
* By setting this property, tab bar controller will display
* given controller as it was added to the viewControllers and activated
* but icon will not appear in the tab bar.
*/
@property (strong, nonatomic) UIViewController *foreignController;
@end
#import "MainTabBarController.h"
@implementation MainTabBarController
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
self.foreignController = nil;
}
- (void)setForeignController:(UIViewController *)foreignController
{
if (foreignController) {
CGFloat reducedHeight = foreignController.view.frame.size.height - self.tabBar.frame.size.height;
foreignController.view.frame = CGRectMake(0.0f, 0.0f, 320.0f, reducedHeight);
[self addChildViewController:foreignController];
[self.view addSubview:foreignController.view];
} else {
[_foreignController.view removeFromSuperview];
[_foreignController removeFromParentViewController];
}
_foreignController = foreignController;
}
@end
The code will correctly set "foreign" controller's view size and remove it when user choose item in the tab bar.
A:
You either push it (if you have a navigation controller) or add it's view to your visible View Controller's view and add it as child View Controller also.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visual Studio 2008 Product Key in Registry?
I have a friend who needs to reinstall windows, but he can't find his VS2008 activation code/product key. Is there a way to look up which product key he entered when he last installed VS2008 in the registry? Any other method of finding the key is also welcome.
A:
For 32 bit Windows:
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
For 64 bit Windows:
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY
Notes:
Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
If PIDKEY value is empty try to look at the subfolders e.g.
...\Registration\1000.0x0000\PIDKEY
or
...\Registration\2000.0x0000\PIDKEY
A:
I found the product key for Visual Studio 2008 Professional under a slightly different
key:
HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY
it was listed without the dashes as stated above.
A:
For Visual Studio 2005:
If you do have an installed Visual Studio 2005 however, and want to find out the serial number you’ve used to install it because you don’t have a clue where you put that shiny sticker, you can. It is, like most things in Windows, in the registry.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
In order to convert the value in that key to an actual serial number you have to put a dash ( – ) after evert 5 characters of the code.
From: http://www.gooli.org/blog/visual-studio-2005-serial-number/
For Visual Studio 2008 it's supposed to be:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
However I noted that the the Data field for PIDKEY is only filled in the 1000.0x000 (or 2000.0x000) sub folder of the above paths.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tools/Guide to Creating an Image Looper in GWT
I'm setting out to create a weather model display tool (web application), and from what I've seen, I'm really liking the idea of using Google Web Tools, and especially the SmartGWT toolkit. My one biggest sticking point at this point is finding some way to create a sort of image "looper" (displaying all images in a particular "set" one after another, not unlike a slide show). For reference, I need functionality (at least on a basic level) similar to this: http://rapidrefresh.noaa.gov/hrrrconus/jsloop.cgi?dsKeys=hrrr:&runTime=2012053007&plotName=cref_sfc&fcstInc=60&numFcsts=16&model=hrrr&ptitle=HRRR%20Model%20Fields%20-%20Experimental&maxFcstLen=15&fcstStrLen=-1&resizePlot=1&domain=full&wjet=1 (though it certainly need not be exactly like that).
Does anyone know of (ideally) some sort of GWT module that can do image looping? Or if not, does it sound like something an intermediate programmer could figure out without too much trouble (I'm willing to accept a challenge), even if I've never explicitly used GWT before? I'm sure I could whip together something that pulls each image in as it goes through a loop, but prefetching them would be even more ideal.
Please comment if you need clarification on anything!
A:
As far as I'm aware there's not a pre-fab solution to do this, although maybe SmartGWT has something I don't know about. In any case, it won't be too hard to roll your own. Here's some code to get you started:
public class ImageLooper extends Composite {
// List of images that we will loop through
private final String[] imageUrls;
// Index of the image currently being displayed
private int currentImage = 0;
// The image element that will be displayed to the user
private final Image image = new Image();
// The Timer provides a means to execute arbitrary
// code after a delay or at regular intervals
private final Timer imageUpdateTimer = new Timer() {
public void run() {
currentImage = (currentImage + 1) % images.length;
image.setUrl(imageUrls[currentImage]);
}
}
// Constructor. I'll leave it to you how you're going to
// build your list of image urls.
public ImageLooper(String[] imageUrls) {
this.imageUrls = imageUrls;
// Prefetching the list of images.
for (String url : imageUrls)
Image.prefetch(url);
// Start by displaying the first image.
image.setUrl(imageUrls[0]);
// Initialize this Composite on the image. That means
// you can attach this ImageLooper to the page like you
// would any other Widget and it will show up as the
// image.
initWidget(image);
}
// Call this method to start the animation
public void playAnimation() {
// Update the image every two seconds
imageUpdateTimer.scheduleRepeating(2000);
}
// Call this method to stop the animation
public void stopAnimation() {
imageUpdateTimer.cancel();
}
}
One annoying thing with this implementation is that you have no way of knowing when your list of images has finished loading; Image.prefetch doesn't have a callback to help you here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clean up sha256sum output
running sha256sum folder/file` returns
711ad4b9939e0e20e591d753103717f40e794babc4129a0670fd342309bec5af *folder/file
I want to output the sum with just the filename next to it so that it looks like:
711ad4b9939e0e20e591d753103717f40e794babc4129a0670fd342309bec5af file
How do I go about changing the output?
A:
You could try
sha256sum /path/to/file | head -c 64
This is for taking only the hash of 64 characters.
As there were mentioned before, you should read the man of sed for more advanced manipulation.
But to have the output that you want, I mean without folders, a simple way is running the command from the folder where the file is located ;)
In your case:
cd folder/ ; sha256sum file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need help in SQL Select Query
Need some help with this query, I just want to know if what I am doing is fine or do I need JOIN to get it better. Sorry if this a silly question but I am little worried as I query the same table thrice. Thanks in advance
Select *
from TableA
where (A_id in (1, 2, 3, 4)
and flag = 'Y') or
(A_id in
(select A_id from TableB
where A_id in
(Select A_id from TableA
where (A_id in (1, 2, 3, 4)
and flag = 'N')
group by A_id
having sum(qty) > 0)
)
Relation between TableA and TableB is one-to-many
Condition or Logic:
if the flag is true, the data can be selected without further checks
if the flag is false, we have to refer TableB to see if sum of the qty column is greater than 0
A:
Your approach is indeed way too complicated. Select from A where flag = Y or the sum of related B > 0. Do the latter in a subquery.
select *
from a
where a_id in (1,2,3,4)
and
(
flag = 'Y'
or
(select sum(qty) from b where b.a_id = a.a_id) > 0
)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Google's In App Purchase work on all markets?
I was wondering if Google's In App Purchase works on all markets. Not able to find much info on this online. Thanks for your help!
A:
In short, no. It depends on the Android Market application and related services. If the device doesn't have Market, IAB won't work. BTW, Amazon won't allow applications linking or invoking the Android Market. They have their own in-app billing solution, but it's currently in closed beta. You can try applying if you are already on the Amazon Appstore.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove row containing array of NaN?
I have a df like this:
num1 num2
0 [2.0] 10
1 [3.0] 20
2 [4.0] 30
3 [5.0] 40
4 [6.0] 50
5 [nan] 60
6 [nan] 70
7 [10.0] 80
8 [nan] 90
9 [15.0] 100
num1 column contains arrays of floats. [nan] is a numpy array containing a single np.NaN.
I am converting this to integers via this:
df['num1'] = list(map(int, df['num1']))
If I just use this df:
num1 num2
0 [2.0] 10
1 [3.0] 20
2 [4.0] 30
3 [5.0] 40
4 [6.0] 50
This works when there are no [nan] and I get:
num1 num2
0 2.0 10
1 3.0 20
2 4.0 30
3 5.0 40
4 6.0 50
But if I include the full df with [nan] I get the error:
`ValueError: cannot convert float NaN to integer`
I tried doing:
df[df['num1'] != np.array(np.NaN)]
But this gave the error:
TypeError: len() of unsigned object
How can I get the desired output:
num1 num2
0 2.0 10
1 3.0 20
2 4.0 30
3 5.0 40
4 6.0 50
5 10.0 80
6 15.0 100
A:
Try this -
df['num1'] = df['num1'].apply(lambda x: x[0]).dropna() # unlist the list of numbers (assuming you dont have multiple)
df['num1'] = list(map(int, df['num1'])) # map operation
print(df)
Output
num1 num2
0 2 10
1 3 20
2 4 30
3 5 40
4 6 50
7 10 80
9 15 100
Timings (depends on size of data)
# My solution
# 2.6 ms ± 327 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# @O.Suleiman's solution
# 2.8 ms ± 457 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# @ Anton vBR's solution
# 2.96 ms ± 504 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to modify google analytics code using google tag manager
I have the google analytics tracking code running on my site which I have added through google tag manager.
The code from google analytics in general looks like this:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');
however since I have added it through tag manager I only have the tag manager code in my page code which is:
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=XXX-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','XXX-XXXXXX');</script>
<!-- End Google Tag Manager -->
Now I would need to add some lines of code in the google analytics code between:
ga('create', 'UA-XXXXXXXX-1', 'auto');
add *code* here
ga('send', 'pageview');
How can I do that? I did not find any possibility yet to modify the original analytics code within tag manager so would appreciate any assistance.
A:
That depends on what you want to do with that code.
Option 1
If it's something 'standard', Tag Manager should give you a fairly straight-forward form when you add a Universal Analytics tag - you can use this to set certain options within the tag:
Option 2
If this doesn't cover it, you can change the type of your GA tag to a custom js tag, put the original snippet in and make your changes directly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Configuration error on Run Dist Play Application
I have created a dist of my Play application with sbt clean dist.
Then I have extracted the zip file inside the universal folder.
When I run the application with bin/app-name I get the following error:
7626kfpi3: Configuration error
at play.api.libs.crypto.CryptoConfigParser.get$lzycompute(Crypto.scala:498)
at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:465)
at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:463)
at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
at com.google.inject.internal.BoundProviderFactory.provision(BoundProviderFactory.java:72)
at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:61)
at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:62)
at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:61)
at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
at com.google.inject.Guice.createInjector(Guice.java:96)
at com.google.inject.Guice.createInjector(Guice.java:84)
at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:181)
at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:123)
at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
at play.core.server.ProdServerStart$.start(ProdServerStart.scala:47)
at play.core.server.ProdServerStart$.main(ProdServerStart.scala:22)
at play.core.server.ProdServerStart.main(ProdServerStart.scala)
I have tried to remove all extra configuration properties from conf/application.conf file, but this had not resolved the problem.
A:
You probably need to add a secret key as discussed here: https://www.playframework.com/documentation/2.6.x/ApplicationSecret
Play should generate a better error message for that scenario (it did in the past).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Need to remove multiple entity objects when using Entity Framework 4.0
I am new in Entity Framework. I want to remove multiple entities in one database context. If I used DBContext.Remove(Object) then It delete only the one entity from database. Please consider my code:
CCSRequest objCCSRequest = DBContext.CCSRequest.Find(ccsRequestId);
if (objCCSRequest != null)
{
DBContext.CCSRequest.Remove(objCCSRequest);
DBContext.SaveChanges();
}
CCProducts objCCProducts = DBContext.CCProducts.Find(ccsRequestId);
if (objCCProducts != null)
{
DBContext.CCProducts.Remove(objCCProducts);
DBContext.SaveChanges();
}
I want to remove entity in both CCSRequest and CCProducts table.
Thank you in advance.
A:
If you want to have a loop that will remove entities of different types you might use this:
object[] entities = new object[]{
DBContext.CCSRequest.Find(ccsRequestId),
DBContext.CCProducts.Find(ccsRequestId)
};
foreach(object entity in entities)
{
DBContext.Entry(entity).State = EntityState.Deleted;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I create a line that is perpendicular to a plane of coordinates
I have three datasets (numpy arrays) of coordinates (X, Y and X) representing a planar surface. I need to create a line that is perpendicular to the plane surface.
I got the data from another file, because I can't share it easily with you, I created a random pandas dataset the code I used to generate the data surface is as following:
cor_CTV = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns = list('xyz'))
linear_data = np.c_[cor_CTV["x"], cor_CTV["y"], cor_CTV["z"]]
mn = np.min(linear_data, axis=0)
mx = np.max(linear_data, axis=0)
X,Y = np.meshgrid(np.linspace(mn[0], mx[0], 20), np.linspace(mn[1], mx[1], 20))
XX = X.flatten()
YY = Y.flatten()
A = np.c_[linear_data[:,0], linear_data[:,1], np.ones(linear_data.shape[0])]
C,_,_,_ = scipy.linalg.lstsq(A, linear_data[:,2])
Z = C[0]*X + C[1]*Y + C[2]
I would be very grateful if anyone can help me.
A:
You can use the cross product of the relative position of any two non-colinear points:
O = np.array([X[0][0], Y[0][0], Z[0][0]]) # Corner to be used as the origin
V1 = np.array([X[1][0], Y[1][0], Z[1][0]]) - O # Relative vectors
V2 = np.array([X[0][1], Y[0][1], Z[0][1]]) - O
V1 = V1 / scipy.linalg.norm(V1) # Normalise vectors
V2 = V2 / scipy.linalg.norm(V2)
# Take the cross product
perp = np.cross(V1, V2)
Example result:
[ 0.18336919 -0.0287231 -0.98260979]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IntelliJ IDEA seems to be ignoring code formatting
I've been attempting to get my Intellij IDEA to confirm to a google-like Java standard - however both imports and manual settings seem to be ignored.
Here's how my indentations are currently set:
However my code still formats at 4 spaces, and when I reformat it goes to 4 spaces as well.
Thanks in advance!
A:
This is the setting for your GoogleStyle scheme. But your project most likely doesn't use it. It's not enough to just select it in the combobox. You need to import this scheme into your project.
Click Manage... and Copy to Project, and it should work as expected.
Also, make sure you're setting language-spefic settings, so instead Code Style select Code Style > Java.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle V$OSSTAT
The Oracle view V$OSSTAT holds a few operating statistics, including:
IDLE_TICKS Number of hundredths of a second that a processor has been idle, totalled over all processors
BUSY_TICKS Number of hundredths of a second that a processor has been busy executing user or kernel code, totalled over all processors
The documentation I've read has not been clear as to whether these are ever reset. Does anyone know?
Another question I have is that I'd like to work out the average CPU load the system is experiencing. To do so I expect I have to go:
busy_ticks / (idle_ticks + busy_ticks)
Is this correct?
Update Nov 08
Oracle 10g r2 includes a stat called LOAD in this table. It provides the current load of the machine as at the time the value is read. This is much better than using the other information as the *_ticks data is "since instance start" not as of the current point in time.
A:
You'll need to include 'IOWAIT_TICKS` if they are available.
IDLE_TICKS - Number of hundredths of a
second that a processor has been idle,
totaled over all processors
BUSY_TICKS - Number of hundredths of a second that a
processor has been busy executing
user or kernel code, totaled over all
processors
IOWAIT_TICKS - Number of hundredths of a second that a
processor has been waiting for I/O to
complete, total led over all
processors
Here is a query.
SELECT (select value from v$osstat where stat_name = 'BUSY_TICKS') /
(
NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) +
NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) +
NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0)
)
FROM DUAL;
On 10.2 and later the names _TICKS have been changed to _TIME.
Cumulative values in dynamic views are reset when the database instance is shutdown.
See Automatic Performance Statistics and v$OSStat for more info.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Queue messages not being moved to the poison queue
I have a job that imports files into a system. Everytime a file is imported, we create a blob in azure and we send a message with instructions to a queue so that the data is persisted in SQL accordingly. We do this using azure-webjobs and azure-webjobssdk.
We experienced an issue in which after the messages failed more than 7 times, they didn't move to the poision queue as expected. The code is the following:
Program.cs
public class Program
{
static void Main()
{
//Set up DI
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = AppSettingsHelper.Get("StorageConnectionString");
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel), NameResolver = new QueueNameResolver() };
config.Queues.MaxDequeueCount = 7;
config.UseTimers();
//Pass configuration to JobJost
var host = new JobHost(config);
host.RunAndBlock();
}
}
Functions.cs
public class Functions
{
private readonly IMessageProcessor _fileImportQueueProcessor;
public Functions(IMessageProcessor fileImportQueueProcessor)
{
_fileImportQueueProcessor = fileImportQueueProcessor;
}
public async void FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
{
await _fileImportQueueProcessor.ProcessAsync(item);
}
}
_fileImportQueueProcessor.ProcessAsync(item) threw an exception and the message's dequeue count was properly increased and re-processed. However, it was never moved to the poison-queue. I attached a screenshot of the queues with the dequeue counts at over 50.
After multiple failures the webjob was stuck in a Pending Restart state and I was unable to either stop or start and I ended up deleting it completely. After running the webjob locally, I saw messages being processed (I assumed that the one with a dequeue count of over 7 should've been moved to the poison queue).
Any ideas on why this is happening and what can be done to have the desired behavior.
Thanks,
Update
Vivien's solution below worked.
Matthew has kind enough to do a PR that will address this. You can check out the PR here.
A:
Fred,
The FileImportQueue method being an async void is the source of your problem.
Update it to return a Task:
public class Functions
{
private readonly IMessageProcessor _fileImportQueueProcessor;
public Functions(IMessageProcessor fileImportQueueProcessor)
{
_fileImportQueueProcessor = fileImportQueueProcessor;
}
public async Task FileImportQueue([QueueTrigger("%fileImportQueueKey%")] string item)
{
await _fileImportQueueProcessor.ProcessAsync(item);
}
}
The reason for the dequeue count to be over 50 is because when _fileImportQueueProcessor.ProcessAsync(item) threw an exception it will crash the whole process. Meaning the WebJobs SDK can't execute the next task that will move the message to the poison queue.
When the message is available again in the queue the SDK will process it again and so on.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Telling git its ok to remove untracked files
Possible Duplicate:
How do you remove untracked files from your git working copy?
Is it possible to tell git to remove untracked files? Mainly something that is similar to a reset?
example:
git checkout -- index.php <-- revert my file
git checkout -- master <-- this would revert the entire repo back to the last commit on master, removing (deleting) any and all untracked files as well as reverting committed ones.
I know this is trivial to do on the shell. But I'd like to know if this can be done in Git?
A:
You need git clean but add the -df to enable removing files that are in directories from where you are. Add x to include ignored files.
So to completely clean your working directory leaving only what is in source control, issue this command:
git clean -xdf
A:
You may be looking for git clean. This will delete all untracked files. By default this ignores (does not delete) patterns in .gitignore, but git clean -x cleans those files too.
From the git clean man page:
-x
Don't use the ignore rules. This allows removing all untracked
files, including build products. This can be used (possibly in
conjunction with git reset) to create a pristine working directory
to test a clean build.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove Duplicate Time Zones From SELECT query
I need help removing duplicate time zone records from my select query without deleting them. The current result is as follows:
Employee ID # Presence Presence Start Time Presence End Time GMT Presence Start Time
691 Out Of Office 2020-02-01 04:30:00 2020-02-01 14:30:00 2020-02-01 12:30:00
691 Out Of Office 2020-02-01 05:30:00 2020-02-01 15:30:00 2020-02-01 12:30:00
691 Out Of Office 2020-02-01 07:30:00 2020-02-01 17:30:00 2020-02-01 12:30:00
691 Out Of Office 2020-02-01 13:30:00 2020-02-01 23:30:00 2020-02-01 12:30:00
691 Out Of Office 2020-02-01 20:30:00 2020-02-02 06:30:00 2020-02-01 12:30:00
435 Out Of Office 2020-02-01 00:15:00 2020-02-01 09:00:00 2020-01-31 16:15:00
5681 Out Of Office 2020-02-02 07:00:00 2020-02-02 15:45:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 08:00:00 2020-02-02 16:45:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 10:00:00 2020-02-02 18:45:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 16:00:00 2020-02-03 00:45:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 23:00:00 2020-02-03 07:45:00 2020-02-02 15:00:00
1927 Out Of Office 2020-02-02 07:00:00 2020-02-02 18:15:00 2020-02-02 15:00:00
1927 Out Of Office 2020-02-02 08:00:00 2020-02-02 19:15:00 2020-02-02 15:00:00
1927 Out Of Office 2020-02-02 10:00:00 2020-02-02 21:15:00 2020-02-02 15:00:00
1927 Out Of Office 2020-02-02 16:00:00 2020-02-03 03:15:00 2020-02-02 15:00:00
1927 Out Of Office 2020-02-02 23:00:00 2020-02-03 10:15:00 2020-02-02 15:00:00
The table returns duplicate GMT start times for the same employee, the database appears to be duplicating the results based on different time zones.
I just want to remove the duplicate GMT Presence Start Times
Employee ID # 691 should have 1 row, same with 5681 and 1927. Can someone please help?
A:
You can use a GROUP BY clause to give unique values of GMT Presence Start Time for each employees Presence in the log. You need to use an aggregation function on the Presence Start Time and Presence End Time functions; I've chosen MIN in my example, but you might want something else.
SELECT [Employee ID #],
[Presence],
MIN([Presence Start Time]),
MIN([Presence Start Time]),
[GMT Presence Start Time]
FROM data
GROUP BY [Employee ID #], [Presence], [GMT Presence Start Time]
Output (for your sample data):
Employee ID # Presence Presence Start Time Presence Start Time GMT Presence Start Time
435 Out Of Office 2020-02-01 00:15:00 2020-02-01 09:00:00 2020-01-31 16:15:00
691 Out Of Office 2020-02-01 04:30:00 2020-02-01 14:30:00 2020-02-01 12:30:00
1927 Out Of Office 2020-02-02 07:00:00 2020-02-02 18:15:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 07:00:00 2020-02-02 15:45:00 2020-02-02 15:00:00
Demo on SQLFiddle
Alternatively you can use window functions on the Presence Start and End times:
SELECT DISTINCT [Employee ID #],
[Presence],
FIRST_VALUE([Presence Start Time]) OVER (PARTITION BY [Employee ID #], [Presence], [GMT Presence Start Time] ORDER BY [Presence Start Time]) AS [Presence Start Time],
FIRST_VALUE([Presence End Time]) OVER (PARTITION BY [Employee ID #], [Presence], [GMT Presence Start Time] ORDER BY [Presence End Time]) AS [Presence End Time],
[GMT Presence Start Time]
FROM data
Output:
Employee ID # Presence Presence Start Time Presence End Time GMT Presence Start Time
435 Out Of Office 2020-02-01 00:15:00 2020-02-01 09:00:00 2020-01-31 16:15:00
691 Out Of Office 2020-02-01 04:30:00 2020-02-01 14:30:00 2020-02-01 12:30:00
1927 Out Of Office 2020-02-02 07:00:00 2020-02-02 18:15:00 2020-02-02 15:00:00
5681 Out Of Office 2020-02-02 07:00:00 2020-02-02 15:45:00 2020-02-02 15:00:00
Demo on SQLFiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento edit responsive css to rearrange column
My site's product page is two column
col-main contains product and col-right sidebar displays some bocks like (related products, ads)
These two columns works perfect in desktop but when the product page is viewed from mobile device the right column displays first. The users have to scroll down to view the product.
If you understand my problem eg: A user visits a product page from his mobile device and first thing it shows is the related products. visitors leave the site from there most visitors dont tend to scroll down.
if some one can help me make the col-main to appear first and col-right second.
down is my theme's main-responsive.css file
Theme Link: http://accessshopthemes.com/magento-themes/accessshop-lite/
Eg Page link (try resizing browser window): http://accessshopthemes.com/demo/access-shop/cute-2014-navy-stand-collar-ruffles-buttons-coat.html
@media (max-width: 1200px) {
.right-header-top .welcome.col-sm-3{
width: 100%;
text-align: right;
}
.right-header-top .col-sm-9{
width: 100%;
}
.product-image {
max-width: none;
width: 100%;
}
.col-right{
width: 23%;
}
.block-content > img {
width: 100%;
}
.box-left {
width: 75%;
}
.box-left > img, .box-right > img {
width: 100%;
}
.box-right{
width: 24%;
}
.responsive-features-left{
width: 65%;
}
.responsive-features-right{
width: 30%;
}
.responsive-display-img > img {
width: 100%;
}
.right-image > img {
width: 100%;
}
.imgresponsive {
width: 100%;
}
.productimage label{
top: 170px;
}
.col-left {
width: 25%;
}
.col2-layout .col-main {
float: left;
width: 70%;
}
.top-cart{
border: none;
}
#sequence > .sequence-canvas li > .banner-container{
width: 100%;
}
.col3-layout .col-main {
width: 44%;
}
}
@media (max-width: 992px) {
header .col-sm-4, header .col-sm-6 {
width: 100%;
}
header .col-sm-6.col-sm-offset-2{
margin-left: 0;
margin-bottom: 20px;
float: left;
}
.logo{
text-align: center;
float: none;
}
.services{
width: 49%;
margin-bottom: 5px;
}
.services:nth-of-type(2n){
border-right: none;
}
.maincontent.col1-layout{
overflow: hidden;
}
.categories-search input[type="text"]{
width: 240px !important;
}
.product-options-bottom .add-to-links{
position: static;
}
.related-items {
margin-top: 36px;
}
.productimage > img {
height: auto;
width: 100%;
}
.display-onhover .add-to-links{
top: 10px;
}
.display-onhover .actions{
top: 92px;
}
.title{
width: 90%;
}
.subtitle{
width: 50%;
}
.col3-layout .col-main {
width: 42%;
}
}
@media (max-width: 767px) {
header, .maincontent, .brands, #before-footer, footer{
padding: 0 1%;
}
#before-footer{
padding: 10px 1%;
}
.col-sm-4.wow.slideInRight.animated {
margin-left: 100px;
}
.focus-content .col-sm-4{
clear: both;
float: left;
margin-bottom: 10px;
width: 100%;
}
.right-links{
padding-bottom: 15px;
}
.block-footer-bottom-right-links.pull-right, .block-copyright.pull-left{
float: none !important;
text-align: center;
clear: both;
width: 100%;
}
.block-footer-bottom-right-links ul{
float: none;
margin: 10px 0;
}
.header-top .col-sm-5{
text-align: center;
}
.header-top .col-sm-7{
width: 100%;
}
.col-sm-8.pull-right{
float: none;
text-align: center;
width: 100%;
}
/* .mini-products-list .product-details{
text-align: center;
}*/
.navbar-form.navbar-right {
clear: both;
display: inline-block;
}
.col-sm-12.top-search {
clear: both;
float: none;
}
.col-sm-12.top-cart {
clear: both;
float: none;
}
.list-inline.pull-right.topcart {
float: none !important;
}
.col-main{
width: 100% !important;
}
.col-right.sidebar{
width: 100%;
margin-left: 0;
}
.add-to-box{
min-height: 150px;
}
.product-img-column{
width: 100%;
}
.responsive-features-left{
width: 100%;
}
.responsive-features-right{
width: 100%;
}
.right-header-top{
text-align: center;
}
.js #menu {
display:none;
}
.product-options-bottom .add-to-links{
position: absolute;
}
.imgresponsive{
width: auto;
}
.dropdown-menu {
position: relative;
width: 100%;
box-shadow: none;
border: none;
}
.dropdown li {
padding: 5px 0;
width: 100%;
z-index: 999;
}
.level1.dropdown-menu{
left: 0;
}
.col-left{
width: 100%;
}
.products-grid .item{
width: 100%;
}
.productimage > img{
width: auto;
}
.maincontent {
overflow: hidden;
}
.header .welcome-msg, .welcome{
float: none;
}
.col3-layout .col-main {
width: 98% !important;
}
.col2-layout .col-main {
width: 98% !important;
}
.navbar-nav > li.parent > a:after{
content: '';
}
}
@media (max-width: 640px){
.newsletter-box .box-left, .newsletter-box .box-right{
width: 100%;
border: none;
}
.newsletter-box .box-left{
border-bottom: 1px solid #CCC;
}
.newsletter-box .box-right{
border-top: 1px solid #fff;
}
.banner{
display: none;
}
.left-image{
width: 100%;
}
.middle-text{
width: 100%;
}
}
@media (max-width: 480px) {
.services{
width: 100%;
margin-bottom: 15px;
border-right: none;
border-bottom: 1px solid #DDD;
}
.services:nth-of-type(4){
border-bottom: none;
}
.welcome.pull-left{
display: block;
float: none !important;
margin-bottom: 10px;
text-align: center;
}
.right-header-top{
padding: 0;
}
.categories-search select{
width: 90px;
}
.categories-search input[type="text"]{
width: 120px !important;
}
.custom-link{
display: none;
}
.right-header-top {
text-align: center;
}
.sorter .amount, .sorter .sort-by, .sorter .limiter, .sorter .view-mode, .sorter .pages{
width: 100%;
}
}
<?php
/**
* @category design
* @package accessshop_lite_default
* @copyright Copyright (c) 2015 AccessShop Themes (http://www.accessshopthemes.com)
* Template for Mage_Page_Block_Html
*/
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="<?php echo $this->getLang(); ?>"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="<?php echo $this->getLang(); ?>"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="<?php echo $this->getLang(); ?>"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="<?php echo $this->getLang(); ?>"> <!--<![endif]-->
<head>
<?php echo $this->getChildHtml('head'); ?>
</head>
<body<?php echo $this->getBodyClass()?' class="'.$this->getBodyClass().'"':'' ?>>
<?php echo $this->getChildHtml('after_body_start'); ?>
<?php echo $this->getChildHtml('global_notices'); ?>
<header>
<?php echo $this->getChildHtml('header'); ?>
</header>
<?php echo $this->getChildHtml('slider'); ?>
<div class="maincontent col2-layout">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php echo $this->getChildHtml('breadcrumbs'); ?>
<aside class="col-right sidebar">
<?php echo $this->getChildHtml('right'); ?>
</aside>
<div class="col-main">
<?php echo $this->getChildHtml('global_messages'); ?>
<?php echo $this->getChildHtml('content'); ?>
</div>
</div>
</div>
</div>
</div>
<div class="brands">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php echo $this->getChildHtml('home-block-brands'); ?>
</div>
</div>
</div>
</div>
<section id="before-footer">
<?php echo $this->getChildHtml('before-footer'); ?>
</section>
<footer id="footer">
<?php echo $this->getChildHtml('footer'); ?>
</footer>
<?php echo $this->getChildHtml('before_body_end'); ?>
<?php echo $this->getAbsoluteFooter(); ?>
</body>
</html>
A:
With your current markup, you can do the following:
Add a custom class reorder to the parent container of the three divs.
Assign flexible box layout the the parent container.
Target the mobile screen size layout using media queries and reorder them using order property.
Check the browser compatibility table for Flexbox
@media (max-width: 768px) {
.reorder {
display: flex;
flex-flow: column nowrap;
}
.col-main {
order: 1;
}
.col-right {
order: 2;
}
}
<div class="col-md-12 reorder">
<div class="breadcrumbs">1</div>
<aside class="col-right sidebar ">2</aside>
<div class="col-main">3</div>
</div>
Tested on your sample page for output:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ionic2 Popover Change Width
I want to change the popover width of only 1 page.
I tried this:
I do not want to use this $popover-ios-width in variable.scss files
since it changes the width on all pages.
A:
You can create a custom class for only this popover and pass it in the cssClass on it's options
let's say you have this:
.custom-popover {
width: 60%;
}
In your popover creation you'll just insert it as the cssClass on the options
const customPopOver = this.popover.create({ yourPopoverPage, yourData, { cssClass: 'custom-popover'}});
customPopOver.present();
Hope this helps :D
A:
@gabriel-barreto's answer is totally fine. However, I guess it needs an additional consideration in other versions.
In Ionic 3.6 the custom class is added to the <ion-popover> element. In order to override the default width rule set in .popover-content class, your selector should be:
.custom-popover .popover-content {
width: 60%;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
System.InvalidOperationException 'n' index in collection change event is not valid for collection of size '0'
I'm getting this exception when triggering a CollectionChanged event on a custom implementation of INotifyCollectionChanged:
An exception of type 'System.InvalidOperationException' occurred in
PresentationFramework.dll but was not handled in user code
Additional information: '25' index in collection change event is not
valid for collection of size '0'.
A XAML Datagrid is bound to the collection as ItemsSource.
How can this exception occurrence be avoided?
The code follows:
public class MultiThreadObservableCollection<T> : ObservableCollection<T>
{
private readonly object lockObject;
public MultiThreadObservableCollection()
{
lockObject = new object();
}
private NotifyCollectionChangedEventHandler myPropertyChangedDelegate;
public override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
lock (this.lockObject)
{
myPropertyChangedDelegate += value;
}
}
remove
{
lock (this.lockObject)
{
myPropertyChangedDelegate -= value;
}
}
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eh = this.myPropertyChangedDelegate;
if (eh != null)
{
Dispatcher dispatcher;
lock (this.lockObject)
{
dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
let dpo = nh.Target as DispatcherObject
where dpo != null
select dpo.Dispatcher).FirstOrDefault();
}
if (dispatcher != null && dispatcher.CheckAccess() == false)
{
dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => this.OnCollectionChanged(e)));
}
else
{
lock (this.lockObject)
{
foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
{
nh.Invoke(this, e);
}
}
}
}
}
The error occurs in the following line:
nh.Invoke(this, e);
Thanks!
A:
The point is that (by design) nh.Invoke(this, e); is called asynchronously.
When the collection is bound, in a XAML, and the collection changes, System.Windows.Data.ListCollectionView's private method AdjustBefore is called. Here, ListCollectionView checks that the indexes provided in the eventArgs belong to the collection; if not, the exception in the subject is thrown.
In the implementation reported in the question, the NotifyCollectionChangedEventHandler is invoked at a delayed time, when the collection may have been changed, already, and the indexes provided in the eventArgs may not belong to it any more.
A way to avoid that the ListCollectionView performs this check is to replace the eventargs with a new eventargs that, instead of reporting the added or removed items, just has a Reset action (of course, efficiency is lost!).
Here's a working implementation:
public class MultiThreadObservableCollection<T> : ObservableCollectionEnh<T>
{
public override event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
var eh = CollectionChanged;
if (eh != null)
{
Dispatcher dispatcher = (from NotifyCollectionChangedEventHandler nh in eh.GetInvocationList()
let dpo = nh.Target as DispatcherObject
where dpo != null
select dpo.Dispatcher).FirstOrDefault();
if (dispatcher != null && dispatcher.CheckAccess() == false)
{
dispatcher.Invoke(DispatcherPriority.DataBind, (Action)(() => this.OnCollectionChanged(e)));
}
else
{
// IMPORTANT NOTE:
// We send a Reset eventargs (this is inefficient).
// If we send the event with the original eventargs, it could contain indexes that do not belong to the collection any more,
// causing an InvalidOperationException in the with message like:
// 'n2' index in collection change event is not valid for collection of size 'n2'.
NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
foreach (NotifyCollectionChangedEventHandler nh in eh.GetInvocationList())
{
nh.Invoke(this, notifyCollectionChangedEventArgs);
}
}
}
}
}
References:
https://msdn.microsoft.com/library/system.windows.data.listcollectionview(v=vs.110).aspx
https://msdn.microsoft.com/library/ms752284(v=vs.110).aspx
|
{
"pile_set_name": "StackExchange"
}
|
Q:
after downloading ubuntu can I revert back to Windows 8?
I am thinking of trying out Ubuntu and if I don't care for it, can I easily revert back to windows 8 or can it be run side by side with windows 8?
A:
The best thing to do is to choose Try Ubuntu, before you do any thing else.
Once you try it, and you decide that you like it, you can install it along side windows,
and yes if you decide that you don't want it, you can revert back to windows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Selenium - Can click, getText, etc. on an element except hover
I'm at a complete loss on this one. We have an li element that has a single a element under each. They have no javascript, nor anything unusual about them.
However, trying to hover over one is proving to be impossible! I can click, get text, scroll to, any other action on any of these, but for 3 of the 20 I can NOT do a hover. There are 20 list elements and I can hover over all except 3 of them (elements 5, 10 and 15). I've tried using the li element, using the a element under the li element, many other solutions.
In every case, selenium finds the element and can interact with it in every way except hovering. Any suggestions? Here is the HTML code:
<div id="level1-all-departments" style="display: block;">
<li data-parent="0" id="31447" class="selectedLinkBold">
<a href="https://this.website.com/holiday.html" aria-expanded="true">Holiday & Seasonal</a>
</li>
<li data-parent="0" id="31356" class="">
<a href="https://this.website.com/appliances.html" aria-expanded="false">Appliances</a>
</li>
<li data-parent="0" id="31357" class="">
<a href="https://this.website.com/auto.html" aria-expanded="false">Automotive & Tires</a>
</li>
<li data-parent="0" id="31358" class="">
<a href="https://this.website.com/baby-kids.html" aria-expanded="false">Baby, Kids & Toys</a>
</li>
<li data-parent="0" id="557612" class="">
<a href="https://this.website.com/clothing-handbags.html" aria-expanded="false">Clothing, Luggage, & Handbags</a>
</li>
<li data-parent="0" id="31359" class="">
<a href="https://this.website.com/computers.html" aria-expanded="false">Computers</a>
</li>
<li data-parent="0" id="31360">
<a href="https://this.website.com/electronics.html" aria-expanded="false">Electronics</a>
</li>
<li data-parent="0" id="252601">
<a href="https://this.website.com/funeral.html" aria-expanded="false">Funeral</a>
</li>
<li data-parent="0" id="31363">
<a href="https://this.website.com/furniture.html" aria-expanded="false">Furniture & Mattresses</a>
</li>
<li data-parent="0" id="31361">
<a href="https://this.website.com/gift-cards-tickets-floral.html" aria-expanded="false">Gift Cards, Tickets & Floral</a>
</li>
<li data-parent="0" id="31362">
<a href="https://this.website.com/grocery-household.html" aria-expanded="false">Grocery & Household</a>
</li>
<li data-parent="0" id="31365">
<a href="https://this.website.com/health-beauty.html" aria-expanded="false">Health & Beauty</a>
</li>
<li data-parent="0" id="31366">
<a href="https://this.website.com/home-and-decor.html" aria-expanded="false">Home & Kitchen</a>
</li>
<li data-parent="0" id="31364">
<a href="https://this.website.com/hardware.html" aria-expanded="false">Home Improvement</a>
</li>
<li data-parent="0" id="31367">
<a href="https://this.website.com/jewellery-fashion.html" aria-expanded="false">Jewellery, Watches & Sunglasses</a>
</li>
<li data-parent="0" id="31368">
<a href="https://this.website.com/office-products.html" aria-expanded="false">Office Products</a>
</li>
<li data-parent="0" id="31369">
<a href="https://this.website.com/patio-lawn-garden.html" aria-expanded="false">Patio, Lawn & Garden</a>
</li>
<li data-parent="0" id="31489">
<a href="https://this.website.com/pet-supplies.html" aria-expanded="false">Pet Supplies</a>
</li>
<li data-parent="0" id="31370">
<a href="https://this.website.com/sports-fitness.html" aria-expanded="false">Sports & Fitness</a>
</li>
<li data-parent="0" id="439601">
<a href="https://this.website.com/view-more.html" aria-expanded="false">View More Categories</a>
</li>
Here is the code I'm using to successfully hover (I stuck with the index because that removed the most other potential issues, however, I've tried about every other way to identify the element):
@FindBy(xpath = "//div[@id='level1-all-departments']//a[4]/..")
private WebElement listElement;
Actions aAction = new Actions(wDriver);
aAction.moveToElement(listElement).build().perform();
Thanks
-Greg
A:
Was able to get this working using javaScript hover as suggested by Christine.
mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover',true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) wDriver).executeScript(mouseOverScript, element);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Merge, delete when not on Source
I have an issue with a merge statement into a FACT TABLE
It was pretty simple until the users started to delete records from the source.
Current SQL:
Set Count = 1
WHEN NOT MATCHED
INSERT
WHEN MATCHED
UPDATED
New SQL:
So in this example, a record has been deleted from the source, it no longer matches but there is nothing to insert. I would like it the count to be set to 0.
WHEN DELETED FROM SOURCE
Set Count = 0
.
Source
Bob Jones | 1111
Mary Jones | 1112
James Jones | 1113
Helen Jones | 1114
TARGET
Bob Jones | 1111 | Count 1
Mary Jones | 1112| Count 1
James Jones | 1113| Count 1
Helen Jones | | 1114| Count 1
Peter Market | 1115| Count 0
I’m loading to a fact table using a merge and now they are just blanket deleting records, my facts are off. This must be accounted for somehow?
Thank you for any help at all.
A:
You could do a merge using the target full outer joined with source, but id has to a unique key across both for this to work.
MERGE INTO target tgt
USING (SELECT CASE
WHEN s.id IS NULL THEN t.name --write this logic for all other non id columns.
ELSE s.name
END AS name,
coalesce(s.id, t.id) AS id, --use target's id when no source id is available
CASE
WHEN s.id IS NULL THEN 0 --zero for non matching ids
ELSE 1
END AS source_count
FROM target t
full outer join source s
ON s.id = t.id) src
ON ( src.id=tgt.id)
WHEN matched THEN
UPDATE SET tgt.name = src.name,
tgt.source_count = src.source_count
WHEN NOT matched THEN
INSERT (id,
name,
source_count)
VALUES(src.id,
src.name,
1) ; --insert 1 by default for new rows
Demo
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Audit failed for wanting to recommend deletion to an answer that reads like a joke solution
So doing some review queue stuff a few minutes ago and I came across this item. The original question is about remotely shutting down a PC that has no apparent RDP connectivity. The answer I wanted to delete was basically recommending building a Rube Goldberg contraption:
Find an old computer with a CD-ROM drive. Install linux. Name it
HOMECOMPUTERSHUTDOWNROBOT. Find a plastic stick, about 2 inches long.
Superglue it to the CD-ROM door so that it sticks straight out from
the computer. Position the old computer so that the stick points at
the power button for the computer you want to shut down. Use old books
as necessary to prop the computer up to the needed height to do so.
When you want to turn off the computer, SSH into
HOMECOMPUTERSHUTDOWNROBOT. In the terminal, use the eject command to
eject the CD drive. The plastic stick will push the power button of
the computer not supporting RDP and turn it off.
Okay this is a cute idea that shows a creative use of an ejectable optical drive mechanism. But come on? I failed an audit for saying this idea should be deleted?
The question has a very good accepted answer as well as a much higher ranked alternative answer. This joke answer was posted hours after those other answers and really adds not much.
Screenshot of the audit context here:
A:
As has already been mentioned several times in all the "failed audit" meta questions mods have no say in what questions go into audits.
Technically though, that is an actual valid workable answer to the question. That there are other and better answers is irrelevant.
It sounds ludicrous, and it probably was meant as a joke but it is a solution that would probably work. That makes it an actual answer.
Mods, while having a greater say in what happens on the site, are slightly constrained in how they can act. Unanimously running rampage across the site deleting anything that we find is considered a "no-no". We try, wherever possible, to act with the community consensus of what is acceptable on our site.
Just because someone doesn't like an answer or thinks an answer it "too silly" or is "missing the point" does not make that answer any less valid than any of the other answers and mods have to keep that in mind when dealing with flags.
If you want that answer gone from the site then I would recommend asking a meta-question specifically asking whether we should allow these types of answers. Generally though (and I know this is regarding questions) we don't hate fun.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
moving from ng-include to ngRoute
I am new to Angular and learned the basics about it recently.
In my current project, I am developing a single page application. As of now, my HTML/JS setup is as per below:
HTML:
<body>
<ng-include src='"src/includes/home.html"'></ng-include>
<!-- home.html is the HTML template with static data -->
</body>
app.js:
'use strict';
var app = angular.module('MyApp',['home']);
angular
.module('home', [])
.directive('homeDir', function(){
return {
replace: true,
restrict: 'E',
templateUrl: 'src/includes/home.html'
};
});
This code is working fine but I would like to introduce routing to have better control over the pages, instead of using ng-include.
So now, my HTML looks the same and I actually dont know what to change in it while using routing.
My app.js now looks like this:
'use strict';
var app = angular.module('MyApp',['home']);
// trying to introduce routing:
angular
.module('home', ['ngResource', 'ngRoute'])
.config(['$routeProvider', '$locationProvider'],
function($routeProvider, $locationProvider){
$routeProvider.
when('/', {
templateUrl: 'src/includes/home.html',
controller: 'homeCtrl'
}).
when('/drawer', {
redirectTo: 'src/includes/home.html#drawer',
controller: 'drawerCtrl'
})
.otherwise({
redirectTo: '/'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
}
);
app.controller('homeCtrl', function($scope){
$scope.message = "some message";
console.log("homeCtrl called");
});
app.controller('drawerCtrl', function($scope){
$scope.message = "some other message";
console.log("drawerCtrl called");
});
However, I am getting an error:
Error: error:modulerr
Module Error
As per the link following the error:
This error occurs when a module fails to load due to some exception.
Why is it not loading? What am I missing? What should I change the HTML to?
UPDATE:
After including angular-route.min.js, I am getting the error:
Error: whole is undefined
beginsWith@file:///D:/projects/svn/trunk/src/libs/angular.js:8729:1
LocationHtml5Url/this.$$parse@file:///D:/projects/svn/trunk/src/libs/angular.js:8772:9
$LocationProvider/this.$get<@file:///D:/projects/svn/trunk/src/libs/angular.js:9269:5
invoke@file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
createInjector/instanceCache.$injector<@file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService@file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
invoke@file:///D:/projects/svn/trunk/src/libs/angular.js:3752:1
createInjector/instanceCache.$injector<@file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService@file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
invoke@file:///D:/projects/svn/trunk/src/libs/angular.js:3752:1
registerDirective/</<@file:///D:/projects/svn/trunk/src/libs/angular.js:5316:21
forEach@file:///D:/projects/svn/trunk/src/libs/angular.js:322:7
registerDirective/<@file:///D:/projects/svn/trunk/src/libs/angular.js:5314:13
invoke@file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
createInjector/instanceCache.$injector<@file:///D:/projects/svn/trunk/src/libs/angular.js:3604:13
getService@file:///D:/projects/svn/trunk/src/libs/angular.js:3725:11
addDirective@file:///D:/projects/svn/trunk/src/libs/angular.js:6363:28
collectDirectives@file:///D:/projects/svn/trunk/src/libs/angular.js:5801:1
compileNodes@file:///D:/projects/svn/trunk/src/libs/angular.js:5666:1
compileNodes@file:///D:/projects/svn/trunk/src/libs/angular.js:5682:1
compileNodes@file:///D:/projects/svn/trunk/src/libs/angular.js:5682:1
compile@file:///D:/projects/svn/trunk/src/libs/angular.js:5603:1
bootstrap/doBootstrap/</<@file:///D:/projects/svn/trunk/src/libs/angular.js:1343:11
$RootScopeProvider/this.$get</Scope.prototype.$eval@file:///D:/projects/svn/trunk/src/libs/angular.js:12077:9
$RootScopeProvider/this.$get</Scope.prototype.$apply@file:///D:/projects/svn/trunk/src/libs/angular.js:12175:11
bootstrap/doBootstrap/<@file:///D:/projects/svn/trunk/src/libs/angular.js:1341:9
invoke@file:///D:/projects/svn/trunk/src/libs/angular.js:3762:7
bootstrap/doBootstrap@file:///D:/projects/svn/trunk/src/libs/angular.js:1340:8
bootstrap@file:///D:/projects/svn/trunk/src/libs/angular.js:1353:5
angularInit@file:///D:/projects/svn/trunk/src/libs/angular.js:1301:37
@file:///D:/projects/svn/trunk/src/libs/angular.js:21050:5
jQuery.Callbacks/fire@file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:1037:1
jQuery.Callbacks/self.fireWith@file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:1148:7
.ready@file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:433:38
completed@file:///D:/projects/svn/trunk/src/libs/jquery-1.9.1.min.js:103:4
file:///D:/projects/svn/trunk/src/libs/angular.js
Line 9511
Edit:
Here are my HTML imports:
<head>
<title></title>
<!-- External libraries -->
<link rel="stylesheet" type="text/css" href="src/css/font-awesome-4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="src/css/headers.css">
<link rel="stylesheet" type="text/css" href="src/css/drawer.css">
<link rel="stylesheet" type="text/css" href="src/css/custom.css">
<script type="text/javascript" src="src/libs/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="src/libs/bootstrap.min.js"></script>
<script type="text/javascript" src="src/libs/angular.js"></script>
<script type="text/javascript" src="src/libs/angular-resource.js"></script>
<script type="text/javascript" src="src/libs/angular-ui-router.js"></script>
<script type="text/javascript" src="src/libs/angular-sanitize.min.js"></script>
<script type="text/javascript" src="src/libs/angular-pull-to-refresh.js"></script>
<script type="text/javascript" src="src/libs/nprogress.js"></script>
<script type="text/javascript" src="src/libs/ng-modal.js"></script>
<script type="text/javascript" src="src/libs/angular-route.min.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.core.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.utils.js"></script>
<script type="text/javascript" src="src/js/jssor-slider-plugin/jssor.slider.js"></script>
<script type="text/javascript" src="src/js/app.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
</head>
A:
Config section is incorrect. Instead of
.config(['$routeProvider', '$locationProvider'], function($routeProvider, $locationProvider) { ... });
it should be
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { ... }]);
Note, that function definition belongs to array object.
Another mistake is in redirectTo property of the drawer route, currently it doesn't make sense. You want probably this instead:
.when('/drawer', {
templateUrl: 'src/includes/drawer.html',
controller: 'drawerCtrl'
})
A:
Ensue that you have added the angular-route.js file to the html file.
And you are missing the ngRoute module here -
var app = angular.module('MyApp',['ngRoute','ngResource' ]);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){... }]);
dfsq is correct. There are syntax errors in the code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is used to login in LDAP mail server?
If I added data on LDAP in this way:
$ldapserver = "mail";
$ds = ldap_connect($ldapserver);
$r = ldap_bind($ds, $ldaprootun, $ldaprootpw);
add = ldap_add($ds, "cn=$full_name,ou=$domain,o=mygroup.com", $infonew);
Then does that mean that when I log in to my account I will use:
`cn="mynameHere",ou="domainIused",o=mygroup.com`
as my username? Or just my uid?
My account cannot login but I'm sure that it exists in LDAP.
Answers are very much appreciated. =)
A:
Usually, the user provides a simple name. Then the app searches the LDAP source for some attribute that has that value. Then you bind or password compare in your code, as that full DN.
You can use uid which is Unique ID, which is required to be unique. I.e. If you find more than one instance of it, that is an error.
You can try CN, but that can often be multi valued depending on your LDAP implementations schema.
If you know you are going against eDirectory, then uid is fine, or CN just do something if it is multi valued.
If you know you are going against Active Directory, you can assume sAMAccountName is unique since the system enforces uniqueness. userPrinicpalName ought to be unique, but nothing actually enforces it.
You can always use mail, which is the email address pretty uniformly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Valor minimo de um linha excluindo os valores zero (R)
TIMP3 TOTS3 UGPA3 USIM5 VALE3 VALE5 VIVT4 VLID3 WEGE3
1 0.7941716 0 0.00915221 0.2751215 0.3803796 0.5162442 1.505921 0 0.5559166
2 0.7710909 0 0.09351134 0.3925726 0.3687917 0.5158750 1.469548 0 0.5389812
3 0.7634292 0 0.10535813 0.4906756 0.3575568 0.5170484 1.433848 0 0.5225616
4 0.7479777 0 0.26867319 0.5142030 0.3754794 0.5018268 1.407619 0 0.5066423
5 0.7520354 0 0.29342233 0.6426008 0.4840935 0.6466121 1.400813 0 0.4912079
6 0.7559319 0 0.28448351 0.6571724 0.4694412 0.6365194 1.360621 0 0.4762438
Estou usando :
MIN = apply(EWMA_SD252[,2:102]*100,1,min)
Mas gostaria de pegar o minimo de cada linha porem desconsiderando os valores 0, alguma ideia ?
A:
Ao invés de usar o min no apply, você pode aplicar uma função anônima que selecione o mínimo somente dos números diferentes de zero (function(x) min(x[x!=0])). Por exemplo, no seu código ficaria assim:
MIN = apply(EWMA_SD252[,2:102]*100,1,function(x) min(x[x!=0]))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
From how far can a verbal spell component be heard?
So my character (a level 10 human enchanter wizard) was tasked with infiltrating the home of a mysterious elf to steal a maguffin. The elf employs around 10 guards on varying shifts, a house steward, and a captain of the guard. My plan is to use charm person/dominate person to get in and find the captain or steward, and use those spells to have them retrieve the item for me.
My concern is that while I'm casting a spell on one of the guards, some of the others will hear the voice and raise the alarm.
About Verbal Component: A verbal component is a spoken incantation. To provide a verbal component, you must be able to speak in a strong voice. A silence spell or a gag spoils the incantation (and thus the spell). A spellcaster who has been deafened has a 20% chance of spoiling any spell with a verbal component that he tries to cast. (Emphasis mine)
My question is: how loudly must one speak to fulfill the requirement? And secondly, how far away can someone hear the sound(given unobstructed terrain outside with clear weather). Or perhaps, what would be the formula to calculate the perception dc to hear?
As a secondary note, the grounds of the estate lie near the center of a town in the middle of a harvest festival. Given festivities, how far away could one hear the sound of a spell?
A:
The perception rules give sample DCs. It is reasonable to equate "hearing someone speak in a strong voice" to "hear the details of a conversation" at DC 0. The DC increases by 1 for every 10 feet away, and a further +2 for the festivities (unfavorable conditions).
So if you try to dominate a guard who is patrolling 100 feet away from the nearest other guard, that nearest guard will need to succeed on a DC 12 check (+10 for 100 feet, +2 for background noise) to hear that something is going on. He would probably need to make an Intelligence check to realize that the noise was a spell being cast. If he doesn't know it was a spell, you could be long gone, and your new puppet can make up some reason like "Oh, I just stubbed my toe and cursed." Of course, the other guard would also be entitled to a Sense Motive check to determine traces of enchantment...
Note: By pure RAW, you do not need to actually speak in a strong voice, merely be able to, but you may have difficulty convincing your DM that it works this way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to set GIF RLE compress when calling Canvas.toDataUrl()?
I'm working on a minimalist image creation project and I need to have the ability to create images within the browser that are uploaded and used on a server.
I've managed to create the image data for the server via calling the toDataUrl() method on my canvas object. Specifically, I create my image by calling toDataUrl('image/gif') but the resulting image is not RLE compressed. Is there a way that I can force the toDataUrl method to create a compressed GIF?
A:
The spec leaves it up to the browser on how to implement the GIF mime type. The only guaranteed MIME in the spec is image/png
So unfortunately, even if you're lucky enough that the browser will generate GIF, there doesn't seem to be any browsers currently that take RLE into consideration.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
String to NSDate conversion works in English, but not in Russian
I've written such extension for String :
extension String {
var asDate : NSDate! {
print(self)
let styler = NSDateFormatter()
styler.dateFormat = "dd MMM yyyy"
print(styler.dateFromString(self))
if let aStyler = styler.dateFromString(self) {
return aStyler
} else {
return NSDate()
}
}
}
I've noticed that it only works when English language is set on the device. However, it doesn't work with Russian, for example. Why?
It takes a string, e.g. "10 Apr 2016", and it should convert this string to date. However, styler.dateFromString(self) is always nil when the language is not English. I've checked that self (the string that I want to convert) matches the unicode format. However, I don't understand why styler.dateFromString(self) always returns nil.
A:
If not configured otherwise, NSDateFormatter uses the default locale to parse strings. If you switch your computer to Russian, it will expect Russian month names. 'Apr' is not Russian, hence it can't parse that string as a valid month.
If the string to parse is always English, you need to set the locale of the formatter to an English locale. Like so:
let df = NSDateFormatter()
df.locale = NSLocale(localeIdentifier: "en_US")
df.dateFormat = "dd MMM yyyy"
let date = df.dateFromString("21 Apr 2016")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IOS: add a parameter to @selector
When I have this line of code
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];
and this
- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture{
...
}
I want to add at "@selector(dragGestureChanged:)" a parameter that is "(UIScrollView*)scrollView", how can I do?
A:
You can't directly — UIGestureRecognizers know how to issue a call to a selector that takes one argument only. To be entirely general you'd probably want to be able to pass in a block. Apple haven't built that in but it's fairly easy to add, at least if you're willing to subclass the gesture recognisers you want to get around the issue of adding a new property and cleaning up after it properly without delving deep into the runtime.
So, e.g. (written as I go, unchecked)
typedef void (^ recogniserBlock)(UIGestureRecognizer *recogniser);
@interface UILongPressGestureRecognizerWithBlock : UILongPressGestureRecognizer
@property (nonatomic, copy) recogniserBlock block;
- (id)initWithBlock:(recogniserBlock)block;
@end
@implementation UILongPressGestureRecognizerWithBlock
@synthesize block;
- (id)initWithBlock:(recogniserBlock)aBlock
{
self = [super initWithTarget:self action:@selector(dispatchBlock:)];
if(self)
{
self.block = aBlock;
}
return self;
}
- (void)dispatchBlock:(UIGestureRecognizer *)recogniser
{
block(recogniser);
}
- (void)dealloc
{
self.block = nil;
[super dealloc];
}
@end
And then you can just do:
UILongPressGestureRecognizer = [[UILongPressGestureRecognizerWithBlock alloc]
initWithBlock:^(UIGestureRecognizer *recogniser)
{
[someObject relevantSelectorWithRecogniser:recogniser
scrollView:relevantScrollView];
}];
A:
So the method will look like this:
- (void)dragGestureChanged:(UILongPressGestureRecognizer*)gesture
scrollView:(UIScrollView *)scrollview
{
...
}
The selector will look like this:
UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(dragGestureChanged:scrollView:)];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to put an image on web browser control
In the web browser app for windows phone 7,i have created a web browser control(in xaml.cs) on the Grid. After that i have created an image on the Grid. But when i open the web browser in emulator, that image is not visible. It's a tabbed browser. But the image is visible in the grid but not visible on web browser control(After debugging the app). Like the UC Browser has this thing. PLease the below images, on the grid, the image is visible but on the web browser control, the image is not visible.
In .xaml
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox x:Name="UrlTextBox" Background="White" InputScope="URL" KeyDown="UrlTextBox_KeyDown" Margin="0,0,98,0" GotFocus="UrlTextBox_GotFocus" LostFocus="UrlTextBox_LostFocus" KeyUp="UrlTextBox_KeyUp"/>
<Grid x:Name="BrowserHost"
Grid.Row="1" GotFocus="BrowserHost_GotFocus">
<Image x:Name="Full" Source="Images/full.png" Height="60" Width="60" Margin="430,678,0,0" MouseEnter="Full_MouseEnter" Visibility="Visible" />
</Grid>
In Xaml.cs
private void ShowTab(int index)
{
this.currentIndex = index;
UrlTextBox.Text = this.urls[this.currentIndex] ?? "Search";
if (this.browsers[this.currentIndex] == null)
{
WebBrowser browser = new WebBrowser();
this.browsers[this.currentIndex] = browser;
BrowserHost.Children.Add(browser);
browser.IsScriptEnabled = true;
}
for (int i = 0; i < NumTabs; i++)
{
if (this.browsers[i] != null)
{
this.browsers[i].Visibility = i == this.currentIndex ? Visibility.Visible : Visibility.Collapsed;
}
}
}
I need that image in my web browser control. Can anybody help me?
Thanks in advance for your hard work!
A:
WHen you are adding the browser control in code, you are putting it on top of the image. You need a container within the Grid to hold your controls. Ultimately, though, you should probably try to set this up in XAML the way Matt Lacey shows above.
If you want do try this your way, you need something like this:
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox x:Name="UrlTextBox" Background="White" InputScope="URL" KeyDown="UrlTextBox_KeyDown" Margin="0,0,98,0" GotFocus="UrlTextBox_GotFocus" LostFocus="UrlTextBox_LostFocus" KeyUp="UrlTextBox_KeyUp"/>
<Grid x:Name="BrowserHost"
Grid.Row="1" GotFocus="BrowserHost_GotFocus">
<Grid x:Name="BrowserHolder"/>
<Image x:Name="Full" Source="Images/Full.png" Height="60" Width="60" Margin="430,678,0,0" MouseEnter="Full_MouseEnter" Visibility="Visible" />
</Grid>
</Grid>
Notice the addition of the Grid "BrowserHolder". Since that one was added first, anything that you add to that control should appear behind the image.
So your code then becomes:
private void ShowTab(int index)
{
this.currentIndex = index;
UrlTextBox.Text = this.urls[this.currentIndex] ?? "Search";
if (this.browsers[this.currentIndex] == null)
{
WebBrowser browser = new WebBrowser();
this.browsers[this.currentIndex] = browser;
// NOTE: Changed to BrowserHolder
BrowserHolder.Children.Add(browser);
browser.IsScriptEnabled = true;
}
for (int i = 0; i < NumTabs; i++)
{
if (this.browsers[i] != null)
{
this.browsers[i].Visibility = i == this.currentIndex ? Visibility.Visible : Visibility.Collapsed;
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java 8 streams maintain specific map key order return from group by operation
I have a list with collections of TitleIsbnBean objects. I wrote the following code snippet to group by this collection by learning area type as below.
titleListByLearningArea = nonPackageIsbnList.stream()
.collect(groupingBy(TitleIsbnBean::getKeylearningarea,
LinkedHashMap::new,Collectors.toList())
);
but I want to preserve the following specific order in the map return from the above stream.
titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {});
but I'm getting a different order once I group by the collections using streams. How can I maintain a specific order when stream group by operation using.
class TitleIsbnBean {
private String titleName;
private String isbn;
private int status;
private String keylearningarea;
public TitleIsbnBean(String titleName, String isbn, int status, String keylearningarea){
super();
this.titleName = titleName;
this.isbn = isbn;
this.status = status;
this.setKeylearningarea(keylearningarea);
}
}
ArrayList<TitleIsbnBean> nonPackageIsbnList = new ArrayList<>();
Map<String,List<TitleIsbnBean>> titleListByLearningArea = new LinkedHashMap<>();
titleListByLearningArea.put("Commerce", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("English", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Health & PE", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Humanities", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Mathematics", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Music & the Arts", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Science", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea.put("Others", new ArrayList<TitleIsbnBean>() {});
titleListByLearningArea = nonPackageIsbnList.stream()
.collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea,
LinkedHashMap::new,Collectors.toList()));
A:
Considering you need a desired order of keys for the Map you are collecting in, you can collect to a TreeMap with a Comparator based on index specified such as:
Collection<TitleIsbnBean> nonPackageIsbnList = .... //initialisation
List<String> orderedKeys = List.of("Commerce", "English", "Health & PE", "Humanities",
"Mathematics", "Music & the Arts", "Science", "Others");
Map<String, List<TitleIsbnBean>> titleListByLearningArea = nonPackageIsbnList.stream()
.collect(Collectors.groupingBy(TitleIsbnBean::getKeylearningarea,
() -> new TreeMap<>(Comparator.comparingInt(orderedKeys::indexOf)),
Collectors.toList()));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ObjectionJS relationship modelClass is not defined
I'm trying to update a relationship between a user and user_profile. I can update the user, but I keep getting this error when I try to update the user_profile:
ERROR: Error: UserProfile.relationMappings.user: modelClass is not defined
As far as I can tell I've mimicked the example from the docs, and TypeScript example, but can anyone see why this isn't working?
I included the query, both models, and the user profile migration. The contents of the BaseModel are commented out so it is equivalent to inheriting from Model directly, and the jsonSchema is only for validation so I removed them for brevity.
UPDATE
Removing the relationshipMappings from UserProfile stops the error from occurring, but since I need the BelongsToOneRelation relationship I'm still trying. At least it seems to be narrowed down to the relationMappings on the UserProfile.
Query
const user = await User.query() // <--- Inserts the user
.insert({ username, password });
const profile = await UserProfile.query() <--- Throws error
.insert({ user_id: 1, first_name, last_name });
Models
import { Model, RelationMappings } from 'objection';
import { BaseModel } from './base.model';
import { UserProfile } from './user-profile.model';
export class User extends BaseModel {
readonly id: number;
username: string;
password: string;
role: string;
static tableName = 'users';
static jsonSchema = { ... };
static relationMappings: RelationMappings = {
profile: {
relation: Model.HasOneRelation,
modelClass: UserProfile,
join: {
from: 'users.id',
to: 'user_profiles.user_id'
}
}
};
}
import { Model, RelationMappings } from 'objection';
import { BaseModel } from './base.model';
import { User } from './user.model';
export class UserProfile extends BaseModel {
readonly id: number;
user_id: number;
first_name: string;
last_name: string;
static tableName = 'user_profiles';
static jsonSchema = { ... };
static relationMappings: RelationMappings = {
user: {
relation: Model.BelongsToOneRelation,
modelClass: User,
join: {
from: 'user_profiles.user_id',
to: 'users.id'
}
}
};
}
Migration
exports.up = function (knex, Promise) {
return knex.schema
.createTable('user_profiles', (table) => {
table.increments('id').primary();
table.integer('user_id')
.unsigned()
.notNullable();
table.foreign('user_id')
.references('users.id');
table.string('first_name');
table.string('last_name');
table.timestamps(true, true);
});
};
A:
I would say that
a) it is problem of circular dependency or/and
b) there is problem with import paths
One is to use absolute file paths in modelClass instead of constructors. For example
modelClass: __dirname + '/User'
or
modelClass: require('./User').default
look at example at:
https://github.com/Vincit/objection.js/blob/master/examples/express-es7/src/models/Animal.js
|
{
"pile_set_name": "StackExchange"
}
|
Q:
rails database where query with params
I want to make a db query in my Controller with a where statement as params.
How do I do that?
example:
def show
@user = User.where(:user_id => params[:user_id])
end
It's a GET request and the parameters are :user_id.
Thanks
A:
I don't fully understand the meaning of "where statement as params" but if you're in UsersController and want to find the user given params[:user_id] then this should get you there.
def show
@user = User.where(:id => params[:user_id])
end
If you don't need to use where you can just do
def show
@user = User.find(params[:user_id])
end
If neither of those work could you try to elaborate a little on what you are trying to accomplish and what you've tried so far?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RDBMS Relational Algebra Example
I am working on implementing a Relational Database Management System for a school project. The system generates pseudo-SQL commands based on what the user enters into an interactive system. These commands are passed through a parser, which translates the line into actual function calls that the engine can execute.
I feel like I understand fairly well the operations that the database needs to perform in an SQL sense, but I'm unsure of how to translate those tasks to a procedural language that can actually carry out those operations.
I'm trying to find one or more examples of a relational algebra system implemented in an object oriented language like C++ or Java, so I can get an idea of what might work for my design. If anyone has an example they can share with me, that would be greatly appreciated. It doesn't need to be super complicated (in fact I would prefer the opposite), I am just trying to get an idea of how I might translate operations like selection or projection into an actual programming language.
A:
Take a look at SIRA_PRISE - a "Straightforward Implementation of a Relational Algebra - Prototype of a Relational Information Storage Engine".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can JsonPatchDocument use Attributes
Can I use Attributes on my objects and still use JsonPatchDocument?
Currently, if I have this object:
public class Test {
public float FloatTest { get; set; }
}
I can only send in float, both in a post-request and in a patch-request.
If I add an attribute:
public class Test {
[Range(1, 100)]
public float FloatTest { get; set; }
}
I can now, in a post-request, only send in floats between 1 and 100. In patch though, ModelState stays valid even if I patch with FloatTest = 1000.
Is there anyway to check this in the ApplyTo-function in JasonPatchDocument, or is there any other best practice I've missed?
A:
Use TryValidateModel to validate your data , refer to the below code :
[HttpPatch]
public IActionResult JsonPatchWithModelState([FromBody] JsonPatchDocument<Test> patchDoc)
{
if (patchDoc != null)
{
var test = new Test();
// Apply book to ModelState
patchDoc.ApplyTo(test, ModelState);
// Use this method to validate your data
TryValidateModel(test);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return new ObjectResult(test);
}
else
{
return BadRequest(ModelState);
}
}
Result :
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does the ping command differentiate between its ICMP responses and anothers?
If I have two shells open each pinging the same host, how do the two shells differentiate between the ICMP responses coming back for each shell?
A:
The request includes a 2-byte Identifier field, which must match in the reply. This is separate from the Sequence field. You can see it described in RFC 792
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Есть ли у русского языка "стандартный диалект" (с письменностью и преподаваемый в школах)?
Есть ли у русского что-то похожее на то, что есть у британского английского (имеется в виду американский английский)? Есть ощущение, что то, что среднестатистический россиянин понимает под словом "диалект", — это несравнимо меньшее, чем то, что произошло с английским, когда его "увезли" на известный континент. Но я — филолог английского, не русист, могу ошибаться. Судя по Википедии, у русского попросту нет такого диалекта. Права я?
A:
Принято говорить, что общенародный язык существует в 4 основных формах, одна из которых нормативна, остальные ненормативны - просторечия, жаргоны, территориальные диалекты. "Стандартный диалект" в русском языке - это, скорее всего, русский литературный язык - образцовая, нормированная и кодифицированная форма национального языка, обладающая богатым лексическим фондом, развитой системой стилей. Он выполняет функции бытового языка грамотных людей, языка науки, публицистики, государственного управления, языка культуры, литературы, образования, средств массовой информации и т.д. Однако в определенных ситуациях функции литературного языка могут быть ограничены (например, он может функционировать в основном в письменной речи, а в устной используются территориальные диалекты). Литературный язык используется в различных сферах общественной и индивидуальной деятельности человека.
Литературный язык имеет свою историю.
В XVI веке в Московской Руси решили нормализовать письменность русского языка (тогда он назывался «проста мова» и подвергался влиянию белорусского и украинского) – ввести преобладание сочинительной связи в предложениях и частое употребление союзов «да», «и», «а». Двойственное число было утрачено, а склонение существительных стало очень похоже на современное. А основой литературного языка стали характерные черты московской речи. Например, «аканье», согласный «г», окончания «ово» и «ево», указательные местоимения (себя, тебя и др.). Начало книгопечатания окончательно утвердило литературный русский язык.
В Петровскую эпоху русский язык освободили от «опеки» церкви, а в 1708 году реформировали азбуку, чтобы она стала ближе к европейскому образцу.
Во второй половине XVIII века Ломоносов заложил новые нормы русского языка, объединив все, что было до этого: разговорную речь, народную поэзию и даже приказной язык. После него язык преобразовывали Державин, Радищев, Фонвизин. Именно они увеличили количество синонимов в русском языке, чтобы как следует раскрыть его богатство.
Огромный вклад в развитие нашей речи внес Пушкин, который отвергал все ограничения по стилю и комбинировал русские слова с некоторыми европейскими, чтобы создать полноценную и красочную картину русского языка. Его поддержали Лермонтов и Гоголь.
Выходит, наш современный русский язык, со всеми его лексическими и грамматическими правилами произошел от смешения различных восточнославянских диалектов, которые были распространены на территории всей Руси, и церковнославянского языка. И теперь слово диалект понимается в узком смысле - местный говор в отличие от литературного языка
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to arbitrate between two different update sources without a lock?
I am receiving updates from two different sources (network listen) upon which I get a callback to a method somewhat like this:
void onUpdate(Update* update)
{
static MutexT lock;
static hash_set<UpdateID> set;
ScopedGuard _(lock); //lock here
hash_set<UpdateID>::iterator it = set.find(update->id);
if (it == set.end())
set.insert(update->id);
else
return;
listener->onUpdate(/*some stuff*/);
}
since both sources are feeding you the same updates, you want to avoid notifying on duplicates, you want to arbitrate between both sources to be up to date with the latest from whoever gives it to you first and also for missed updates if one sources is possibly unreliable. The thing is, it's expensive to lock on every update, is there a way around this lock if I definitely do not want duplicate onUpdate calls?
(Or at least a way to reduce cost?)
A:
First of all, the lock shouldn't be static, it should be a member variable.
You could make it more efficient by using a reader/writer mutex, e.g.
boost::shared_mutex mutex_;
std::unordered_set<UpdateID> set_;
void onUpdate(const Update& update)
{
boost::upgrade_lock<boost::shared_mutex> lock(mutex_);
auto it = set_.find(update.id);
if(it == set_.end())
{
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(mutex_);
set.insert(update.id);
}
listener->onUpdate(/*some stuff*/);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
perl config file
I am trying to create a settings file/configuration file. This would contain a list of key value pairs. There are 10 scripts that would be using this configuration file,either taking the input from it or sending output to it(key-values) or both.
I can do this by simply reading from and writing to the file..but I was thinking about a global hash in my settings file which could be accessed by all 10 scripts and which could retain the changes made by each script.
Right now,if I use :
require "setting.pl"
I am able to change the hash in my current script,but in the next script the changes are not visible..
Is there a way to do this?Any help is much appreciated.
A:
How about a config file tied to a hash?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NFS showing Security Contexts "?" / "blank" on Client?
I'm using NFSv4 and used following /etc/exports on Server (lets say, xx.xx.xx.x0):
/var/www/html/project xx.xx.xx.x101(rw)
/var/www/html/project xx.xx.xx.x102(rw)
And each Client is showing something like below, when i check mount:
xx.xx.xx.x0:/var/www/html/project on /var/www/html/project type nfs (rw,vers=4,addr=xx.xx.xx.x0,clientaddr=xx.xx.xx.x101)
But when i check into the mounted directory ls -laZ (with Z option), it is showing like:
drwxrwxrwx. 11 user1 user1 ? 4.0K Mar 9 02:36 .
drwxr-xr-x. 26 user1 user1 ? 4.0K Mar 8 18:17 ..
drwxrwxrwx. 9 user1 user1 ? 4.0K Sep 3 2012 wp-admin
drwxrwxrwx. 8 user1 user1 ? 4.0K Dec 12 09:47 wp-content
drwxrwxrwx. 8 user1 user1 ? 4.0K Oct 16 12:04 wp-includes
-rwxrwxr--. 1 user1 user1 ? 647 Mar 8 18:54 .htaccess
-rwxrwxr--. 1 user1 user1 ? 395 Dec 12 09:49 index.php
-rwxrwxrwx. 1 user1 user1 ? 20K Dec 12 09:49 license.txt
-rwxrwxrwx. 1 user1 user1 ? 9.0K Dec 12 09:49 readme.html
The problems are the ? Question Marks, which i believe is showing wrong File Security Context Values.
Any good idea on it please?
Note: SELinux is disabled, on every machines.
A:
i got it by myself that i realized SELinux on Clients, was blocking the Security Context Permissions whilst NFS Server is totally disabling the SELinux. So i disable the SELinux on this Client machines and rebooted, then the exactly the same File/Directory Security Contexts are showing on all ends.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to limit all the queries with tenant_id in PostgreSQL?
One possible way to isolate tenants is to add tenant_id to every table, and scope every request with that field.
But you have to be very carefull and put that in every SQL query.
I wonder if there's a way to tell PostgreSQL to do that automatically? Something like
scope tenant_id = 'foo'
select * from my_table -- tenant_id = 'foo' should be added automatically
A:
You can use views in conjunction with custom configuration parameters, example:
create table customers_table(id serial primary key, tenant_id int, name text);
insert into customers_table (tenant_id, name) values
(1, 'a'),
(2, 'b'),
(1, 'c'),
(2, 'd');
create view customers as
select *
from customers_table
where tenant_id = current_setting('glb.tenant_id')::int;
Use the view instead of the table in your select queries. You have to set the custom configuration parameter to have queries run:
select * from customers;
ERROR: unrecognized configuration parameter "glb.tenant_id"
set glb.tenant_id to 1;
select * from customers;
id | tenant_id | name
----+-----------+------
1 | 1 | a
3 | 1 | c
(2 rows)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Alternate meaning for えぐい
One of the dictionary definitions for えぐい is "amazing".
I've never actually come across this sense of the word in any sentences. Does anyone have examples of where native writers have used えぐい to mean something like "amazing"?
A:
That is why I don't like Jisho. It does not explain things; It just throws definitions at you.
"Amazing", or rather 「すごい」, is a new and slangy meaning of 「えぐい」. It is used quite heavily among the younger generations nowadays. It is used far more often than you seem to think, too. Even I, who is not so young, used the word for that meaning to describe the excellent quality of the pizza served at my favorite pizzeria in Nagoya the other day.
We use the word 「やばい」 for the same kind of new meaning these days as well. For both 「えぐい」 and 「やばい」, the new meaning is positive, which is the opposite of what Japanese-learners might think.
This video is all about homeruns, but you might want to check its title at least.
https://www.youtube.com/watch?v=RgOe6mfrs9Y
A:
使い方としては日本語の「ヤバい」、英語の "crazy", "insane" などと似ており、状況によって良い意味にも悪い意味にもなります。ただし、個人的には、肯定的な意味で使われる頻度は「ヤバい」よりかなり低い気がします。私は「エグい」をほめ言葉として自分で使うことはまずありません。個人差や地域差は大きいと思います。
また、「ヤバい」や "amazing" は比較的素直な賞賛の言葉として使えますが、「エグい」は個性的・衝撃的・異質な物に対して使われることが多い気がするので、誤解を受けないよう注意をする必要があると思います。嬉しそうな顔で「あの映画マジでヤバかった」と言われたら単純に褒めているのだろうと感じますが、「あの映画マジでエグかった」と言われたら、個人的には「どういう意味で?」と聞き返したくなります。
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you index an array inside a JSON with an Oracle 12c query?
I have a table "move" with one column "move_doc" which is a CLOB. The json stored inside has the structure:
{
moveid : "123",
movedate : "xyz",
submoves: [
{
submoveid: "1",
...
},
{
submoveid : "2",
...
}
]
}
I know I can run an Oracle 12c query to access the submoves list with:
select move.move_doc.submoves from move move
How do I access particular submoves of the array? And the attributes inside a particular submove?
A:
You have to use Oracle functions json_query and/or json_value like this:
SELECT json_value(move_doc, '$.submoves[0].submoveid' RETURNING NUMBER) FROM move;
returns 1.
SELECT json_query(move_doc, '$.submoves[1]') FROM move;
would return the second JSON element, i.e. something like
{
submoveid : "2",
...
}
json_value is used to retrieve a scalar value, json_query is used to retrieve JSON values. You might also want to have a look at json_table which returns an SQL result table and thus can be used in Joins.
See this Oracle Doc for more examples
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are STI's still incompatible with Rails 3.1 rc?
I did a fresh install of Rails 3.1 rc, following the [Railcast][1] of Ryan Bates. It seems, every STI implementation throws the same error (described below). For every other model, no problems occur.
Is this a known issue? A bug perhaps? Or is there something missing on my end? Anyone experiencing the same error?
Media model is the STI. Event model inherits from the Media model. Model definitions:
class Media < ActiveRecord::Base
belongs_to :user
....
end
class Event < Media
...
end
In console, I do:
ruby-1.9.2-p136 :009 > Event.count
Creating scope :page. Overwriting existing method Event.page.
ActiveRecord::StatementInvalid: PGError: ERROR: relation "media" does not exist
LINE 4: WHERE a.attrelid = '"media"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"media"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:958:in `async_exec'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:958:in `exec_no_cache'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:547:in `block in exec_query'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract_adapter.rb:222:in `block in log'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract_adapter.rb:217:in `log'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:546:in `exec_query'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:1057:in `column_definitions'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/postgresql_adapter.rb:736:in `columns'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:93:in `block (2 levels) in initialize'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:174:in `with_connection'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:90:in `block in initialize'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:104:in `yield'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:104:in `default'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/connection_adapters/abstract/connection_pool.rb:104:in `block in initialize'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activerecord-3.1.0.rc1/lib/active_record/base.rb:709:in `yield'
... 8 levels...
from /Users/Chris/Sites/site_name.1/app/models/event.rb:1:in `<top (required)>'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:452:in `load'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:452:in `block in load_file'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:639:in `new_constants_in'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:451:in `load_file'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:338:in `require_or_load'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:489:in `load_missing_constant'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:181:in `block in const_missing'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:179:in `each'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/activesupport-3.1.0.rc1/lib/active_support/dependencies.rb:179:in `const_missing'
from (irb):9
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/railties-3.1.0.rc1/lib/rails/commands/console.rb:44:in `start'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/railties-3.1.0.rc1/lib/rails/commands/console.rb:8:in `start'
from /Users/Chris/.rvm/gems/ruby-1.9.2-p136@railspre/gems/railties-3.1.0.rc1/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require' from script/rails:6:in
[1]: http://railscasts.com/episodes/265-rails-3-1-overview
A:
Ok, found the problem. Quite interesting actually. In 3.0+, 'media'.pluralize returns 'medias'. In 3.1, 'media'.pluralize returns 'media'.
This means, for 3.1, the singular form for media, would be medium.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should white hats know methods that can be used by black hats to attack them?
In my opinion to be sure that protection mechanisms work, you should know what attacks can be performed against them. Only if you know techniques that can be used to attack you, you can be sure whether you are protected. If you go to Sec.SE asking about attack protection without knowing full attack profile, you can't judge whether those protection mechanisms work. So before knowing protection measures, you should know attack itself.
Based on this, I think that questions asking about how to perform an attack seem to be good for me as this knowledge is needed to be able to judge protection measures.
For example to be sure that my protection measures catching scan anonymizers work, I should know techniques that can be used to anonymize scans.
To figure out how to build smartphone that will be able to notify user in case of attack, I should know how those attacks work.
Arguments like this can be devised in most of situations.
I vote to allow content like this to be posted on site.
A:
(Lightly adapted from my answer to How do we provide value to white and grey hats?)
I'm speaking here as a fully white-hat person (I'm a developer whose products are sometimes part of a security infrastructure, and an occasional system administrator). Talking about attacks tells me what I'm supposed to defend again. When designing a defense, a lot of the difficulty is imagining how it could be breached.
Why would a thread about an attack require a remediation? Conversely, should a thread about a defense include a way to bypass it?
Rejecting questions because they're “too black hat” lessens the value of the site to me. I need to know what I'm defending against. If black hats want to post to the site, what I have to say to them is teach me.
(And it's tit for tat, of course. I'm perfectly happy with having defense techniques published on the site, even if they end up informing black hats what they're up against.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Published project can't find my files
I just published my project and he can't find my Manual file. I'm using this for getting the file:
private void btnHelp_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(Environment.CurrentDirectory + @"\Handleiding Lijmlijnen tekenen.pdf");
}
pretty straight forward, and it works when I'm debugging. But when I published it, it shows an error that he can't find that specific file. It points to this location: C:\Users\Bart\Documents\Visual Studio 2015\Projects\TestDXFlibrary\TestDXFlibrary\bin\Debug\Handleiding Lijmlijnen tekenen.pdf
A:
The "current directory" in release can change (and most probably will change). Display a simple dialog with your path to check if it is correct. Check if the file is in there by copying and pasting the path to File Explorer.
If you are trying to deliver a pdf file along with the project, change the properties of the pdf file in your project file:
set Copy To Output Directory to Copy always/Copy if newer
set Build Action to Content
BTW. Better would be to use Path.Combine method, like that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I wire 7 outdoor posts correctly?
I've seen a few posts on how to wire a single post/column for lighting outdoor but I can't find anything that relates to multiple posts/columns.
I have 7 posts/columns outdoor and I'd like to add lighting at the top of each post. These posts/columns will be used with a fence (in case you are trying to visualize this).
So far this is what I understand I need to do in a nutshell:
Dig a trench of 18" and bury wiring with PVC piping
Use existing outdoor GFCI and extend your wiring from that outlet as long as you are not overloading the circuit
Use a wiring hub that runs power from the outlet being used to the main hub input and then have separate outs from the same hub running to each lamp that will go to each post/column
Here is where I need some guidance:
What is a good hub to use outdoor? When searching online, I only find extension cords hubs. This isn't what I need. Does it have a different/formal name?
My run from the outlet at the house to the hub by the posts/columns would be about 60 feet. If I position the hub midpoint of all posts/columns, I have about 40 feet each way (left or right) to the furthest point to supply cable to each lamp on each post/column. Do I need some sort of amplifier so that I don't experience voltage drop? If so, which one and how do I introduce this?
I've read that looping or daisy chaining just makes it more complex trying to maintain adequate voltage (evenly) on all post so a hub is recommended. Is this correct?
I have a basic understanding of electrical and wiring. I've done some smaller projects at home so tackling this isn't a concern. I'd just like to know what are the right components I need to ensure this is done correctly
A:
A few specific points:
Use existing outdoor GFCI
Because this is outdoors, it needs to be GFCI protected if there are any receptacles in the circuit outdoors. As noted by Harper, a circuit used only for lighting does not necessarily need GFCI protection. But the original question mentions a receptacle, so we'll consider GFCI to be a requirement. If you can actually put the GFCI protection inside the building (e.g., either at an upstream receptacle or using a GFCI breaker instead of a plain breaker), that will eliminate exposure of the relatively sensitive GFCI electronics to wind/rain/etc. and generally make it last longer.
Use a wiring hub
That sounds to me like computer networking lingo. In the case of simple lighting, all you are connecting is power (hot/neutral/ground). A "hub" is simply a junction box that has all the wires connected to it - in this case "all in one" would be 1 in, 7 out = 8 x 2 = 16 wires (plus grounds) which is not a big deal. If your "hub" is simply a box at one post then it is 1 in, 3 out (1 to left, 1 to right, 1 to light in the same post) and the other posts just have 3 sets of wires - 1 in, 1 out, 1 to light in the same post (except for the post on each end). Nothing "special" - just ordinary wiring.
Do I need some sort of amplifier so that I don't experience voltage drop?
Voltage drop depends on both distance and current. Using an online calculator I get 0.42% drop (== "nothing") on 100 ft. of 14 AWG with 1 Amp load. With a 10 Amp load, it is a more significant 4.21%, and switching to 12 AWG with 10 Amp load gives 2.65% (which is not "nothing" but still quite low).
FYI, while 14 AWG is plenty for this type of circuit, if the breaker is a 20 Amp breaker then you must stick with 12 AWG (or larger) wire or replace the breaker with 15 Amp. If this circuit is shared with receptacles as described then if it is 20 Amp go with 12 AWG and keep the breaker 20 Amp so that you don't limit your receptacle loads as much with the extra load of the lighting.
Bottom line: with the distances you are talking about and modern LED lighting, this is just not much of an issue. If each of the 7 posts has a 60 W LED fixture (that is a LOT of light), that is 1/2 Amp per fixture = 3.5 Amps total. So unless you are going to waste energy on halogen floodlights, voltage drop is really not a problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Investing in a fund
I am looking to invest some personal money of around £5000.
I understand to give your money to a hedge fund you need to have a high net worth.
Lets say I want to invest in the Goldman Sachs India Equity Portfolio which has generated great returns in the past.
Is there anyway for me to invest £5000 into this fund?
A:
According to my research one only needs £5000 to invest in this fund. However, it also has a sales charge of 4% with an annual charge of 1.75%. If this is short term money, you would have to have a fairly high return to break even.
A:
You do not need to have 'high net value', and yes, you can invest in it.
Typically, fund companies require a minimum investment, that could be 100, it could be a 1000. 5000 should be enough for 99.9 % of all funds for an initial investment.
What you need is an investment company that manages the account for you. I cannot name those for your country, but they should be easy to find (companies like IMG, and Fidelity might serve your country). You then open an account with the company of your choice, transfer the money, and tell them which fund it shall go in; all this is possible online.
You can also go to see an agent in person, and he will fill the forms for you, and handle all the action, but he might take a fee for it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Control Behavior of Constraints During SQL Bulk Insert?
I am curious if there is a way to control how the database responds to foreign and primary key constraints while using the bulk insert command. Specifically, I am inserting data into an employees table (with primary key empID), that is linked to data in other tables (children, spouse, and so on) by that key (empID). Given the logic and purpose behind this application, if, during bulk insert, a duplicate primary key is found, I would like to do the following:
Delete (or update) the 'employee' row that already exists in the database.
Delete all data from other tables associated with that employee (that is children, beneficiaries, and so on).
Insert the new employee data.
If I was inserting data the usual way, that is without bulk insert, I think the task would be quite simple. However, as am using it, I must admit, I am not quite certain how to approach this.
I am certainly not expecting anybody to write my code for me, but I am not quite sure if it is even possible, how to begin, or what the best approach might be. A stored procedure perhaps, or changes to schema?
Thanks so much for any guidance.
A:
The usual solution to this kind of problem is to load the data into a Staging table, perhaps in it's own Schema or even Database. You would then load the actual table from this staging table, allowing you to perform whatever logic is required in an un-restricted manner. This has the added benefit of letting you log/audit/check the logic you are using while loading the 'real' table.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are pmd, repositories etc tasks in Gradle
I am creating basic custom tasks in Gradle and learning how to extend them to do more complicated actions (Learning from here: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html).
One of my reference projects, which I am extending to learn Gradle looks something like this
// pmd config
pmd {
ignoreFailures = false
reportsDir = file("$globalOutputDir/pmd")
toolVersion = toolVersions.pmdVersion
}
repositories {
mavenCentral()
}
task listSubProjects{
doLast{
println 'Searching in root dir `'
}
}
My question is around the pmd and repositories sections and why they don't have a clear qualifier like "task" on them but my listSubProjects requires a task qualifier? Are these inherited tasks from plugins and don't need a task qualifier?
A:
The blocks that you see are task extensions, also discussed here.
A plugin creator can define extensions to allow users to configure a plugin:
// plugin code
class GreetingPluginExtension {
// default value
String message = 'Hello from GreetingPlugin'
}
// plugin code
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
// Add the 'greeting' extension object
def extension = project.extensions.create('greeting', GreetingPluginExtension)
// Add a task that uses configuration from the extension object
...
}
}
In project.extensions.create('greeting',... the greeting block to be used later in build.gradle files is defined.
Then in user build.gradle files
apply plugin: GreetingPlugin
// Configure the extension
greeting.message = 'Hi from Gradle'
// Same effect as previous lines but with different syntax
greeting {
message = 'Hi from Gradle'
}
Often the name of the extension is chosen to be the same as the plugin and/or the task, which can make things confusing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
New to Git, why are there already so many configurations set in git config?
New to using git, and just downloaded it. Getting it set up and was surprised to find so many presets with git config --list? I thought nothing was supposed to be preset.
output of git config --list:
core.excludesfile=~/.gitignore
core.legacyheaders=false
core.quotepath=false
mergetool.keepbackup=true
push.default=simple
color.ui=auto
color.interactive=auto
repack.usedeltabaseoffset=true
alias.s=status
alias.a=!git add . && git status
alias.au=!git add -u . && git status
alias.aa=!git add . && git add -u . && git status
alias.c=commit
alias.cm=commit -m
alias.ca=commit --amend
alias.ac=!git add . && git commit
alias.acm=!git add . && git commit -m
alias.l=log --graph --all --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(white)- %an, %ar%Creset'
alias.ll=log --stat --abbrev-commit
alias.lg=log --color --graph --pretty=format:'%C(bold white)%h%Creset -%C(bold green)%d%Creset %s %C(bold green)(%cr)%Creset %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative
alias.llg=log --color --graph --pretty=format:'%C(bold white)%H %d%Creset%n%s%n%+b%C(bold blue)%an <%ae>%Creset %C(bold green)%cr (%ci)' --abbrev-commit
alias.d=diff
alias.master=checkout master
:
A:
If you download it from SourceForge instead of the official site (https://git-scm.com/downloads), it is probably just for convenience, as Biswapriyo says.
You can just erase all of that and start clean if you want. There is no problem with that. Just open your .gitconfig file with your favourite editor and erase everything or just the things that you don't understand. It is typically located at ~/.gitconfig.
But there are some useful tools there, anyways. For example, everything starting with alias is a shortcut to writing less code.
For example, if you type
git lg
that will give you the same result as
git log --color --graph --pretty=format:'%C(bold white)%h%Creset -%C(bold green)%d%Creset %s %C(bold green)(%cr)%Creset %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative
This will create a colored graph with a short commit message and some other info. It's very useful.
So it is very convenient, but you need to familiarise yourself first in my opinion. If you are totally new to git, I would recommend you to avoid aliases for a while and start using them as you feel the need to. Because if you try to use them now, it will be too much information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
loosing css properties in jquery-mobile
Im using jquery-mobile.
in the panel menu i have a link that when user clicks on it the page loads but it looses its css properties and gives me a dirty page!
<div data-role="panel">
<ul>
<li><a href="login_page.html">Login</a></li>
.
.
.
</ul>
</div>
In login_page.html i have:
<ul class="forms">
<li><input type="text"></li>
.
.
.
</ul>
and in css:
.forms{
list-style:none;
background-color:red;
}
.forms li
{
display:inline;
}
Note: When I refresh the page the css properties comes back.
A:
You are using jquery-mobile and the other pages might be written by other web languages.
If by refreshing page it gets fixed so you're probebly lucked in a frame,and you should use target="_top" to escape it:
<a href="example.com" target="_top"></a>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does the term "Longest chain" mean?
What does the term "Longest chain" mean, as there is only one 'right' blockchain exists? How another longer chain would make the 'right' chain invalid?
A:
Bitcoin's block chain system is really two quite separate systems, and they are easily confused. The first one is the block tree and the second is the active chain.
The block tree consists of all valid blocks whose entire ancestry is known, up to the genesis block. The rules for validness include no double spending, valid signatures, no introduction of more currency than allowed, ... These are the network rules, and every full Bitcoin node verifies them.
The active chain is one path from genesis block at the top to some leaf node at the bottom of the block tree. Every such path is a valid choice, but nodes are expected to pick the one with the most "work" in it they know about (where work is loosely defined as the sum of the difficulties). Relativity and technological constraints prevent us from doing instant communication across the globe, so two nodes can not be expected to pick the same chain as the active one. This is no problem: the mining mechanism makes sure that the chance two nodes disagree about blocks in the past decreases exponentially as they are older.
So no, there is not one "right chain", there are many. Nodes choose for themselves, but the system is designed to make sure consensus arises quickly.
The rules in practice are this: when a new block arrives, and it extends the previous active chain, we just append it to the active chain. If not, it depends on whether the branch it extends now has more work than the currently active branch. If not, we store the block and stop. If it does have more work, we do a so called "reorganisation": deactivating blocks from the old branch, and activating blocks from the new branch.
A:
Imagine that the blockchain is 210000 blocks long and TWO miners both find valid blocks within a few seconds of each other and broadcast them to the network.
This is perfectly normal as the Bitcoin network is peer to peer and global.
You now have two chains, each of length 210001. Neither of these are longer than each other. Some bitcoind nodes will see the first miner's block and some bitcoind nodes will see the second.
Temporarily you have two forks of the blockchain, each of length 210001 blocks long. They are identical for 210000 blocks, but the 210001st is different on the two forks.
Sometime later another miner finds another valid block, the 210002nd block, and that will be attached to exactly one of the forks.
This chain is now the longest at 210002 blocks and becomes the longest chain. It becomes the "definitive" blockchain.
(The transactions in the alternate fork don't disappear - they simply get put back into the pool of unconfirmed transactions and miners will put them into a subsequent block).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Questions about NSUinteger and int
I use JSONModel to capture data from json:
@interface BBTCampusBus : JSONModel
@property (strong, nonatomic) NSString * Name;
@property (assign, nonatomic) NSUInteger Latitude;
@property (assign, nonatomic) NSUInteger Longitude;
@property (nonatomic) BOOL Direction;
@property (assign, nonatomic) NSUInteger Time;
@property (nonatomic) BOOL Stop;
@property (strong, nonatomic) NSString * Station;
@property (assign, nonatomic) NSInteger StationIndex;
@property (assign, nonatomic) NSUInteger Percent;
@property (nonatomic) BOOL Fly;
@end
And I have the following code:
for (int i = 0;i < [self.campusBusArray count];i++)
{
NSLog(@"index at nsuinteger - %@", (NSUInteger)self.campusBusArray[i][@"StationIndex"]);
NSLog(@"index - %lu", index);
if ([(NSUInteger)self.campusBusArray[i][[@"StationIndex"] ]== index)
{
numberOfBusesCurrentlyAtThisStation++;
}
}
Actually StationIndex is a 1 or 2 digit integer. For example I have self.campusBusArray[i][@"StationIndex"] == 4, and I have index == 4, then the two NSLog all output 4, but it will not jump into the if block, or the numberOfBusesCurrentlyAtThisStation++ won't be executed. Can somebody tell my why?
A:
Lets look at the line:
NSLog(@"index at nsuinteger - %@", (NSUInteger)self.campusBusArray[i][@"StationIndex"]);
%@ says that an object will be included in the log, one that implements description. That's good, because the end of the expression dereferences a dictionary, which may only contain objects.
NSUInteger, like int is a scalar type. Like old-fashioned C, its just a group of bytes in memory whose value is the numerical value of those bytes. An object, even one that represents a number, like NSNumber cannot be cast using the c-style cast (moreover, the precedence of the cast is low, this expression really just casts self, also nonsensical).
So it appears that self.campusBusArray is an array of dictionaries (probably the result of parsing JSON describing an array of objects). And it appears you expect those dictionaries to have a key called [@"StationIndex"] with a numerical value. That must be an NSNumber by the rules of objective-c collections (they hold objects). Therefore:
NSDictionary *aCampusBusObject = self.campusBusArray[i]; // notice no cast
NSNumber *stationIndex = aCampusBusObject[@"StationIndex"]; // this is an object
NSUInteger stationIndexAsInteger = [stationIndex intValue]; // this is a simple, scalar integer
if (stationIndexAsInteger == 4) { // this makes sense
}
if (stationIndex == 4) { // this makes no sense
}
That last line tests to see of the pointer to an object (an address in memory) is equal to 4. Doing scalar math on, or casts on, or comparisons on object pointers almost never makes sense.
Rewriting...
for (int i = 0;i < [self.campusBusArray count];i++)
{
NSDictionary *aCampusBusObject = self.campusBusArray[i];
NSNumber *stationIndex = aCampusBusObject[@"StationIndex"];
NSUInteger stationIndexAsInteger = [stationIndex intValue];
NSLog(@"index at nsuinteger - %lu", stationIndexAsInteger);
NSLog(@"index - %lu", index);
if (stationIndexAsInteger == index)
{
numberOfBusesCurrentlyAtThisStation++;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error in starting MySQL in Mac OS X 10.6
i am trying to run MySQL 5.5.8 in my Mac OS X 10.6 (Snow Leopard).
I'm calling /usr/local/mysql/bin/mysqld_safe and I get this in the error log...
110124 16:35:36 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql-5.5.8-osx10.6-x86_64/data
110124 16:35:36 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql-5.5.8-osx10.6-x86_64/data/ is case insensitive
110124 16:35:36 [Note] Plugin 'FEDERATED' is disabled.
InnoDB: The InnoDB memory heap is disabled
InnoDB: Mutexes and rw_locks use GCC atomic builtins
InnoDB: Compressed tables use zlib 1.2.3
110124 16:35:36 InnoDB: Initializing buffer pool, size = 128.0M
110124 16:35:36 InnoDB: Completed initialization of buffer pool
110124 16:35:36 InnoDB: highest supported file format is Barracuda.
110124 16:35:36 InnoDB: 1.1.4 started; log sequence number 2809411
110124 16:35:36 [ERROR] Can't start server : Bind on unix socket: Permission denied
110124 16:35:36 [ERROR] Do you already have another mysqld server running on socket: /var/mysql/mysql.sock ?
110124 16:35:36 [ERROR] Aborting
110124 16:35:36 InnoDB: Starting shutdown...
110124 16:35:38 InnoDB: Shutdown completed; log sequence number 2809411
110124 16:35:38 [Note] /usr/local/mysql-5.5.8-osx10.6-x86_64/bin/mysqld: Shutdown complete
110124 16:35:38 mysqld_safe mysqld from pid file /usr/local/mysql-5.5.8-osx10.6-x86_64/data/MyMacPro.local.pid ended
Here is what I have in /etc/my.cnf... wondering if I need to add more settings.
[client]
socket = /var/mysql/mysql.sock
[mysqld]
socket = /var/mysql/mysql.sock
Thank you so much,
Robert
A:
110124 16:35:36 [ERROR] Can't start server : Bind on unix socket: Permission denied
We did the following just now with MySQL 5.5.28 that fixed the bind problem for us. It is necessary because the sock file is written here:
sudo chown -R _mysql /var/lib/mysql
We also did the following although I'm not sure that it was necessary:
sudo chown -R _mysql /usr/local/mysql
A:
$ sudo cp /usr/local/mysql/support-files/my-small.cnf /etc/my.cnf
$ sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
.... SUCCESS!
This done it for me!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to stop my puppy from eating his stool?
I have a 4 months old puppy who is healthy and playful. For the past one week he started eating his own stool.
There is a place reserved for his #1 and #2, and he does those activities there only. I tried to constantly monitor him but I miss always. He is too sneaky.
I googled and I saw some products for this but I don't know whether they will work or good for his health.
Is there any suggestion to stop him from eating stool?
Thanks in advance.
A:
Sounds like your dog is enjoying his home-made snack! Here's a few tips we recommend at the hospital:
Pick up stool as soon as it comes out, need to be a bit more watchful.
For-Bid - all the hospitals I've worked at carry this product, you'll need to use it for a week or 2 so the dog learns to avoid stools all together.
Canned pineapple - You only need a small amount in comparison to the size of the dog to change the taste of the stool so they don't eat it. Too much can cause GI upset.
Small dog (0-10kg) - 1/8th of a cup per meal
Medium dog (11-30kg) - 1/4 of a cup per meal
Large dog (>30kg) - 1/4 to 1/2 of a cup per meal
These tricks may stop working once you stop using them but don't worry! It is gross but not harmful for the dog to eat his poo and also NOT an indicator that he's ill or in poor health, he just genuinely enjoys eating it. I know some dogs who only eat their poo in the winter as it's frozen (poopsicles).
He may grow out of it as he ages, though not always the case. Some dogs will eat their stools because they are hungry as well, growing dogs need to eat more while some breeds are genetically predisposed to ALWAYS be hungry.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I make cron email my @gmail account
I have a couple of cron jobs that sometimes produce error output and would like to get a notification in my "real" email account, since I don't use my user's mailbox in my Ubuntu laptop, but cron (or is it postfix maybe) keeps trying to email the local root account.
I know I can add the MAILTO variable to the crontab:
ricardo@ricardo-laptop:~$ sudo crontab -l
[email protected]
# m h dom mon dow command
*/5 * * * * /home/ricardo/mrtg/cfg/run.sh
But it doesn't seem to pay any attention to it
I also tried adding my email to the /etc/aliases file and running newaliases
ricardo@ricardo-laptop:~$ cat /etc/aliases
# See man 5 aliases for format
postmaster: root
root: [email protected]
ricardo: [email protected]
still, whenever cron wants to send an email it's still sending it to [email protected]:
ricardo@ricardo-laptop:/var/log$ tail mail.log
Aug 3 16:25:01 ricardo-laptop postfix/pickup[2002]: D985B310: uid=0 from=<root>
Aug 3 16:25:01 ricardo-laptop postfix/cleanup[4117]: D985B310: message-id=<20100803192501.D985B310@ricardo-laptop>
Aug 3 16:25:01 ricardo-laptop postfix/qmgr[2003]: D985B310: from=<[email protected]>, size=762, nrcpt=1 (queue active)
Aug 3 16:25:03 ricardo-laptop postfix/smtp[4120]: D985B310: to=<[email protected]>, orig_to=<root>, relay=smtp.gmail.com[74.125.157.109]:25, delay=1.5, delays=0.38/0.02/0.9/0.18, dsn=5.7.0, status=bounced (host smtp.gmail.com[74.125.157.109] said: 530 5.7.0 Must issue a STARTTLS command first. d1sm12275173anc.19 (in reply to MAIL FROM command))
Any suggestions? I'm running Ubuntu 10.04, with everything up-to-date
A:
It would appear that you have configured smtp.gmail.com as your smarthost for the mail server. You need to remove the smarthost configuration or edit it so that your server is at all capable of sending mail to the outside world.
The configuration you have now for the mail forward appears to be working, but is failing because smtp.gmail.com is rejecting the mail.
Update: For future reference, the problem was in /etc/mailname which listed a name that wasn't in the mydestinations list of postfix. This caused all mails to be considered foreign and the mail bypassed /etc/aliases processing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can a C socket recv 0 bytes without the client shutting the connection?
I've implemented a web server in C. It calls recv() on a connected, blocking socket to receive an incoming HTTP request. The Linux man pages state the following about recv() on a blocking socket:
If no messages are available at the socket, the receive calls wait for a message to arrive...The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.
...
These calls return the number of bytes received, or -1 if an error occurred...The return value will be 0 when the peer has performed an orderly shutdown.
Hence, to receive the full request, my server code contains a loop of the following form:
int connfd; // accepted connection
int len; // # of received bytes on each recv call
...
while (/* HTTP message received so far has not terminated */) {
len = recv(connfd, ...);
if (len == 0) {
// close connfd, then escape loop
} else if (len < 0) {
// handle error
} else {
// process received bytes
}
}
My question: is it possible for recv() to return 0 bytes due to network issues and without the client performing an orderly shutdown, thereby causing my code to exit the loop prematurely? The man pages are ambiguous.
A:
TL;DR: POSIX says "no".
I don't think the man page is so unclear, but POSIX's description is perhaps a bit more clear:
The recv() function shall receive a message from a connection-mode or connectionless-mode socket.
[...]
Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error.
Thus, there are exactly three alternatives allowed by POSIX:
recv() successfully receives a message and returns its length. The length is nonzero by definition, for if no bytes were received then no message was received. recv() therefore returns a value greater than 0.
no message was received from the peer, and we are confident that none will be forthcoming because the peer has (by the time recv() returns) performed an orderly shutdown of the connection. recv() returns 0.
"otherwise" something else happened. recv() returns -1.
In any event, recv() will block if no data are available and no error condition is available at the socket, unless the socket is in non-blocking mode. In non-blocking mode, if there is neither data nor error condition available when recv() is called, that falls into the "otherwise" case.
One cannot altogether rule out that a given system will fail to comply with POSIX, but you have to decide somehow how you're going to interpret function results. If you're calling a POSIX-defined function on a system that claims to conform to POSIX (at least with respect to that function) then it's hard to argue with relying on POSIX semantics.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Importing Flat file dynamically using %MACRO and dataset values SAS
I have a folder with various flat files. There will be new files added every month and I need to import this raw data using an automated job. I have managed everything except for the final little piece.
Here's my logic:
1) I Scan the folder and get all the file names that fit a certain description
2) I store all these file names and Routes in a Dataset
3) A macro has been created to check whether the file has been imported already. If it has, nothing will happen. If it has not yet been imported, it will be imported.
The final part that I need to get right, is I need to loop through all the records in the dataset created in step 2 and execute the macro from step 3 against all file names.
What is the best way to do this?
A:
Look into call execute for executing a macro from a data step.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java.lang.IllegalStateException: Could not find method in a parent or ancestor Context for android:onClick attribute
I'm trying to add the onClick method front() to my Button. However when I click on the Button it returns this error:
java.lang.IllegalStateException: Could not find method front(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'front'
Here's my xml:
<Button
android:id="@+id/front"
android:onClick="front"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
Register.java:
public class Register extends AppCompatActivity {
private Button front;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
front = (Button) findViewById(R.id.front);
}
private void front(View v) {
Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
}
}
Any idea what the problem is?
A:
Your front method in your activity should be public. You have made it private right now.
This is described in Android Developer site too.
In order for this to work, the method must be public and accept a View as its only parameter
public void front(View v) {
Toast.makeText(Register.this, "String", Toast.LENGTH_LONG).show();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Usage of HTML5 Tags
Questions
On average, has the usage of HTML5
semantic tags increased compared to
the usage of CSS layers (div)?
Also, is there a good difference between them and does it optimize the code for better speed and maintainability?
Differences in character length is not much
and <div id="footer"> is
compatible in older browser without
using Modernizr or other
Javascript solutions to emulate
support of HTML5 in non supported
browsers.
Therefore, if I only use semantic
tags of HTML5, and not using any
advance functionality of HTML5 like
audio, video, etc. am I missing
something?
Examples
HTML
<footer> and <div id="footer">
CSS
#footer {} and Footer {}
A:
From what I've seen and experienced, HTML5 tags like and are mainly provided for SEO so that search engines can (one day?) possibly use those sections and other tags properly.
Like you said, most of the tags are semantic and provide no real functional benefit- in fact, most break rendering in older browsers. I ran into an issue with these new tags when I tried dynamically loading HTML5 content with jQuery and the HTML5Shiv.js/Modernizr.js. I was unable to properly render the elements that were dynamically loaded in older browsers such as IE8 and IE7.
At this point, I'd recommend sticking with divs, as they're more widely used and provide better cross-browser functionality.
My two cents.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I set the User Information in jetspeed?
We are using Jetspeed in a project and have a requirement that jetspeed should authenticate against a third party rest service which accepts username and password and returns back the User Object.
The most simplest and straightforward way I found of implementing this without effecting jetspeed too much was to write a custom AuthenticationProvider extending the DefaultAuthenticationProvider class and overriding the login method.
After I authenticate the user I get back the User details including roles, email, etc. Now if the user already exists in jetspeed database, I sync his roles, else I create the user and assign him the roles returned by the remote service.
Now I want a way to set the user.email, user.firstname and user.lastname properties too, so that it is accessible using $jetspeed.getUserAttribute in the psml files. Any idea how can we do this?
Here is my code [cut out unnecessary stuff] --
public class CustomAuthenticationProvider extends BaseAuthenticationProvider {
....
public AuthenticatedUser authenticate(String userName, String password) throws SecurityException {
try {
//Login the user
UserSessionDTO customSession = Security.login(userName, password);
//Fetch the user details
UserDTO customUser = customSession.getUser();
//Get the user roles
List<UserRoleDTO> roles = customUser.getUserRoleDTOList();
//Verify/create the user in jetspeed user database
UserImpl user = null;
if (!um.userExists(customUser.getLoginId())) {
user = (UserImpl) um.addUser(customUser.getLoginId(), true);
//Standard data
user.setMapped(true);
user.setEnabled(true);
} else {
user = (UserImpl) um.getUser(customUser.getLoginId());
}
//Sync the portal user roles with the CMGI user roles
List<Role> portalRoles = rm.getRolesForUser(customUser.getLoginId());
for (Role portalRole : portalRoles) {
Boolean found = Boolean.FALSE;
for (UserRoleDTO role : roles) {
if (role.getRoleName().equalsIgnoreCase(portalRole.getName())) {
found = Boolean.TRUE;
break;
}
}
if(!found){
rm.removeRoleFromUser(userName, portalRole.getName());
}
}
for(UserRoleDTO role : roles){
rm.addRoleToUser(userName, role.getRoleName());
}
PasswordCredential pwc = new PasswordCredentialImpl(user, password);
UserCredentialImpl uc = new UserCredentialImpl(pwc);
AuthenticatedUserImpl authUser = new AuthenticatedUserImpl(user, uc);
return authUser;
}
....
}
}
A:
You can add custom user attributes in Jetspeed user bean "org.apache.jetspeed.security.JetspeedPrincipalType.user" located in security-managers.xml.
These attributes should be defined like this
e.g
<bean class="org.apache.jetspeed.security.impl.SecurityAttributeTypeImpl">
<constructor-arg index="0" value="user.lastname" />
<constructor-arg index="1" value="info" />
</bean>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linear transformations for fixing the line $y = 0$
The professor says that the subgroup for "stabilizing" the line $y = 0$ is
$$A = \begin{bmatrix}
a & c \\
0 & d
\end{bmatrix}$$
because in order to fix the first basis vector, $b = 0$. The first column represents the transformation on the first basis vector, and the second column represents the transformation on the second basis vector. So to fix the line, the first basis vector is taken into some multiple of the first basis vector. So the coefficient of the second basis vector in the matrix will be $0$.
I did not understand any of this. Shouldn't $b$ and $d$ both be $0$ if you don't want to fix $y$? And doesn't this linear transformation $A$ he gave take a vector $(x ,y) \to (ax+cy, dy)$? I don't see how this fixes or "stabilizes" the line $y=0$.
A:
Your last sentence is completely correct. Now take a point on the line $y = 0$, say, $(x, 0)$. According to you, this transforms to $(ax + c \cdot 0, d \cdot 0) = (ax, 0)$, which is another point on that same line. So the line (as a set, not as individual points!) remains fixed.
Does that help?
If you want to have each point of the line $y = 0$ remain fixed, you need a matrix of the form
$$
\begin{bmatrix}
1 & c\\
0 & d
\end{bmatrix},
$$
which may have been what you thought the prof was saying.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matlab and XTickLabel
I've been trying to get Matlab to change the labelling on my contourf plots for about an hour now. When I go to change XTickLabel or XTick, it simply removes my x-axis altogether! The frustrating and infuriating thing is that I'm doing exactly what all the help pages and help forums are asking me to do - I honestly don't understand why this is not working.
Hence, I am here.
My plotting code (knowledge of the function shouldn't be required - the code is rather intense. It is, however, a 2D contourf plot with valid data and ranges - the axes are the issue, not the graph):
contourf(time,f,power,levels)
colormap(jet(levels))
set(gca,'XTickLabelMode','manual')
set(gca, 'XTick', 0:23);
set(gca, 'XTickLabel', {'0';'1';'23'});
xlabel('Time (UT)')
ylabel('Frequency (Hz)')
caxis([0,8])
axis([0 StopTime 0 0.1])
Any help would be greatly appreciated!
A:
Solved:
I realized that the 'XTick' relied on current values of the array I was using to define the x-axis. I can't just assume matlab will evenly space a new array (at least, if there's a way to do that, I don't know). So, since I have 85,680 data points on my X-axis, I simply rescaled it by:
set(gca, 'XTick', 0:3570:85680)
set(gca, 'XTickLabel', num2cell(0:24))
Moral of the story: Matlab doesn't let you arbitrarily stick a new axis over an old one using these two functions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Que significa for (;;) {} en java
por ejemplo que hace el for (;;) {} aqui?
que significa los ;; dentro del for?
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
else if (eat('-')) x -= parseTerm(); // subtraction
else return x;
}
}
A:
El uso de ;; en la declaración de tu bucle, lo vuelve de caracter infinito; observa el siguiente par de ejemplos
BUCLES INFINITOS
A través del siguiente ejemplo, puedes observar que es para declarar un bucle infinito; pues no estas declarando ni la variable que se va a utilizar ni el contador ni mucho menos el límite a respetar
public class MyClass {
public static void main(String args[]) {
for(;;)
{
System.out.println("Hola");
}
}
}
También lo puedes ver del siguiente modo, declaras la variable a usar y un valor inicial y después el contador de aumento e igual será infinito
public class MyClass {
public static void main(String args[]) {
for(int numero = 0;;numero++)
{
System.out.println(numero);
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to turn flat list into a nested array?
I have flat data:
$flatLists = [
[
'task',
'updater',
'updater_xml',
'some_customer',
'some_customer_de',
],
[
'task',
'updater',
'updater_xml',
'some_customer',
'some_customer_fr',
],
[
'task',
'updater',
'updater_json',
'yet_another_customer',
'yet_another_customer_us',
],
[
'task',
'updater',
'updater_json',
'updater_flatfile',
],
];
It represents a heritage structure, the first element is the first parent, and each entry is a child.
I now want transform this flat array in a nested array, so that the result looks like:
$expectedArray = [
'task' => [
'updater' => [
'updater_xml' => [
'some_customer' => [
'some_customer_de',
'some_customer_fr',
],
],
'updater_json' => [
'yet_another_customer' => [
'yet_another_customer_us',
],
'updater_flatfile',
],
],
],
];
I have tried iterating over the flat list in multiple ways via foreach, for and nothing was close to working and my brain hurts now.
I don't expect a working code example, yet I would appreciate some hints in how to solve this issue and hopefully I can post an answer of my own. Right now, I am stuck.
A:
Unlike your $expectedArray, this creates structure where leaves are keys with empty array as value:
$result = [];
foreach($flatLists as $list) {
$target = &$result;
foreach($list as $element) {
if(!isset($target[$element])) {
$target[$element] = [];
}
$target = &$target[$element];
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is an Iteration Path being assigned to new Work Items
My workplace has a local install of Azure DevOps version 17.143.28621.4.
When I am in the Boards > Backlog view and click the New Work Item button, it opens a popup to add a new user story with a button to add the new item to the top or bottom of the queue.
When I add a new item and click Add to Top or Add to Bottom, the work item is created and is assigned the current iteration path.
Why is the current iteration's path getting added? I would like the work item to be added at the base iteration path, not in the current iteration.
A:
The default iteration is set under Project Settings > Boards > Team Configuration > Iterations. By default this is set to @CurrentIteration, a macro which I think is self explanatory.
You can change the default iteration in the screen.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to ensure that a python function generates its output based only on its input?
To generate an output a function usually uses only values of its arguments. However, there are also cases in which function, to generate its output, reads something from a file system or from a database or from the web. I would like to have a simple and reliable way to ensure that something like that does not happen.
One way that I see is to create a white-list of python libraries that can be used to read from file system, database or web. But if it is the way to go, where can I get this (potentially huge) list. Moreover, I do not want to disable the whole library just because it can be used to read from the file system. For example I want users to be able to use pandas library (to store and manipulate tabular data). I just do not want them to be able to use this library to read data from the file system.
Is there a solution for this problem?
A:
The answer to this is no. What you are looking for is a function that tests for functional purity. But, as demonstrated in this code, there's no way to guarantee that no side effects are actually being called.
class Foo(object):
def __init__(self, x):
self.x = x
def __add__(self, y):
print("HAHAHA evil side effects here...")
# proceed to read a file and do stuff
return self
# this looks pure...
def f(x): return x + 1
# but really...
>>> f(Foo(1))
HAHAHA evil side effects here...
Because of the comprehensive way objects can redefine their behavior (field access, calling, operator overloading etc.), you can always pass an input that makes a pure function impure. Therefore the only pure functions are those that literally do nothing with their arguments... a class of functions that is generally less useful.
Of course, if you can specify other restrictions, this becomes easier.
A:
Your required restrictions can be broken even if you remove all modules and all functions. The code can get access to files, if it can use attributes of an arbitrary simple object, e.g. of number zero.
(0).__class__.__base__.__subclasses__()[40]('/etc/pas'+'swd')
The index 40 is individual and very typical for Python 2.7, but the index of subclass <type 'file'> can be easily found:
[x for x in (1).__class__.__base__.__subclasses__()if'fi'+'le'in'%s'%x][0](
'/etc/pas'+'swd')
Any combination of white list and blacklist is either insecure and/or too restrictive.
The pypy sandbox is robust by the principle without compromise:
... This subprocess can run arbitrary untrusted Python code, but all
its input/output is serialized to a stdin/stdout pipe instead of being
directly performed. The outer process reads the pipe and decides which
commands are allowed or not (sandboxing), or even reinterprets them
differently...
Also a solution based on seccomp kernel feature can be secure enough. (blog)
I want to be sure that in future the function will generate the same
output as today.
It is easy to write a function that has hard reproducible results and it can not be easily prevented:
class A(object):
"This can be any very simple class"
def __init__(self, x):
self.x = x
def __repr__(self):
return repr(self.x)
def strange_function():
# You get a different result probably everytimes.
return list(set(A(i) for i in range(20)))
>>> strange_function()
[1, 18, 12, 5, 16, 15, 8, 2, 14, 0, 6, 19, 13, 11, 10, 9, 17, 3, 7, 4]
>>> strange_function()
[0, 9, 14, 3, 17, 5, 6, 11, 8, 1, 15, 7, 12, 13, 2, 10, 16, 4, 19, 18]
... even if you remove everythng that depends on time, random number generator, order based on hash function etc., it is also easy to write a function that sometimes exceeds available memory or timeout limit and sometimes gives a result.
EDIT:
Roman, you wrote recently that you are sure you can believe the user. Then a realistic solution exists. It is to verify the input to and output from a function by recording it to a file and verifing it on a virtual machine running a remote IPython notebook (nice short tutorial video, support for remote computing out of box, restart of the backend service by web document menu from the browser in one second, without loss of data (input/output) in the notebook (html document) because it is created dynamically step by step by our activity triggering the javascript that calls the remote backend).
You need not be interested in internal calls, only the global input and output, until you find a difference. The virtual machine should be able to verify the results independently and reproducible. Configure the firewall that the machine accepts connections from you, but can not initiate an outgoing connection. Configure the filesystem that no data can be saved by the current user and therefore they are not present, except software components. Disable database services. Verify the results input/output in a random order or start two IPython notebook services on different ports and select a random backend for every command line on the notebook, or restart the backend process frequently before anything important. If you find a difference, debug your code and fix it.
You can automate it without "notebook" finally only with IPython remote computing after you don't need interactivity.
A:
What you want is called sandboxing or restricted Python.
Both are mostly dead.
The closest to functional today is http://pypy.readthedocs.org/en/latest/sandbox.html note however that newest build is actually 3 years old.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. - DECLARE to use SPLIT_ROW
I have that query:
DECLARE @test AS varchar =
(select * from users where Usr_ID in
(select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931))
And I've got an error "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." The result of select statement are three numbers, which i need to split into three rows.
A:
(select * from users where Usr_ID in
(select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931))
you query returns multiple rows as a result variable can not contain multiple rows value.
if your query just return one value then it will return correct result
but if you change your query like below then it will works
DECLARE @test AS varchar =
(select top 1 Doc_Shortstringcolumn1 from users where Usr_ID in
(select Doc_Shortstringcolumn1 from Documents where Doc_ID = 11931)
)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
convert yyyymmdd to mm/dd/yyyy on csv file
Please help. I need a unix shell command for the sample.csv file with records below:
1231,aaa,bbb,20161001,20161002,hi-ax
1231,aaa,ccc,20161002,20161003,hi-ay
1231,aaa,ddd,20161001,20161007,hi-az
And output should be:
1231,aaa,bbb,10/01/2016,10/02/2016,hi-ax
1231,aaa,ccc,10/02/2016,10/03/2016,hi-ay
1231,aaa,ddd,10/01/2016,10/07/2016,hi-az
Can someone fix the this command? I've tried it but it won't work without a delimiter:
awk -F, '{split($4,a,"");$4=a[2]"/"a[3]"/"a[1]}1' OFS=, sample.csv > output.csv
A:
I would rather go with a function for something like this, it makes it more maintainable, e.g.:
convert-date.awk
function ruin_utc(d) {
year = substr(d, 1, 4)
month = substr(d, 5, 2)
day = substr(d, 7, 2)
return month "/" day "/" year
}
You can now use the function like this:
awk -f convert-date.awk -e '{ $4 = ruin_utc($4); $5 = ruin_utc($5) } 1' FS=, OFS=, sample.csv
Or more portable:
convert-date2.awk
function ruin_utc(d) {
year = substr(d, 1, 4)
month = substr(d, 5, 2)
day = substr(d, 7, 2)
return month "/" day "/" year
}
{ $4 = ruin_utc($4); $5 = ruin_utc($5) }
1
Run it like this:
awk -f convert-date.awk FS=, OFS=, sample.csv
Output:
1231,aaa,bbb,10/01/2016,10/02/2016,hi-ax
1231,aaa,ccc,10/02/2016,10/03/2016,hi-ay
1231,aaa,ddd,10/01/2016,10/07/2016,hi-az
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to import/export QTableWidget to some file?
Is there some simple way in PyQt to store data from QTableWidget to some file, and use that content again? It's not a critical task for me, so i don't want to invent some custom xml rules or somethin else.
A:
Qt provides a (modified) Model->View framework and so the data in a table, or any other GUI widget, is stored in a data model. It's the data in the model that you want to persist. The GUI widgets themselves don't provide any facilities to do this.
There's no standard data persistence method implemented in the Qt data model components. Qt does provide fatures to persist data structures to disc in binary (QDataStream), text (QTextStream) and XML (QDomDocument) formats. However if you're using PyQt you're probably better off using Python's built-in data persistence libraries such as Pickle or Shelve, or it's JSON or XML libraries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can there be a scenario where the use of an IED against an enemy is legally justifiable? (It's for a book, I swear...)
Before I go any further, let me be clear that this is for a work of fiction.
Doing some research for a story where a military protagonist becomes trapped behind enemy lines, with a plan to have her hold out until rescue against superior forces by adopting asymmetric warfare tactics, including the use of improvised explosive devices. This is an urban environment, but it's a situation where most of the civilians formerly in the area are already gone (either dead, fled, or captured), and she's actively trying to keep the enemy away from a pocket of survivors.
Under standard Western rules of war, is it legal for her to use IEDs in this context? I did a little research already but that article mostly just deals with IEDs being used partially or fully for ideological reasons with no care to collateral damage (and often deliberately targeting civilians).
A:
The fact that an explosive device is improvised is irrelevant to any law of war with which I am familiar.
"Legal in war" is more a matter of deciding which treaty, convention, or custom you care to respect.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lightning button icon without border
Is it possible to remove the border on a lightning button icon when it clicked?
<lightning:buttonIcon iconName="utility:dislike" variant="bare" onclick="{!c.downVote}" size="medium""
<lightning:buttonIcon iconName="utility:like" variant="bare" onclick="{!c.upVote}" size="medium" " />
A:
As sfdcfox already said That border is there to indicate active focus.....
but if you still want to remove it
assign a class to button icon like this
<lightning:buttonIcon iconName="utility:like" variant="bare" alternativeText="Settings" size="medium" class="test" />
then use that class to target during focus
css
.THIS .test:focus{
box-shadow:none;
}
if button icon is first element then
.THIS.test:focus{
box-shadow:none;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use zipsplit (or equivalent) on very large files?
According to the man pages, zipsplit does not work on files larger than 2GB.
Is there an equivalent or alternative that would allow me to break up, say, 4GB of files into 500MB chunks in a way that a typical Windows user could access easily? ( I say "typical Windows user" to exclude solutions like gzip, tar, and split(1) ... these aren't workable for the purpose at hand)
Thanks!
A:
7-Zip is a free archiving tool that will do what you're asking for.
Ehtyar.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Typo3 custom FE login without form
Update (2020-04-07): Solution code based on accepted answer below the line.
I am building an extension for Typo3 v9.5 using extbase where I am trying to implement a different entry point for logging in frontend users (think: one-time token via e-mail). So the login form would be bypassed and the credentials retrieved from the DB to log in the user via code. With that said, I want to reuse as much of the login and session logic as possible, that is already there.
I have found a passable solution that superficially seems to work, but I'm not sure, if that is something that will keep working across updates ($GLOBALS['TSFE']->fe_user being converted to the Context API) and I'm pretty convinced it's not the most elegant way. Ideally, I could use this with minor adaptions in the upcoming Typo3 v10. In some cases I'm not even sure I'm using APIs that are supposed to be used publicly.
Let me lay out what I've done so far in the most compact way I can think of:
<?php
# FILE: my_ext/Classes/Authentication/CustomAuthentication.php
use \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
class CustomAuthentication extends FrontendUserAuthentication {
// FrontendUserAuthentication seems to be hard-coded to gather credentials
// that were submitted via login form, so we have to work around that
protected $_formData = [];
// new method, set credentials normally entered via form
public function setLoginFormData(array $data) {
$this->_formData = $data;
}
// new method, set storage PID where user records are located, set via Extbase Controller/TS
public function setStoragePid(int $pid) {
$this->checkPid_value = $pid;
}
// override, ignore parent logic, simply return custom data
public function getLoginFormData() {
return $this->_formData;
}
}
<?php
# FILE: my_ext/Classes/Controller/SessionController.php
use \TYPO3\CMS\Core\Context\Context;
use \TYPO3\CMS\Core\Context\UserAspect;
use \TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use MyExt\MyVendor\Authentication\CustomAuthentication;
class SessionController extends ActionController {
// controller action
public function someAction() {
/*...*/
$loginData = [ /* assume this is retrieved from somewhere */ ];
$this->login($loginData);
/*...*/
}
// perform login
protected function login($data) {
$feAuth = $this->objectManager->get(CustomAuthentication::class);
// use my new methods to inject data
$feAuth->setLoginFormData($data);
$feAuth->setStoragePid($this->settings['pid']);
// the next part imitates what is going on in
// typo3/sysext/frontend/Classes/Middleware/FrontendUserAuthenticator.php
$feAuth->start();
$feAuth->unpack_uc(); // necessary?
$feAuth->fetchGroupData();
// login successful?
if(is_array($feAuth->user) && !empty($feAuth->groupData['uid']) {
$this->setGlobals($feAuth, $feAuth->groupData['uid']);
$feAuth->updateOnlineTimestamp(); // necessary?
}
}
// perform logout
protected function logout() {
//$feAuth = $GLOBALS['TSFE']->fe_user; // deprecated?
$feAuth = $this->objectManager->get(FrontendUserAuthentication::class);
// 'rehydrate' the pristine object from the existing session
$feAuth->start();
$feAuth->unpack_uc(); // necessary?
$feAuth->logoff();
$feAuth->start(); // create fresh session ID, so we can use flash messages and stuff
$this->setGlobals($feAuth);
}
protected function setGlobals(FrontendUserAuthentication $auth, array $grpData=[]) {
$GLOBALS['TSFE']->fe_user = $feAuth; // TODO remove in Typo3 v10?
$ctx = $this->objectManager->get(Context::class);
$ctx->setAspect('frontend.user', $this->objectManager->get(UserAspect::class, $feAuth, $groupData));
$feAuth->storeSessionData(); // necessary?
}
}
I guess the question I have would be, whether there is a better way to do that or if anyone more familiar with the internals of Typo3 could comment, if this is acutally a viable possibility to achieve what I want to do with it.
Thanks!
Update (2020-04-07):
I followed the suggestion from the accepted answer, and I'm posting my code, so other people may be able to use it, if necessary (in mostly abbreviated form).
Below is the service class, that will handle token verification.
# FILE: my_ext/Classes/Service/TokenAuthenticationService.php
<?php
use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
use \TYPO3\CMS\Core\Authentication\LoginType;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use \TYPO3\CMS\Core\Utility\GeneralUtility;
class TokenAuthenticationService extends AbstractAuthenticationService {
protected $timestamp_column = 'tstamp'; // last-changed timestamp
protected $usertoken_column = 'tx_myext_login_token';
public function getUser() {
if($this->login['status'] !== LoginType::LOGIN) {
return false;
}
if((string)$this->login['uname'] === '') {
$this->logger->warning('Attempted token login with empty token', ['remote'=>$this->authInfo['REMOTE_ADDR']]);
return false;
}
// fetch user record, make sure token was set at most 12 hours ago
$qb = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->db_user['table']);
$where_clause = $qb->expr()->andX(
$qb->expr()->eq($this->usertoken_column, $qb->expr()->literal($this->login['uname'])),
$qb->expr()->gte($this->timestamp_column, (int)strtotime('-12 hour'))
);
// Typo3 v10 API will change here!
$user = $this->fetchUserRecord('', $where_clause);
if(!is_array($user)) {
$this->logger->warning('Attempted token login with unknown or expired token', ['token'=>$this->login['uname']]);
return false;
} else {
$this->logger->info('Successful token found', ['id'=>$user['uid'], 'username'=>$user['username'], 'token'=>$this->login['uname']]);
}
return $user;
}
public function authUser(array $user): int {
// check, if the token that was submitted matches the one from the DB
if($this->login['uname'] === $user[$this->usertoken_column]) {
$this->logger->info('Successful token login', ['id'=>$user['uid'], 'username'=>$user['username'], 'token'=>$this->login['uname']]);
return 200;
}
return 100; // let other auth services try their luck
}
}
Then register the Service:
# FILE: my_ext/ext_localconf.php
// Add auth service for token login
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
$_EXTKEY,
'auth',
\MyVendor\MyExt\Service\TokenAuthenticationService::class,
[
'title' => 'Token Auth',
'description' => 'Allows FE user login via one-time token',
'subtype' => 'getUserFE,authUserFE',
'available' => true,
'priority' => 60,
'quality' => 50,
'className' => \MyVendor\MyExt\Service\TokenAuthenticationService::class
]
);
When creating a token, the user gets a link to a page with the added token parameter, like:
[...]/index.php?id=123&tx_myext_pi[action]=tokenAuth&tx_myext_pi[token]=whatever-was-stored-in-the-db
Since we need a few parameters to trigger the login middleware, we render a mostly hidden form on that landing page, which prompts the user to 'confirm'.
<!-- FILE: my_ext/Resources/Private/Templates/Some/TokenAuth.html -->
<f:if condition="{token}">
<h2>Token Login</h2>
<p>Please confirm</p>
<f:form action="doLogin" fieldNamePrefix="">
<f:form.hidden name="logintype" value="login" />
<f:form.hidden name="pid" value="{settings.membersPid}" />
<f:form.hidden name="user" value="{token}" />
<f:form.button>Confirm</f:form.button>
</f:form>
</f:if>
That request will now automatically perform the login, with all the right parameters. In your controller action, you can then add some kind of flash message or redirect to wherever it makes sense.
# FILE: my_ext/Classes/Controller/SomeController.php
<?php
use \TYPO3\CMS\Core\Context\Context;
use \TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
class SomeController extends ActionController {
public function doLoginAction() {
$ctx = $this->objectManager->get(Context::class);
if($ctx->getPropertyFromAspect('frontend.user', 'isLoggedIn')) {
// success
} else {
// failure
}
}
}
A:
You should implement an authentication service this Service only needs to imlement the "authUser()" function. So every thing else might be handled by the core authentication.
See here for details https://docs.typo3.org/m/typo3/reference-services/8.7/en-us/Authentication/Index.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to implement Java's HashMap.equals(HashMap) in JavaScript
I am trying to write a function that takes two strings and returns whether or not they have the same frequency of letters. It is assumed that neither string is null.
Here is my Java implementation:
public void addToMap(HashMap<String, Integer> map, String s){
if(map.get(s) == null){
map.put(s, 1);
} else{
map.put(s, map.get(s)+1);
}
}
public boolean perm(String a, String b){
if(a.length() != b.length()){
return false;
}
HashMap<String, Integer> aMap = new HashMap<>();
HashMap<String, Integer> bMap = new HashMap<>();
for(int i = 0; i < a.length(); i++){
addToMap(aMap, a.substring(i,i+1));
addToMap(bMap, b.substring(i,i+1));
}
return aMap.equals(bMap);
}
I am trying to replicate this in JavaScript:
const addToMap = (map, s) => {
if(map[s] == null){
map[s] = 1;
} else{
map[s] = map[s]+1;
}
}
const perm = (a,b) => {
if(a.length != b.length){
return false;
}
let aMap = new Map();
let bMap = new Map();
for(let i = 0; i < a.length; i++){
addToMap(aMap, a.substring(i,i+1));
addToMap(bMap, b.substring(i,i+1));
}
return aMap === bMap;
}
I tested perm("abca", "bcaa") for both implementations. The Java code returns true, which is correct. However, the JS functions return false.
Is there a way to return that two maps are equal in JS when they have the same keys and values, but in a different order?
A:
Here is the code that I created that works:
const addToMap = (map, s) => {
if(map.has(s)){
map.set(s, map.get(s)+1);
} else{ map.set(s, 1);}
}
const perm = (a, b) => {
if(a.length != b.length){ return false; }
let aMap = new Map();
let bMap = new Map();
for(let i = 0; i < a.length; i++){
addToMap(aMap, a.substring(i, i+1));
addToMap(bMap, b.substring(i, i+1));
}
return aMap.toString() == bMap.toString();
}
const s1 = "abcda";
const s2 = "cdbaa";
console.log(perm(s1, s1));
What happened is I was using the wrong syntax for Map(). I was using bracket notation to create my key value pairs instead or Map.prototype methods.
See this code sample:
let m = new Map();
m.set(1, "a");
m[2] = "b";
console.log(m);
//Output: Map { 1 => 'a', 2: 'b' }
Using the Map.get and Map.set methods works for me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Access array of server side in jQuery
I have a pie chart for which I want to populate the data. I have been able to set the data in jQuery like this
var data = [
{ label: "Abc", data: 12 },
{ label: "xyz", data: 15 },
{ label: "Setwet", data: 85 },
{ label: "DashOut", data: 30 },
];
I want to be able to set the same data from my code behind file from database, and access it in jQuery. How can I do that?
My database does have all the information. I have created a class with two members label and data. I have created a collection of this class and added values from database table to this collection like this
private List<myData> _myData;
public List<myData> MyData
{
get
{
if (_myData == null)
{
_myData = new List<myData>();
_myData.Add(new myData() { label = "abc", data = "10" });
_myData.Add(new myData() { label = "def", data = "20" });
}
return _myData;
}
set { _myData = value; }
}
My jQuery is expecting an array but in code i have created a Collection of user defined class. Will that be ok? or how should I go about it?
A:
There are several forms to do this. Can convert (serialize) MyData to json using JavaScriptSerializer and save in hidden field:
hiddenfield.Value = new JavaScriptSerializer().Serialize(MyData)
then, can access to this from client-side:
var data = $("hiddenfield").val();
Can use WebMethod and use javascript from server-side.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java -version tells me 8 but jdk is 1.7 - OSX 10.9.x
Something I don't understand - I'm on OSX 10.9.5 and when I run java -version at the terminal, I get:
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
But in my /Library/Java/JavaVirtualMachines/ dir I see 3 JDKs:
jdk1.7.0_71.jdk
jdk1.7.0_75.jdk
jdk1.7.0_76.jdk
Eclipse uses jdk1.7.0_76.jdk. I remember installing Java 7 for some personal dev projects in Eclipse, but I don't recall ever installing Java 8. So why would java -version say I'm running 8? And how can it if no jdk exists for Java 8 in that directory?
Confused. TIA.
A:
The version you are questioning is actually the Java Runtime Environment (JRE) version, not the Java Developer Kit (JDK) version; they are two different things. You are running Java 8 (JRE), although you can selectively choose another runtime if there is one available.
If you want to see all of the versions of Java you might currently have:
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (3):
1.8.0_45, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
1.6.0_65-b14-466.1, x86_64: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
1.6.0_65-b14-466.1, i386: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
To see which one is currently running as default:
$ which java ; java -version
/usr/bin/java
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
To see which JDKs are installed:
$ ls /Library/Java/JavaVirtualMachines/
jdk1.8.0_45.jdk
The Java Runtime Environment (JRE)
The JRE allows you to run applications written in the Java programming language. Like the JDK, it contains the Java Virtual
Machine (JVM), classes comprising the Java platform API, and
supporting files. Unlike the JDK, it does not contain development
tools such as compilers and debuggers.
The Java Development Kit (JDK)
The JDK is a development environment for building
applications, applets, and components using the Java programming
language. The JDK includes tools useful for developing and testing programs written in the Java programming language and running on
the Java platform.
Since Eclipse relies on the tools within the JDK they would most definitely be using one of your installed JDKs, for it couldn't work just using the JRE.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Easy way to generate colour-per-vertex models for input to Blender
I procedurally generate 3D planet models that I would like to import into Blender.
I use colour per vertex rendering in my shaders (In practice, I use the same colour for all vertices of a face, but my vertex attributes include RGBA.)
I like generating wavefront .obj files, because the syntax is so easy. But wavefront obj does not let me specify colour per vertex, or colour per face. Instead, the entire object is coloured with a material from the material-library that accompanies the obj geometry file.
I've looked into collada .dae as well, but frankly, that seems like a very complex format, and it still seems to work with material libraries, like the .obj format does.
Is there an easy to generate 3d model format that lets me specify a colour per vert (or face) without material libraries, and can be imported into Blender?
A:
So, Stanford's .PLY Polygon File Format is the winner here.
Although, after the import into Blender, some actions are required to actually see the colours.
PLY supports colour-per-vertex and colour-per-face, but I've found that Blender can only handle the colour-per-vertex files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MPMoviePlayerController - Duration always 0
iPhone4, iOS 4.3.3, iOS SDK4.3
Hi all,
I'm creating a video upload feature. The videos are retrieved using UIImagePickerController and can be captured using the camera or picked from the photo library. I have an application constraint of 60 seconds max duration. This is easily achieved when recording the video using the camera via:
// Limit videos to 60 seconds
[picker setVideoMaximumDuration:60];
However when the video is selected from the photo library the only way I see of obtaining the duration is via MPMoviePlayerController duration property as follows:
// MediaType can be kUTTypeImage or kUTTypeMovie.
NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSLog(@"%@",mediaType);
// if its a movie
if ( [mediaType isEqualToString:(NSString*)kUTTypeMovie] ) {
// get the URL
NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"%@",mediaURL);
// can use MPMoviePlayerController class to get duration
int duration = -1;
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: mediaURL];
if (moviePlayer != nil) {
duration = moviePlayer.duration;
NSString *path = moviePlayer.contentURL;
[moviePlayer release];
}
however the duration is always 0. I know the video has a duration because the duration is displayed as part of the subtitle when selecting it in the photo library. I understand that duration may not always be available but in this case the duration is displayed in photo lib. I also check the contentURL property and it has a good value. I'm able to retrieve the file, get its filesize etc so I know the NSURL of the file is good...
Thanks!
A:
I don't see anything immediately wrong with your code. However, using AVFoundation is much faster for this type of operation. Here's a code snippet to get the duration using AVFoundation:
AVURLAsset *asset = [[[AVURLAsset alloc] initWithURL:anURI
options:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES],
AVURLAssetPreferPreciseDurationAndTimingKey,
nil]] autorelease];
NSTimeInterval durationInSeconds = 0.0;
if (asset)
durationInSeconds = CMTimeGetSeconds(asset.duration) ;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove shadow below UINavigationBar with UISearchController
I could successfully remove the shadow below the navigation bar with the following line of code.
self.navigationController?.navigationBar.shadowImage = UIImage()
When I added a search controller however, the shadow reappeared.
self.navigationItem.searchController = UISearchController(searchResultsController: nil)
I tried the following, but resulted an unexpected behavior.
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.barTintColor = .white
self.navigationController?.navigationBar.isTranslucent = false
How do I remove the shadow under a navigation bar when there is a search controller attached?
A:
I have not found good solution too...
for now I will hide it this way:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let imageView = navigationItem.searchController?.searchBar.superview?.subviews.first?.subviews.first as? UIImageView {
imageView.isHidden = true
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to programmatically add constraint layouts to a scrollview?
I have the following in mind:
Create a new Activity which contains somewhere on the layout a scrollview
Create a ConstraintLayout (width is on match-parent) with one edit-field and one textview next to eachother
=> Now I would like to add with something like a button any number of constraint layouts of this kind to the scrollview.
Can somebody explain how this is done? Is it even possible this way.
(in AndroidStudio)
Edit:
I tried the following:
protected void addElementToScrollView() {
ScrollView sv = getLayoutInflater()
.inflate(R.layout.activity_goods_received_separation_on_container_level, null)
.findViewById(R.id.scrollViewChanges);
ConstraintLayout cl = findViewById(R.id.gc_scrollview_element);
sv.addView(cl);
}
This is inside the activity containing the scrollview:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GoodsReceived_Separation_On_ContainerLevel">
<TextView
android:id="@+id/goods_received_num"
android:layout_width="73dp"
android:layout_height="27dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.601"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toBottomOf="@+id/goods_received_mat2" />
<TextView
android:id="@+id/goods_received_mat2"
android:layout_width="73dp"
android:layout_height="27dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.601"
app:layout_constraintStart_toEndOf="@+id/textView2"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="73dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_num"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
<TextView
android:id="@+id/textView7"
android:layout_width="120dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_eme"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/divider" />
<TextView
android:id="@+id/textView8"
android:layout_width="120dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_loc"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView10" />
<TextView
android:id="@+id/textView10"
android:layout_width="120dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_type"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView9" />
<TextView
android:id="@+id/textView9"
android:layout_width="120dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_bme"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView7" />
<TextView
android:id="@+id/textView3"
android:layout_width="73dp"
android:layout_height="27dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_mat"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/divider"
android:layout_width="368dp"
android:layout_height="3dp"
android:layout_marginTop="8dp"
android:background="?android:attr/listDivider"
android:divider="#000000"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/goods_received_num" />
<ScrollView
android:id="@+id/scrollViewChanges"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="48dp"
android:fillViewport="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView8">
</ScrollView>
<Button
android:id="@+id/button_apply_gr_change"
android:layout_width="137dp"
android:layout_height="68dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/scrollViewChanges" />
<TextView
android:id="@+id/textView11"
android:layout_width="100dp"
android:layout_height="26dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_loc"
app:layout_constraintBottom_toTopOf="@+id/scrollViewChanges"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textView13"
app:layout_constraintTop_toBottomOf="@+id/textView8"
app:layout_constraintVertical_bias="0.2" />
<TextView
android:id="@+id/textView13"
android:layout_width="100dp"
android:layout_height="26dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_type"
app:layout_constraintBottom_toTopOf="@+id/scrollViewChanges"
app:layout_constraintEnd_toStartOf="@+id/textView11"
app:layout_constraintStart_toEndOf="@+id/textView12"
app:layout_constraintTop_toBottomOf="@+id/textView8"
app:layout_constraintVertical_bias="0.2" />
<TextView
android:id="@+id/textView12"
android:layout_width="100dp"
android:layout_height="26dp"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="@string/goods_received_eme"
app:layout_constraintBottom_toTopOf="@+id/scrollViewChanges"
app:layout_constraintEnd_toStartOf="@+id/textView13"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView8"
app:layout_constraintVertical_bias="0.222" />
<View
android:id="@+id/divider3"
android:layout_width="368dp"
android:layout_height="1dp"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:background="?android:attr/listDivider"
app:layout_constraintBottom_toTopOf="@+id/textView11"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView8" />
</android.support.constraint.ConstraintLayout>
And this is the layout element which I try to add to the scroll view (any number of times, so it shall be possible to have for example 10 of these at the same time in the scrollview and the number should be dynamical increasable)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gc_scrollview_element"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="@+id/spinner"
android:layout_width="100dp"
android:layout_height="27dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/spinner3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="@+id/spinner3"
android:layout_width="100dp"
android:layout_height="27dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/spinner2"
app:layout_constraintStart_toEndOf="@+id/spinner"
app:layout_constraintTop_toTopOf="parent" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="100dp"
android:layout_height="27dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/spinner3"
app:layout_constraintTop_toTopOf="parent" />
(I know it contains different elements than the question suggested, but I think there is no difference to the problem.)
My solution crashes while testing at "sv.addView(cl);".
(Thank you for the already suggested solution, will test it as soon as I understand what I am doing wrong here...)
A:
Please try below code, i have added two button, you can replace button with textview or edittext or any other controls.
Suggestion :-
If you use any ui controls inside ConstraintLayout programmatically then please define its id.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ConstraintLayout constraintLayout = findViewById(R.id.constraintlayout);
// Create btn_contact_us1
Button btn_contact_us1 = new Button(this);
// Generate an Id and assign it to programmatically created Button
btn_contact_us1.setId(View.generateViewId());
btn_contact_us1.setText("Contact Us 1");
btn_contact_us1.setLayoutParams(new ConstraintLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// Add programmatically created Button to ConstraintLayout
constraintLayout.addView(btn_contact_us1);
// Create btn_contact_us2
Button btn_contact_us2 = new Button(this);
// Generate an Id and assign it to programmatically created Button
btn_contact_us2.setId(View.generateViewId());
btn_contact_us2.setText("Contact Us 2");
btn_contact_us2.setLayoutParams(new ConstraintLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// Add programmatically created Button to ConstraintLayout
constraintLayout.addView(btn_contact_us2);
// Create ConstraintSet
ConstraintSet constraintSet = new ConstraintSet();
// Make sure all previous Constraints from ConstraintLayout are not lost
constraintSet.clone(constraintLayout);
// Create Rule that states that the START of btn_contact_us1 will be positioned at the END of btn_contact_us2
constraintSet.connect(btn_contact_us2.getId(), ConstraintSet.START, btn_contact_us1.getId(), ConstraintSet.END);
constraintSet.applyTo(constraintLayout);
}
and the layout code is as below
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.constraint.ConstraintLayout
android:id="@+id/constraintlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ScrollView>
Output:- check link image
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Combine two SQL statements where both must be true in many to many relationship
I'm still quite inexperienced in SQL, and I'm trying to figure out how to combine two requirements for a query.
First the model, to simplify understanding the requirement:
I need one set of results, getting rows that match either of the values in one list, I'll call this result 1:
SELECT * FROM
resource r
inner join
category_resource cr
on (r.id = cr.resource_id)
where cr.category_id in (8,9)
But there is also a second requirement, which I'll call result 2:
A similar statement, but with other values must also be matched (by the same rows) in order for any of these rows to match:
SELECT * FROM
resource r
inner join
category_resource cr
on (r.id = cr.resource_id)
where cr.category_id in (10,11,12)
Of course I feel like this is redundant in some way and there should be an easier way to write it all in one statement. But the point of it is, this does NOT fulfil the requirements:
SELECT * FROM
resource r
inner join
category_resource cr
on (r.id = cr.resource_id)
where cr.category_id in (8,9,10,11,12)
Since that would just be equivalent to saying match result 1 OR result 2. But what I need is to match result 1 AND result 2. I.e, something like:
SELECT * FROM
resource r
inner join
category_resource cr
on (r.id = cr.resource_id)
where cr.category_id in (8,9) AND (10,11,12)
But that does not work (probably not correct at all)...
In plain English finally, what I want is to find any resource that has the category 8 OR 9, AND has the category 10 OR 11 OR 12.
So how can I accomplish something like this as simply as possible?
EDIT:
I forgot one requirement:
I have to also get the categories that each of the result rows belong to (whether those categories were asked for in the query or not. I.e even if I just ask for any resource belonging to (8 OR 9) AND (10 OR 11 OR 12), if a resource matches, I want to know all the categories it belongs to even if they could include also 13 and 14 for instance...
I had a similar requirement which I got resolved before that pretty much does this:
SELECT
r.id, r.title,
u.name AS 'created_by',
GROUP_CONCAT( CONCAT(CAST(c.id as CHAR),',',c.name,',',c.value) separator ';') AS 'Categories'
FROM
resource r
INNER JOIN
/*Select matching records as a table*/
(SELECT
resource_id
FROM
category_resource
WHERE
category_id IN (9,10,11,12,13,14,15)) mr
ON r.id = mr.resource_id
INNER JOIN category_resource cr
ON r.id = cr.resource_id
INNER JOIN category c
ON cr.category_id = c.id
INNER JOIN user u
ON r.created_by = u.id
GROUP BY r.id;
But that statement of course does not incorporate this latest requirement. Can I combine this and get the results including all categories each result belongs to?
The answer from mrjink seems to work perfectly. And I have also tested using the same pattern to add even more criteria along the same lines, and it seems to work great:
SELECT
r.id, r.title,
u.name AS 'created_by',
GROUP_CONCAT( CONCAT(CAST(c.id as CHAR),',',c.name,',',c.value) separator ';') AS 'Categories'
FROM
resource r
INNER JOIN
/*Select matching records as a table*/
(SELECT
DISTINCT r.id AS id
FROM
resource r
INNER JOIN
category_resource cr1 ON (r.id = cr1.resource_id)
INNER JOIN
category_resource cr2 ON (r.id = cr2.resource_id)
/*For more criteria, I can just add an inner join here with another alias...*/
INNER JOIN
category_resource cr3 ON (r.id = cr3.resource_id)
INNER JOIN
category_resource cr4 ON (r.id = cr4.resource_id)
WHERE
cr1.category_id IN (8, 9)
AND
cr2.category_id IN (10)
/*and add the corresponding ADD clause here for the same alias...*/
AND
cr3.category_id IN (12)
AND
cr4.category_id IN (14)) mr
ON r.id = mr.id
INNER JOIN category_resource cr
ON r.id = cr.resource_id
INNER JOIN category c
ON cr.category_id = c.id
INNER JOIN user u
ON r.created_by = u.id
GROUP BY r.id;
This way I can add more criteria programmatically if the user selects them (as is the intention). From what I can see, although this might create really complex SQL statements if one were to write or read them by hand, it seems to work well and does not affect performance in a negative way (if anything, adding more criteria seems to speed it up, presumably because there are less and less hits?)
A:
Join twice!
Something like this should work:
SELECT
r.id, r.title,
u.name AS 'created_by',
GROUP_CONCAT( CONCAT(CAST(c.id as CHAR),',',c.name,',',c.value) separator ';') AS 'Categories'
FROM
resource r
INNER JOIN
/*Select matching records as a table*/
(SELECT
DISTINCT r.id AS id
FROM
resource r
INNER JOIN
category_resource cr1 ON (r.id = cr1.resource_id)
INNER JOIN
category_resource cr2 ON (r.id = cr2.resource_id)
WHERE
cr1.category_id IN (8, 9)
AND
cr2.category_id IN (10, 11, 12)) mr
ON r.id = mr.id
INNER JOIN category_resource cr
ON r.id = cr.resource_id
INNER JOIN category c
ON cr.category_id = c.id
INNER JOIN user u
ON r.created_by = u.id
GROUP BY r.id;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SSH over OpenVPN without Admin rights
Would it be possible to install openvpn on a machine without admin rights? Of course it wouldn't be possible to change the network routings but this shouldn't be a problem. I only want to run a ssh client on it like putty. How would I configure the ssh client to use the vpn connection?
A:
It could be possible technically, but the OpenVPN software doesn't support being used that way. (It'd need to have its own TCP implementation, at minimum, and that'd likely make it more complex than it's worth.)
If you cannot change the routing table, you won't be able to connect through the VPN.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android how to divide half screen?
How to create layout with like this image. 50% text and rest of 50% divide by imageview textview and imageview what do i do?
please help me. I want to create screen like this image help me please.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/db1_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="6"
android:background="#333333" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:layout_weight="0"
android:weightSum="1.5"
android:layout_marginBottom="1dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_marginRight="15dip"
android:layout_marginLeft="15dp"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:background="@drawable/layoutborder"
android:layout_marginBottom="1dp"
android:layout_marginTop="1dp"
android:layout_weight="0.8"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:paddingLeft="1dip"
android:src="@drawable/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:paddingTop="5dp"
android:textSize="10dip"
android:text=CONTAINS"
android:textColor="#FFffff" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:paddingLeft="1dip"
android:src="@drawable/ic_launcher" />
</LinearLayout>
<TextView
android:id="@+id/imageView1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:paddingLeft="1dip"
android:text="kurdfgkjdfuhfudshfkdshfdfhs
kdjhfjdshfkjdshfkdshfkshjdhfskjhfksdhfksjhfkjsdhfkjsdhfk
jshfshfshfdshdfshdkjfhsafkjsahdfksahdf" />
</LinearLayout>
</LinearLayout>
A:
Try
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/db1_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#333333"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="1dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="1dp"
android:layout_weight="1"
android:background="@color/blue"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.4"
android:paddingLeft="1dp"
android:src="@drawable/login_down" />
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_weight="0.2"
android:paddingTop="5dp"
android:text="CONTAINS"
android:textColor="#FFffff"
android:textSize="10dip" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.4"
android:paddingLeft="1dp"
android:src="@drawable/login_button" />
</LinearLayout>
<TextView
android:id="@+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="1dp"
android:text="kurdfgkjdfuhfudshfkdshfdfhs
kdjhfjdshfkjdshfkdshfkshjdhfskjhfksdhfksjhfkjsdhfkjsdhfk
jshfshfshfdshdfshdkjfhsafkjsahdfksahdf" />
</LinearLayout>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mongodb full text search and json objects
I am running mongodb v2.4.5. I have a document with the following fields:
{ "_id" : ObjectId("<someid>"), temp:"python", github_repo_languages" : { "python" : 17, "java" : 984 } }
If I run the query:
db.users.runCommand( "text", { search: "java" })
{
"queryDebugString" : "java||||||",
"language" : "english",
"results" : [ ],
"stats" : {
"nscanned" : 0,
"nscannedObjects" : 0,
"n" : 0,
"nfound" : 0,
"timeMicros" : 97
},
"ok" : 1
}
mongodb doesn't find any documents.
Here are my indexes:
> db.users.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "workingon.users",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"ns" : "workingon.users",
"name" : "users_text_index",
"weights" : {
"$**" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 1
}
]
Other searches work for simple text fields. Is the issue the complex json object? Are there plans to add complex json objects?
A:
According to the documentation ( http://docs.mongodb.org/manual/core/text-search/ ) the text index should be on the field or fields whose value is a string or an array of string elements. So as you pointed out, the json field will not work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Code prints time in millisec
This is my code and I am getting a huge output. My code should output the time in milliseconds. Am I doing something wrong?
Random rand = new Random();
int num = rand.nextInt(100);
static long linear = System.currentTimeMillis();
//Linear Search in Unsorted array
private static int linearSearch(int list[],int key)
{
//finds an element in a list
for(int i=0;i<list.length;i++)
{
//if element is found, element is then returned
if(list[i]==key)
return i;
}
//if element is not found, -1 is returned
return -1;
}
System.out.println("Linear Search Time: " + linear);
A:
Below is some code that will run, and print out the time it took for your function to run. The problem you are having is that you are asking for the system time, which is some massive number, because it is how long the computer has been running. To get the time your function took to run we simply ask for the time before we run let's call in t1. Then we run the function. After then function has completed running we ask for the time again let's call it t2. Then we take t2 - t1 this difference is the time it took your function to run, and the time for the calculation to be performed (minimal). Also note that in my example the time outputted will be zero, as the array is so small, and the calculation is so fast.
import java.util.Random;
public class App {
Random rand = new Random(); //stays same
int num = rand.nextInt(100); //stays same
static long linear = 0;//more optimal to move where initial time is set (t1)
//main where things are run ;)
public static void main(String[] args) {
//could be placed outside in the class
int[] array = {1,2,3,4,5};//some array of numbers
int key = 5; //a key
linear = System.currentTimeMillis();//t1 set
linearSearch(array, 5);//calling of your search function
linear = System.currentTimeMillis() - linear; //obtaining the difference between the time, and t2 = System.currentTimeMillis()
//the function started and when it finished
System.out.println("Linear Search Time: " + linear);//printing out the difference, which is the time taken
//also note that the number will likely be zero, as this function will run extremely fast for most arrays.
}
//your function
//Linear Search in Unsorted array
private static int linearSearch(int list[],int key)
{
//finds an element in a list
for(int i=0;i<list.length;i++)
{
//if element is found, element is then returned
if(list[i]==key)
return i;
}
//if element is not found, -1 is returned
return -1;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Simple filesize output terminal
Is there a simple command in the terminal (or a command with a usage that I know not) that would output filesize in bytes of a file given a filename parameter?
A:
You can use the stat command
stat -c '%s' filename
See man stat for details and other options
Or, with du
du -b filename
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OData filter on computed value
I have a Person with a name, split into FirstName and LastName. I need to filter by FullName which is First- and Last-Name combined.
How will I be able to filter that?
~/odata/people?$filter=...
Keep in mind I need to be able to filter a person named FirstName=Foo, LastName=Bar by the following:
foo bar
foo
bar
oo ba
If this isn't possible directly in the query. Then I've been looking at DelegateDecompiler, though I haven't been able to make it work just yet. So also looking for advice on that approach is a good choice.
A:
http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part1-protocol.html check build in functions, contains(concat(concat(FirstName,' '), LastName), 'foo bar')
:)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Negative Lookahead RegEx
Why is this not working? Trying to do a negative lookahead. I am trying to pull the numbers from the bins, except in quarantine bin and inspection bin. When I do the code with the ^ in the front is matches all numbers in parenthesis. When I remove the ^ it matches nothing.
Also can you use the "or operator |" inside the negative lookahead? I want to have ^(?!Quarantine_Bin|Inspection_Bin)
I also tried to specifically negate [^Quarantine_Bin] and it is still matching.
^(?!Quarantine_Bin)\([0-9]+\)
Data
Quarantine(2),Other_Bin(2),Quarantine_Bin(2),Quarantine_Bin(2),
Quarantine_Bin(5),Inspection_Bin(3),Regular_Bin(5),other(2)
A:
It's a negative lookbehind
use warnings;
use feature 'say';
my @strings = (
"Quarantine_Bin(5),Inspection_Bin(3),Regular_Bin(5),other(2)",
"Quarantine(2),Other_Bin(2),Quarantine_Bin(2),Quarantine_Bin(2),"
);
for (@strings) {
my @m = $_ =~ /(?<!\b(?:Quarantine|Inspection)_Bin)\(\d+\)/g;
say "@m";
}
The ^ anchor doesn't do what you want here, use \b to specify a word boundary.
This includes the parenthesis with numbers, returning lines (5) (2) and (2) (2).
If you'd rather omit them, add capturing parethesis around numbers
/(?<! \b(?: Quarantine|Inspection)_Bin ) \( (\d+) \)/xg;
or pull the opening paren inside the lookbehind (so it is not consumed) and leave out the closing one
/(?<! \b(?: Quarantine|Inspection)_Bin \( ) \d+/xg;
These return lines 5 2 and 2 2, no parens.
The /x modifier allows spaces inside for readability.
A:
You should be using a negative lookbehind as:
(?<!\b(Quarantine|Inspection)_Bin)\([0-9]+\)
RegEx Demo
(?<!\b(Quarantine|Inspection)_Bin) is a negative lookbehind that asserts failure if there is Quarantine_Bin or Inspection_Bin before our match.
\b is for word boundary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Objective-C passing parameters in void method
How would I go about passing parameters when calling a void method? I understand that you can do something like this:
-(void)viewDidLoad {
[self callMethod];
}
-(void)callMethod {
//stuff here
}
But how would I pass a parameter, such as an NSString, to the callMethod method?
A:
Here is an example with an integer parameter.
-(void)viewDidLoad {
[self callMethodWithCount:10];
}
-(void)callMethodWithCount:(NSInteger)count {
//stuff here
}
In objective-c the parameters are included within the method name. You can add multiple parameters like this:
-(void)viewDidLoad {
[self callMethodWithCount:10 animated:YES];
}
-(void)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
//stuff here
}
It seems you may be misunderstanding what the void in the beginning of the method means. It's the return value. For a void method, nothing is returned from calling the method. If you wanted to return a value from your method you would do it like this:
-(void)viewDidLoad {
int myInt = [self callMethodWithCount:10 animated:YES];
}
-(int)callMethodWithCount:(NSInteger)count animated:(BOOL)animate{
return 10;
}
You define your method to return an int (in this example it always returns 10.) Then you can set an integer to the value returned by calling the method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
merge array as object into another array
I have 2 array in php (I use echo json_encode()) to show u the output :
echo json_encode($arr);
[{'a':1}]
and echo json_encode($arr2);
[{'something':1},{'something2':2}]
When I do $arr[] = $arr2; it output this
[{'a':1}[{'something':1},{'something2':2}]]
what I want is
[{'a':1},{'something':1},{'something2':2}]
A:
Just use array_merge:
$res = array_merge($arr, $arr2);
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.