text:
Q: Ad Provider integration with PhoneGap App How do I integrate ad providers with a PhoneGap App (for windows phone)?

A: I would think there are a couple of answers to this. One is to edit the XAML page, add the normal silverlight control to the page. This would require you to fiddle with the provided xaml from phonegap. This would give you access to the MS Ad Control and Google's Ad control for .net. At the end of the day, PhoneGap is just a silverlight page, with a browser control in it. So you can still edit that page, but you have to make sure you don't screw up the PhoneGap libraries and page.
The other solution is to find an html based ad control. Although this might not be possible with your ad provider.


text:
Q: Copying column from one database to another I have 2 databases. One called 'main' and the other 'AM.'
main and AM have the same table structure. They both have a table called 'values'. Both tables have the same number of rows and columns.
I am trying to perform the following command
sqlite> insert into main.values(name) select name from AM.values;

but I obtain the following error:
Error: NOT NULL constraint failed: values.guid

Name and guid are names of columns in both tables. Can anyone advise on why this error is occurring? My insert command does not involve the guid column, and only involves the name column, but error points to an issue with the guid column.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "ERROR: Could not build wheels for pyq which use PEP 517 and cannot be installed directly" when installing PyQ? I'm wondering if anyone has encountered any similar errors when attempting to install PyQ for Windows? I've tried both Anaconda and the Windows prompt and there doesn't appear to be any difference in the errors produced.
Any help is much appreciated!
I've included the link to a screenshot here: https://i.stack.imgur.com/Vofnr.png

A: You may try install VS code for C++ before installing PyQ, or you can install PyQ on Linux if possible.

A: The issue was you need to have VS 2017 instead of the most recent version as PyQ for Windows isn't up to date with this regard (at the time of this writing, anyway).

A: Try this
pip install --upgrade setuptools


text:
Q: _cmd in Swift for selector use I'm trying to write the following ObjC code in Swift 3:
- (void)scrollViewScroll:(UIScrollView*)scrollView {
    // some code
    if ([_userDelegate respondsToSelector:_cmd]) {
        [_userDelegate scrollViewDidEndDecelerating:scrollView];
    }
}

But do not know what to replace _cmd with. I'm trying function, but it doesn't work:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    // some code
    if (userDelegate?.responds(to: #function))! {
        userDelegate?.scrollViewDidScroll!(scrollView)
    }
}

using #selector(scrollViewDidScroll(_:)) works, but is there a way to keep it generic?
Edit: Possible duplicate answer is about getting function name which isn't what I'm asking above

A: Swift doesn't have selectors.
Objective-C sends messages to objects while Swift calls functions. So checking if object can respond to selector is part of Objective-C and NSObject.
Swift protocol functions are required by default. Swift compiler doesn't let you skip those function implementations. But you can make them optional, and you have to check, if these functions implemented before calling.
In this case, just call function with question mark at the end, like this
if let returnValue = userDelegate?.theOptionalFunction?(arguments) {
    // you got value
} else {
    // delegate returned nil or delegate function isn't implemented
}

Source: The Swift Programming Language

An optional protocol requirement can be called with optional chaining, to account for the possibility that the requirement was not implemented by a type that conforms to the protocol. You check for an implementation of an optional method by writing a question mark after the name of the method when it is called, such as someOptionalMethod?(someArgument).


text:
Q: How can use custom regex in c#? class Program
{
    private static void showMatch(string text, string expr)
    {
        Console.WriteLine("The Expression: " + expr);
        MatchCollection mc = Regex.Matches(text, expr);

        foreach (Match m in mc)
        {
            Console.WriteLine(m);
        }
    }
    static void Main(string[] args)
    {
        string str = "A Thousand Splendid Suns";

        string pattern = @"[>][@\/" - &',.\w+ -]+[<]";
        Console.WriteLine("Matching words that start with 'S': ");
        showMatch(str, pattern);
        Console.ReadKey();
    }
}

A:    string pattern = @"[>][@\/"" - &',.\w+ -]+[<]";

double quote will escape for you. this line works now


text:
Q: Упростить выражение, чтобы было меньше символов x[i] + x[i + 1] + x[i + 2] > m ? m = x[i] + x[i + 1] + x[i + 2] : 0;

Как можно упростить, чтобы было меньше символов?

A: y = x[i] + x[i + 1] + x[i + 2];
y > m ? m = y : 0;

A: Я думаю, вы ищите это:
#define M(a, b) (a)>(b) ? (a) : (b)
m = M(x[i] + x[i+1] + x[i+2], m);

A: Я думаю, что речь идёт о кол-ве символов. Тогда лучше всего сделать так:
m = max(x[i] + x[i + 1] + x[i + 2], m)

Это самый короткий вариант.


text:
Q: How to represent values that can be of more that one type in Apache Thrift? Is it possible at all to use Thrift to represent something like the Java type Map where the value in the Map is known to be e.g. either String or Integer?
In other words, is there any way to represent values where the actual base type is only known at run time but guaranteed to be one of a set of types which is known in advance.
Is there an alternative for high performance serialisation which can do this?
I am currently using JSON with a manual implementation of the necessary code in Java and Python, but it would be nice to solve this in a more orderly fashion.

A: Thrift requires you to specify a type. That type can be a structured type like a struct or a union, however it has to be a type:
union Anything {
  1: string s
  2: i64    i
  3: double d
}

service foo {
   Anything  bar(1: Anything anyArg)
}

However, if you plan to use JSON and just wrap that JSON data into a Thrift message somehow, then maybe you want to go with string. On the other hand, if you only exchange such JSON strings like in
service foo {
   string  bar(1: string json)
}

then to some extent this would raise the question whether Thrift is the right tool for the job. It may still be, but you are responsible for the JSON serialization/deserialization yourself ...


text:
Q: How can I take the "printed" file path in Python, and use it in a Windows command line? I am making a GUI where it allows you to:

*

*Choose a file (user would click the first button, and a file browser pops up where user can navigate to desired file)
Once selected, the "file path" of the file should be the output

*Execute a batch file in the Windows command window (user would click second button, where the command window opens and uses the output from step 1)
The input in the command window would be {MyFile.bat "the file path from step 1"} for example.

Where I am now?
I am able to output the file path but I can not get the file path into the Windows command prompt window, because instead of inputting the actual file path, it inputs the name of the output, rather than the actual output.
Example:
output name = x
after step 1, x should be = C\file\path\I\want.plz

after pressing the second button: The Windows command prompt opens and the line in the window writes: MyFile.bat "x" rather than MyFile.bat "C\file\path\I\want.plz"

def Button_Open_File(self):
    import tkinter as tk
    from tkinter import filedialog

    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename()
    file_dir_name = print(**file_path**)

def Button_RUN_BATCH_FILE_ON_FILE_IN_CMD(self):
    import subprocess
    p1 = subprocess.check_call(**r'start cmd /c MyFile.bat "file_path"'**, shell=True, cwd="c:/Users/kimk4/Documents/")
    print('done')

I highlighted my problem areas with **, so as you can see, when I run this, I am able to print a file path in the Oython shell, but I am not able to get this batch file to work because instead of writing the actual path (in the window) to the file, it literally writes file_path rather than c\file\location\that\user\navigates\to.thanks in the Windows command prompt window.


text:
Q: Built in way to convert from screen coordinates to image coordinates? I have an app where users can scale and position images in a number of ways.  They can drag an entire layer of images around, scale that layer, drag around individual images inside the layer, and scale those individual images.
For some unrelated functionality, I need to generate the image coordinates that a user is pointing to on a given image (ie (0,0) for the top left & (width,height) for the bottom right), independent of how much it has been moved around and scaled.  Is there a built in method for tranforming an absolute mouse position to it's relative position on an image (and vice versa) that takes into account any scaling/panning?  I have started building my own methods for this tranformation but before I got too deep I wanted to see if it was already built in somewhere that I'm not seeing.

A: Konva doesn't have such methods yet. You have to implement them manually.
You can subscribe to this related issue: https://github.com/konvajs/konva/issues/303


text:
Q: Using .includes and this is popping up- Cannot read property 'includes' of undefined This is my code and every time I try and run it when it gets to .includes it always tells me Cannot read property 'includes' of undefined
function search(keywords, list) {
  for (var i = 0; i < 1000; i++) {
   if ((list[i]).title.includes(keywords)) {
     appendItem(outputList, (parkList[i] + " - " + acresList[i] + " acres ") + locationList[i] + " - ");


text:
Q: How do I get the value from  in javascript? What should I do to get uname and pword the value from the username and password input box? i tried to use document.getelementbyid().value but it doesn't seem to work

<!DOCTYPE html>

    LOGIN

<form id="forme" autocomplete="off">

  Username:<input type="text" id="take" name="Username">

 Password:
  <input type="password" id="pass" name="Password">

  <input type="submit" onsubmit="javascript:checkid()">

</form>

A: You're really close, just a few things:

*

*the  tag is something special, you can't put a p in it. It all needs to go into the body tag.

*the onsubmit event should be on the form, not on the button

*a form by default does a network request. To prevent the page reloading you have to do a preventDefault.
Like this:

function checkid(event) {
  event.preventDefault();
  uname = document.getElementById("take").value
  pword = document.getElementById("pass").value

  if (uname == "abc" && pword == "123") {
    document.getElementById("paragraph").innerText = "right"

  } else {
    document.getElementById("paragraph").innerText = "wrong"
  }

}

  LOGIN

<form id="forme" autocomplete="off" onsubmit="javascript:checkid(event)">

  Username:<input type="text" id="take" name="Username">

 Password:
  <input type="password" id="pass" name="Password">

  <input type="submit">

</form>

A: *

*The onsubmit belongs on the form tag and not on the submit button

*There is no need for javascript: labels in event handlers (or anywhere else for that matter)

*HTML tags do not belong in head tags

*Please do be aware that having a test for userid and password in plain view is no security at all

Recommended method (apart from the plain text password)

<!doctype html>

  <meta charset="UTF-8">
  <title>Form example</title>

  LOGIN

<form id="forme" autocomplete="off">
  Username:<input type="text" id="take" name="Username">

 Password:
  <input type="password" id="pass" name="Password">

  <input type="submit">
</form>

A: EASY:

function getValue() {
  $('form').on('submit', function(event) {
    event.preventDefault();
    $(this).serialize();

    document.getElementById('result').value = `You entered: ${document.getElementById('text-input').value}`;
  });
}
form .form-group {
  margin-bottom: 10px;
}

input[type=text] {
  height: 25px;
}

button[type=submit] {
  height: 30px;
}

input#text-input {
  width: 200px;
}
<form>

    <input type="text" placeholder="Enter your text here..." id="text-input" name="text-input" required>
    <button type="submit" onclick="getValue()">
      Submit
    </button>

    <output id="result" name="result" for="text-input"></output>

</form>


text:
Q: How to make Resharper resolve path for CustomBinding MarkupExtension I want to create some extended Binding-Markup-Extension, which behaves just like a normal WPF-Binding but does some things more (use different defaults, maybe add some behavior, etc.).
Code looks like this:
public class CustomBindingExtension : Binding
{
  .. some extra properties and maybe overrides ...
}

It all works fine including XAML-intellisense, except I just can't make Resharper resolve my Binding-Path correctly.
I.e.: using this code I can [Strg]+Click on 'CurrentText' and Resharper lets vs2010 navigate to the code defining the CurrentText-Property.
<UserControl x:Name="uc" ...>
  <TextBox Text="{Binding ViewModel.CurrentText, ElementName=uc}" />
</UserControl>

But using my binding, which works correctly at runtime, I just get a Tooltip when hovering 'CurrentText' telling me it is some 'MS.Internal.Design.Metadata.ReflectionTypeNode', and no navigation via [Strg]+Click.
<UserControl x:Name="uc" ...>
  <TextBox Text="{util:CustomBinding ViewModel.CurrentText, ElementName=uc}" />
</UserControl>

I tried the following things:

*Derive from Binding

*Derive from BindingDecoratorBase

*Leave out the 'Extension' suffix for my CustomBinding-class

*put the Markup-Extension in a separate assembly

*Use ConstructorArgumentAttribute

*Property of type string and type PropertyPath for the Path-Property
I also looked at the original classes Binding and BindingBase, but could not find any more difference to my code.
Any ideas what should help here?
Or is this just a special treatment of the Binding-MarkupExtension which I can in no way get for my own MarkupExtensions?
Update 16.03.2011: Might also be bug or deficiency of Resharper, Jetbrains is investigating the issue: http://youtrack.jetbrains.net/issue/RSRP-230607
Update 10.12.2013: Meanwhile, the feature seems to be working (with R# 7.1.3, maybe also earlier versions), I actually use the approach with the BindingDecoratorBase and I like it a lot.
Maybe it only works, if your MarkupExtension ends on 'Binding', but mine does, so I am happy.

A: Actually it's not possible in current versions of R# and, unfortunately, still be missing feature of upcoming R# 6.1 release.
This feature requires a lot of infrastructure changes, but it's on our list and definitely will be implemented in R# 7. Seems like [CustomBindingMarkup] and [BindingPath] (for path constructor parameter and the Path property) attributes will be introduced.
We really apologize for any inconvenience.

A: You should access your custom Markup-Extension, using the correct namespace:
<UserControl x:Name="uc" ...
xmlns:ext="clr-ns:YourProjectNamespace">
  <TextBox Text="{ext:CustomBinding ViewModel.CurrentText, ElementName=uc}" />
</UserControl>

Here is a nice article about creating custom Markup-Extensions.

A: One way to fool R# is to name it Binding:
public class Binding : MarkupExtension
{
    public Binding()
    {
    }

    public Binding(string path)
    {
        Path = path;
    }

    public string Path { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return 5;
    }
}

Then it works the same as standard binding with R#
<TextBlock Text="{custom:Binding SomeProp}" />


text:
Q: Change div background on an alert button click I am currently trying to set the background of a div on a jquery ui alert dialog button click event. The user clicks a button and that brings up the dialog where the user chooses an image from a select option. When they hit the Choose Background( The button that is part of  a jqueryUI dialog alert). It should change the div `class="middle-side"" background. I have done this before but the button is part of the html element. I have done this regular buttons but not part of dialog. How can I change the background of the div on alert button click? JSFIDDLE - P.S. Issue with jsfiddle showing images from an external source
jQuery:
$('#backgroundPick').click(function (e) {
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: true,
        buttons: {
            "Delete all items": function() {
                $( this ).dialog( "close" );
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        }
    });
});

HTML

<button id="backgroundPick">Choose Background</button>

    <select class="image-picker show-labels show-html">
        <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
        <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
        <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
        <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
    </select>

A: First of all, I would remove the creation of the dialog from the click function, by initializing with autoOpen: false.  This makes your code cleaner and also doesn't leave your dialog code in the DOM tree until the user clicks "Choose background".
Second, I assume you want the first button to be "Change background", not "Delete all items".
So, to answer your question, in your callback for the button, grab the data for img-src in the :selected option.  Then set the background image of the .middle-side div:
$("#dialog-confirm").dialog({
    resizable: false,
    height: 230,
    modal: true,
    autoOpen: false, // Initialize the dialog, but don't open it
    buttons: {
        "Choose background": function () {
            $(this).dialog("close");
            var img = $('#dialog-confirm select option:selected').data('img-src');
            $('.middle-side').css('background-image', 'url("'+img+'")');
        },
        Cancel: function () {
            $(this).dialog("close");
        }
    }
});

$('#backgroundPick').click(function() {
    $("#dialog-confirm").dialog( "open" ); // Open the dialog on click
});

Demo: http://jsfiddle.net/jtbowden/ohdbu94y/

A: just add an even listener to your <select>:
$(document).on("change", ".image-picker", function(){
    $(".middle-side").css("background", $(this).data("img-src"));
});

edit: as i mentioned in my comment, your question doesn't really make sense. you want to change the background as soon as someone hits the "choose background" button. but this button opens the dialog which lets you choose an image. you can't change the background before you even know what the user is going to select.


text:
Q: V-img in Vue (Vuetify) don't realised in browser contex menu as image I use Vuetify framework and create v-img element. When I open contex menu in browser there isn't ordinary image options (Save as, Open image, Copy image). I check it on Firefox and Chrome. How can I fix it? I need to add abilities to save images from page.
Vue 2.6.12, Vuetify 2.3.10
My code snippet:
<template>
   <v-img
      :src="imageSrc"
      :alt="imageAlt"
      :width="imageWidth"
      :min-height="imageMinHeight"
      contain
   >
     <template v-slot:placeholder>
       <v-row
         class="fill-height ma-0"
         align="center"
         justify="center"
       >
         <v-progress-circular
           indeterminate
           color="blue-grey lighten-3"
         ></v-progress-circular>
       </v-row>
     </template>
   </v-img>
</template>

The src of image is an url.

A: I resolve my issue with default slot of v-img. I put <img> with zero opacity to that slot. So it detected as ordinary image by browser.
My example:
<template>
   <v-img
      :src="imageSrc"
      :alt="imageAlt"
      :width="imageWidth"
      :height="imageHeight"
      contain
   >
     <template v-slot:default>
       <div class="d-flex flex-row">
         <v-spacer/>
           <img
             :src="imageSrc"
             :height="imageHeight"
             align="center"
             class="opacity-0"
           >
          <v-spacer/>
        </div>
     </template>

     <template v-slot:placeholder>
       <v-row
         class="fill-height ma-0"
         align="center"
         justify="center"
       >
         <v-progress-circular
           indeterminate
           color="blue-grey lighten-3"
         ></v-progress-circular>
       </v-row>
     </template>
   </v-img>
</template>

css:
.opacity-0 {
  opacity: 0 !important;
}


text:
Q: Saving data from SDSS query in Python I got the data from SDSS by the following query
query = """SELECT TOP 20000
        p.psfMag_u, p.psfMag_g, p.psfMag_r, p.psfMag_i, p.psfMag_z, s.class
        FROM PhotoObjAll AS p JOIN specObjAll s ON s.bestobjid = p.objid
        WHERE p.mode = 1 AND s.sciencePrimary = 1 AND p.clean = 1
        ORDER BY s.specobjid ASC
        """
data = SDSS.query_sql(query).to_pandas()

psfMag_g  psfMag_u  psfMag_r  psfMag_i  psfMag_z  class
19.08541  17.41787  16.59118  16.03507  15.68560  GALAXY

There are 20000 data.
I want to save in csv format. How to save the data?


text:
Q: Error 438 "object doesn't support this property or method" when i run this simple code I want to go to each worksheet in a workbook called "ETAT.xlsx" that is already opened and set the value of range("a14") to 150, but when I run this code I get a

runtime error 438 object doesn't support this property or method

What could be the problem please?
Sub testo()
    Dim ws As Worksheet
    For Each ws In Worksheets
         Workbooks("ETAT.xlsx").ws.Range("a14").Value = 150
    Next ws
End Sub

A: You need to refer to the workbook in your loop, otherwise by default it will refer to the workbook which is active when the code is executed. Think this should work.
Sub testo()

Dim ws As Worksheet

For Each ws In Workbooks("ETAT.xlsx").Worksheets
    ws.Range("a14").Value = 150
Next ws

End Sub


text:
Q: Invoke Jenkins Restapi call from from webapi C# I have a Jenkins job which takes 2 file parameters and a string. I am able to invoke them from curl however I want to know how to invoke from the c# backend?

A: you can include nuget package jenkinsnet in your code.
DOcumentation & examples https://github.com/null511/Jenkins.NET
or you can use the jenkins rest api directly
https://www.automatetheplanet.com/jenkins-csharp-api-triggering-builds/


text:
Q: self.navigationController popToRootViewControllerAnimated:YES do not pop back to the root I have this line of code to pop back to the root menu when clicking the "back" button on the top bar:
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

I have had no problem with this until now, i still use IOS 5.1 as target.
As i run this code now (XCODE 5) i get the following message:
Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.

...and it only seems to pop the text in the top bar back to the root (Menu) while the display only pop's back one level. As this has always worked i am a bit puzzled and would like some advice how to solve this. The View Controller were i execute this code is a normal ViewController.
I use [self performSegueWithIdentifier:@"xxxxx" sender:self];to push the ViewControllers.
Just for testing i used this code:
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

...and it did pop the VC and then directly pop'ed back to the rootVC without the messages???
Here is the structure, it is from the green VC i have problem going back to the first VC. Again, i have not had this problem prior to xcode5:

A: Ok I just noticed you are trying to pop to root, when the user pushes back, but here is what is happening:
The OS is trying to push to the previous viewController with an animation and in the same moment, you are initiating a second transition and ask it to pop to the root view controller.
The easiest approach would to replace the system's back button with a custom button that will use your own IBAction and you will then pop to the rootViewController:
First hide the back button:
self.navigationItem.hidesBackButton = YES;

and then create your own custom back Button:
UIBarButtonItem *backBtn =[[UIBarButtonItem alloc]initWithTitle:@"back" style:UIBarButtonItemStyleDone target:self action:@selector(popToRoot:)];
self.navigationItem.leftBarButtonItem=backBtn;

Finally you pop to the RootViewController:
- (IBAction)popToRoot:(UIBarButtonItem*)sender {
   [self.navigationController popToRootViewControllerAnimated:YES];
}

Remember to remove the [self.navigationController popToRootViewControllerAnimated:YES]; from the ViewWillDisappear delegate.

A: try this code it will help you..
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];


text:
Q: Accessing the light DOM included by means of a content tag in Polymer Context:
I am working with polymer (0.2.4) on Maverics MacOX (10.9.2) & Chrome agent (34.0.1847.131) building up web components. Particularly, I am trying to partially enrich two components (foo and bar) included in other template by means of a content tag. The enrichment consists of adding new attributes for using them within their respective inner templates (lines (3) and (4)). I am not sure whether this approach will work properly which is what I need. But it gets me to the following problem.
Problem:
I am trying to access from JS the light-DOM nodes included in a template by a content tag. Essentially my intention can be depicted in the following snippet. I need to access nodes foo and bar in lines (1) and (2):
<polymer-element name="wc-tag">
  <template>

       <content select="[role='rA']"></content>
       <content select="[role='rB']"></content>

  </template>

</polymer-element>

 <wc-tag>
    <wc-foo role="rA">Foo</wc-foo>
    <wc-bar role="rB">Bar</wc-bar>
 </wc-tag>

Nevertheless, a null value is obtained in both rA and rB. I have confirmed that when code is evaluated, the content tags have not been resolved yet (content are the two only children with
).
Question:
Does anybody knows how/when could/should I access foo and bar?

A: Here's a jsbin example of how to do this using <content> elements and the getDistributedNodes method.
<polymer-element name="x-foo">
  <template>

Hello from x-foo

    <content id="content" select='[role="rA"]'></content>
  </template>

</polymer-element>

<x-foo>

rA element

</x-foo>

A: Tricky, I haven't done this with Polymer yet so there's a bit of speculation here. Let me know if this works (and post a jsbin if it doesn't :)
Here's my understanding. In the shadow dom, the <content> nodes don't exactly have the <wc-foo/bar> elements as children. Those are still part of the light dom, they're just effectively copied over. So because you're querying for children of this.$.container in the shadow dom for elements with role="rA" you won't find them because they're in the light dom. Two options: you could give the <content> nodes identifying attributes so you can select them and then call getDistributedElements() on them; or you could do this.querySelector rather than this.$.container.querySelector.
Related reading: How to style distributed nodes


text:
Q: Trimming my panel dataset - filtering out observations meeting criterion if preceding ID meets the complementary criterion I am working with a dataset that includes 118,979 observations over 9 wide variables in Stata 16.0. The most prominent variable is whether a company-observation over multiple dates reports either "GPS" or "EPS". These companies can report both a "GPS" observation in a datapoint, as well as an "EPS" observation in the following datapoint. Please refer to the data overview below for further visualisation.
Datasample:
clear
input str8 cusip8 str16 cname str4 measure double actual long anndats_act float(fyear tanalyst meanforcast UE)
"87482X10" "TALMER BANCORP"   "EPS"   1.21 20118 2014  29   .8686207     .3930131
"87482X10" "TALMER BANCORP"   "GPS"   1.02 20479 2015  34   .8576471     .1893004

I need to drop the GPS observations (over multiple dates) once an identifier (being cusip8 in the table above) has reported an EPS over multiple dates. That is, if a company has reported GPS as well as EPS in e.g. January 1st, 2010, I want to drop the GPS observation such that the EPS is kept.
If a company only reports a GPS, and does not report an EPS during a given date, I want to keep the GPS observation in my dataset.

A: The following works for me (adjust your variable names as required):
. clear

. input str10(company_id measure) month day year

     company_id measure month day year
  1. "Company A" "EPS" 1 1 2010
  2. "Company A" "GPS" 1 1 2010
  3. "Company A" "GPS" 1 1 2010
  4. "Company A" "GPS" 1 2 2010
  5. "Company B" "EPS" 1 2 2010
  6. "Company B" "GPS" 1 1 2010
  7. "Company C" "GPS" 1 4 2010
  8. "Company C" "EPS" 1 4 2010
  9. end

.
. gen date = mdy(month,day,year)

. format date %d

. drop month day year

.
. sort company_id date measure

.
. gen both = 0

. by company_id date: replace both = 1 if measure[1] == "EPS" & measure[2] == "GPS"
(5 real changes made)

.
. list, sepby(company_id)

     +----------------------------------------+
     | company~d   measure        date   both |
     |----------------------------------------|
  1. | Company A       EPS   01jan2010      1 |
  2. | Company A       GPS   01jan2010      1 |
  3. | Company A       GPS   01jan2010      1 |
  4. | Company A       GPS   02jan2010      0 |
     |----------------------------------------|
  5. | Company B       GPS   01jan2010      0 |
  6. | Company B       EPS   02jan2010      0 |
     |----------------------------------------|
  7. | Company C       EPS   04jan2010      1 |
  8. | Company C       GPS   04jan2010      1 |
     +----------------------------------------+

.
. drop if measure == "GPS" & both == 1
(3 observations deleted)

.
. list, sepby(company_id)

     +----------------------------------------+
     | company~d   measure        date   both |
     |----------------------------------------|
  1. | Company A       EPS   01jan2010      1 |
  2. | Company A       GPS   02jan2010      0 |
     |----------------------------------------|
  3. | Company B       GPS   01jan2010      0 |
  4. | Company B       EPS   02jan2010      0 |
     |----------------------------------------|
  5. | Company C       EPS   04jan2010      1 |
     +----------------------------------------+


text:
Q: Input string was not in a correct format exception for Math.Round() in c# I am getting exception like Input string was not in a correct format for below equation for some big values say for example 3225036
decimal eutra = 3225036;

decimal result =
  Convert.ToDecimal(Math.Round((eutra / 256), 0).ToString() +
  Math.Ceiling((((eutra / 256) - Math.Round((eutra / 256), 0)) * 256)));

Actually i was trying to convert an excel equation in to c# which is
CONCATENATE(ROUND(eutra /256,0),ROUNDUP(((eutra /256)-ROUND(eutra /256,0))*256,0))

A: The immediate problem is that Math.Ceiling((((eutra / 256) - Math.Round((eutra / 256), 0)) * 256)) returns "-52" when eutra = 3225036.  Since you're turning the other result into a string first, these are combined as a string to become "12598-52", which isn't a parseable decimal.
It's possible that you want to call Math.Floor instead of Math.Round on the third division of eutra, this should avoid the possibility of a negative number but I'm not sure what you actually want the end result to be.

A: The problem is that on line 4 in your code you are using '.ToString()' on a decimal value which converts the decimal value to a string and then trying to add the string to a second value which is a decimal value this, in turn, gives you a string which is then passed to 'Math.Round()' which requires a decimal value but instead now you're giving it a string value.
See the corrected code below:
decimal eutra = 3225036;

decimal result =
  Convert.ToDecimal(Math.Round((eutra / 256), 0) +
  Math.Ceiling((((eutra / 256) - Math.Round((eutra / 256), 0)) * 256)));


text:
Q: Idiom for two people having two drastically different appraisals of an event What's an idiom for "two people have two drastically different appraisals of an event they were a part of"?
For example, two people on a date. One thinks it was great and hopes for another, and the other thinks it was terrible.

A: This sounds like an example of the Rashomon effect. From Wikipedia (footnotes omitted):

The Rashomon effect occurs when an event is given contradictory interpretations by the individuals involved. The effect is named after Akira Kurosawa's 1950 film Rashomon, in which a murder is described in four contradictory ways by four witnesses. The term addresses the motives, mechanism and occurrences of the reporting on the circumstance and addresses contested interpretations of events, the existence of disagreements regarding the evidence of events and subjectivity versus objectivity in human perception, memory and reporting.

So for example if A and B go on a date, A might remember that the food was terrific and they were incredibly witty, but then B got increasingly tipsy and there was a weird digression into French art criticism that tanked the whole date; while B remembers that the food violated their dietary restrictions and A kept telling total groaners, but the wine was terrific and there was a fascinating conversation about French art criticism that really made them want to see B again. And the waiter might primarily remember that A and B totally stiffed him on the tip in spite of ordering three appetizers, two desserts, and three bottles of wine.
To address the request for an idiom: The term Rashomon, applied as an adjective to various nouns, has come to be an idiom1 for this kind of encounter. For example (bolding added; other emphasis original):

This turned out to be what I call a Rashomon date, where the perspectives on how it went differ wildly.
  —Kashmir Hill, "My Weird Hobby: Matchmaking Lawyers", Forbes, February 14, 2011

Watergate's Rashomon moment: Fans of All the President's Men . . . may have wondered why the anonymous source then known as Deep Throat didn't simply reveal everything he knew. In telling the story from the perspective of Deep Throat . . . writer-director Peter Landesman helps us understand the G-man's justified paranoia. The film is a thriller, but the current occupant of the White House may find it to be a horror film . . . .
  —Simon Houpt, "The TIFF movies we can't wait to see, from a tiny Matt Damon to two tennis tales", The Globe and Mail, September 8, 2017 (describing the film Mark Felt: The Man Who Brought Down the White House)

Let's face it: We live in a Rashomon reality in which every event is instantly captured from a dozen angles and given at least as many interpretations . . . .
  —Antonio García Martínez, "Journalism isn't dying. It's returning to its roots", Wired, 02.10.19

Perhaps unsurprisingly, the use has picked up quite a bit in US news reports in the past few years.

1 I am taking "idiom" here to mean "an expression whose meaning is not predictable from the usual meanings of its constituent elements" (Dictionary.com), since the usual meaning of something like "Rashomon encounter" would be "an encounter with Rashomon".

A: one man's meat is another man's poison (TFD)
That is, there is no accounting for tastes.

What one person may consider good, enjoyable, or beneficial may be disliked by someone else.
A: "I really don't understand the appeal of the Harry Potter series. There are so many better books out there!"
  B: "Eh, one man's meat is another man's poison."
  (Farlex Partner Idioms Dictionary © Farlex 2017)

See also:

You may not like something that I like. The phrase, which was first written by the Roman poet Lucretius, was appropriated to refer to any situation where two people disagree over something. The 20th-century literary wit George S. Kauffman's most celebrated pun was "One man's Mede is another man's Persian."
  (Endangered Phrases by Steven D. Price Copyright © 2011 by Steven D. Price)

A: I couldn't find anything specific to an 'event' experience, but perhaps you could use:
Different sides of the same coin
Two things that appear different, but have a connection/are related

A: They had a difference of opinion(s). TFD

The term is often used to frame such a disagreement as
  a polite one in which people simply differ in their views.


text:
Q: How to hide side navigation bar in angular 2 material I am trying to create responsive side navigation bar using angular 2 material. My side nav is working. It is always opened navigation bar.How do i hide it when reducing the screen size.
This is my code:
<md-sidenav-container style="width: 100%" onloadstart="false">

    <md-toolbar color="primary">
      <md-icon>menu</md-icon>
      Profile

        <button md-icon-button [mdMenuTriggerFor]="menu"><md-icon>more_vert</md-icon></button>
        <md-menu #menu="mdMenu">
          <button md-menu-item><md-icon>swap_horiz</md-icon>toggle</button>
          <button md-menu-item disabled><md-icon>person</md-icon>profile</button>
          <button md-menu-item><md-icon>exit_to_app</md-icon>log out</button>
        </md-menu>

    </md-toolbar>
    <md-sidenav-layout class="demo-sidenav-layout">
      <md-sidenav align="start" mode="side" opened>
        <md-list>
          <md-list-item>
            <button md-button ><md-icon>home</md-icon> Home </button></md-list-item>
          <md-list-item>
            <button md-button ><md-icon>security</md-icon> Security </button></md-list-item>
          <md-list-item>
            <button md-button ><md-icon>settings</md-icon>Settings </button></md-list-item>
        </md-list>
      </md-sidenav>
      <router-outlet></router-outlet>
    </md-sidenav-layout>

</md-sidenav-container>

A: Just add a class to your md-sidenav, then have that class hide it when the screen is small enough.
In your template, add the class to the md-sidenav
...

<md-sidenav align="start" mode="side" opened class="hide-on-small-screens">
        <md-list>
          <md-list-item>

...

In your css, implement your class
...

@media only screen and (max-width: 500px) {
    .hide-on-small-screens {
        display: none;
    }
}

...

This will hide the sidenav if the screen is 500px or smaller. Look up media queries for more information on how to use this method.

A: Your view file:
You have to add #sidenav document refernce variable in your component html file.
<mat-sidenav #sidenav>
   ...
 </mat-sidenav>

Your TS file:
The variable which you have declared in html file you can access that variable in component ts file with the help @viewchild and please don't forget to define the type of sidenav to MatSidenav. after that you can easily access all the methods which are available on MatSidenav like close, open, toggle etc.
 import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatSidenav } from '@angular/material';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {

      @ViewChild('sidenav') sidenav: MatSidenav;
      constructor(){

      }

      ngOnInit(){}

      toggleSideNav(){
        this.sidenav.toggle();
      }
    }

A: I understand that styling should stay with CSS but I've taken a different approach to solve this issue.
I make use of Angular ViewChild and Hostlistener modules to control that programmatically. It gives you more control over what you want to do when the size of the window changes.
In your view/html:
<md-sidenav #sidenav align="start" mode="side" opened>
    ...
</md-sidenav/>

In your typescript file:
import { ViewChild, HostListener } from '@angular/core';
import { MdSidenav } from '@angular/material';

export class ClassName implements AfterViewInit {
    @ViewChild('sidenav') sidenav: MdSidenav;

    constructor() {}

    @HostListener('window:resize', [$event])
    onResize(event): void {
        if (this.sidenav !== undefined) {
            if (event.target.innerWidth <= 500) { // This can be any value.
                this.sidenav.close();
            } else {
                this.sidenav.open();
            }
        }
    }
}

With this approach the onResize method will run every time a window resize event is executed.


text:
Q: Facebook Workplace webhook call back url fixing I have two Azure web apps services and both have been configured similarly.
When I pass the callback URL to the workplace webhook, one of them is working whereas the other is not. I have verified the verify token, access token, and they are both correct.
I get the fail message: "We could not verify the webhook callback. Make sure your webserver is listening and reachable through the specified callback url." when I pass this URL along with the token:
https://<xxx>.azurewebsites.net/webhook

A: You may need to enable "Always On" via the Azure portal to make your app running reliably.


text:
Q: Print out the index and the element So I am writing a program supposed to print out the position in the array and the number at that position (by using linear search). Here is what I've got so far, but the output was not what I expected.
Output:
Number 0  Linear Search Index At 0
Number 1  Linear Search Index At 1
Number 2  Linear Search Index At 2
Number 2  Linear Search Index At 2
Number 2  Linear Search Index At 2
Number 3  Linear Search Index At 5

My expected Output:
Number 0  Linear Search Index At 0
Number 1  Linear Search Index At 1
Number 2  Linear Search Index At 2
Number 2  Linear Search Index At 3
Number 2  Linear Search Index At 4
Number 3  Linear Search Index At 5

Code:
    public class LinearSearch {
    public int linearSearch(int[] array, int key) {
        int size = array.length;
        for ( int i = 0; i < size; i++ ) {
            if ( array[i] == key ) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] arg) {
        int[] array = { 0, 1, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9, 9, 10, 11, 12, 13, 15, 16, 20, 21, 22, 22, 23, 24, 24, 26, 27, 27, 28, 30};

        LinearSearch linSearch = new LinearSearch();
        for (int i = 0; i < array.length; i++) {
            System.out.println("Number " + array[i] + " " + " Linear Search Index " +
                linSearch.linearSearch(array, array[i]));
        }
    }

  }

Any helps would be great! Thank you!

A: i in your linearSearch() function always starts from 0 ie. linearSearch() always starts its search from the beginning of the array. Therefore, linearSearch() will always return the first element which matches your key.

A: The code as you have it will return the first index where it finds the value:
public int linearSearch(int[] array, int key) {
    int size = array.length;
    for ( int i = 0; i < size; i++ ) {
        if ( array[i] == key ) {
            return i;
        }
    }
    return -1;
}

So, if your array is {1,2,2} and you look for 2, you will always get the index 1 (for the second item in the array).
Unless the array elements are unique, there's no way to fix this in the general case. When looking for an element of which there is more than one, you have to make some decision as to which one you want to use.

A: To retrieve your expected Output you can simply do:
for (int x = 0; x < array.length; x++){
   System.out.println("Number " + array[i] + " " + " Linear Search Index " + x);
}

Your method has two problems:
1. It tries to find the first occurence of an int, this is why your output is jumbled from your expectations.
2. It is ABSOLUTELY not O(n). It's O(n^2), which is probably what you don't want to do in the first place, since you asked for linear search.


text:
Q: Terraform, how to append passed-in string variable to a value? Terraform v0.12.17
I have a script where I want to do this, that is, I want it to search AMIs with a passed-in jenkins_version variable
$ terraform plan -var "jenkins_version=2.249.3" -out out.output

data "aws_ami" "jenkins_master_ami" {
  most_recent = true
  filter {
    name   = "name"
    values = ["packer-jenkins-master-${var.jenkins_version}"]
  }
  owners = ["1234567890"]
}

In my example, I want it to give me the AMI with name packer-jenkins-master-2.249.3 which I know exists because I just created it, and with the correct owner. However I get an error, since I obviously have the wrong syntax. What's the correct syntax?
Error: Your query returned no results. Please change your search criteria and try again.

A: Based on the comments.
I verified the data.aws_ami.jenkins_master_ami using my own sandbox account, and the data source definition is correct.
It returns AMI named packer-jenkins-master-2.249.3 as expected, if it exists in the given region and account.


text:
Q: anime.js not working in Ionic 3 project I am trying to use anime.js i my Ionic 3 project but whenever I use the function anime({}) in the .ts file it reports an error.
Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a
function
TypeError: __webpack_require__.i(...) is not a function
at new AnimationPage (http://localhost:8100/build/main.js:56040:78)
at createClass (http://localhost:8100/build/main.js:11137:26)
at createDirectiveInstance (http://localhost:8100/build/main.js:10973:37)
at createViewNodes (http://localhost:8100/build/main.js:12323:49)
at createRootView (http://localhost:8100/build/main.js:12228:5)
at callWithDebugContext (http://localhost:8100/build/main.js:13359:42)
at Object.debugCreateRootView [as createRootView]
(http://localhost:8100/build/main.js:12820:12)
at ComponentFactory_.create (http://localhost:8100/build/main.js:10164:46)
at ComponentFactoryBoundToModule.create
(http://localhost:8100/build/main.js:3779:29)
at NavControllerBase._viewInit
(http://localhost:8100/build/main.js:43786:44)
at c (http://localhost:8100/build/polyfills.js:3:12642)
at Object.reject (http://localhost:8100/build/polyfills.js:3:11998)
at NavControllerBase._fireError
(http://localhost:8100/build/main.js:43544:16)
at NavControllerBase._failed (http://localhost:8100/build/main.js:43532:14)
at http://localhost:8100/build/main.js:43587:59
at t.invoke (http://localhost:8100/build/polyfills.js:3:8488)
at Object.onInvoke (http://localhost:8100/build/main.js:4477:37)
at t.invoke (http://localhost:8100/build/polyfills.js:3:8428)
at r.run (http://localhost:8100/build/polyfills.js:3:3686)
at http://localhost:8100/build/polyfills.js:3:13183
Ionic Framework: 3.2.1
Ionic App Scripts: 1.3.7
Angular Core: 4.1.0
Angular Compiler CLI: 4.1.0
Node: 7.4.0
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

my file animation.ts is :
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { trigger,state,style,transition,animate,keyframes } from '@angular/animations';
import { anime } from 'animejs';
/**
 * Generated class for the AnimationPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-animation',
  templateUrl: 'animation.html',

})
export class AnimationPage {
    state: string ="small";
  constructor( public navCtrl: NavController, public navParams: NavParams) {
      anime({
        targets: '.animatable',
        translateX: 250
      });

  }

  animateThis(){
    this.state=(this.state=='small'?'large':'small');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad AnimationPage');
  }

}

If there is any other file you need to sort this out please ask!

A: I also had this problem, and fixed it by examining the tsconfig.json next to the typings in DefinitelyTyped (link).
What I was missing in my local tsconfig was "allowSyntheticDefaultImports": true. With that added, I could import in the same way as the DefinitelyTyped test, which uses:
import anime from 'animejs';
It then works to add animations like the following (with the expected type support):
anime({ targets: "#my-div", opacity: 0.5, duration: 1000 });

A: After updating to anime.js 3.0.1 and @types/animejs 2.0.2, I got the same error and went for this workaround to be able to use the new 3.0.1 and keep my previous work:
animejs is still the same as when I used 2.2.0:
import * as anime from 'animejs';
and turn my calls from anime* to (anime).default*
For example it changes from:
anime({ targets: "#my-div", opacity: 0.5, duration: 1000 });
to:
(<any>anime).default({ targets: "#my-div", opacity: 0.5, duration: 1000 });
or to use its functions change from:
anime.random(0, 360) * Math.PI / 180;
to:
(<any>anime).default.random(0, 360) * Math.PI / 180;
Like I said, it's a workaround until @types/animejs is updated.

A: try to import it like this:
import * as anime from 'animejs';

this works for me.

A: Seems that there some issues with animejs above 2.2.0 WITH with angular 7. Try to use the 2.2.0 version as stated here:
https://github.com/juliangarnier/anime/issues/527


text:
Q: angular material ie11 fix nested layout column overflow double scroll bar the double scroll bar in ie11 Facing particular issue in ie11 where the content of the container is overflowing the height of the container and ERGO the double scroll bar is observed in the ie 11 browser, i have tried fixing the issues by issue flex-basis= auto but that is not respecting the value, as there is nested layout column in the code, is there any workaround for it. for this issue
where there are nested layout column and flex-basis: auto is not working in ie11

A: The Solution to this was to use overflow: visible in a class and use the same class in the html element. there was also a instance where height: auto !important also fixed the issue but layout-fill used in the code was not working properly after that


text:
Q: Polyfill for getElementsByClassName for particular uses How can I make this.getElementsByClassName('class')[0] work for Internet Explorer 6-8? Is there any polyfill to fix this?

A: Just for the record, older browsers are still alive because people keep making efforts to support them.
Polyfill for document.getElementsByClassName
With that said, a short google search could have brought you to this link:
https://gist.github.com/eikes/2299607
The polyfill for IE6/7 is like this:
if (d.evaluate) { // IE6, IE7
  pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
  elements = d.evaluate(pattern, d, null, 0, null);
  while ((i = elements.iterateNext())) {
    results.push(i);
  }
}

Based on the document.evaluate method
https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate
EDIT: Polyfill for element.getElementsByClassName
You seem to want to call the getElementsByClassName method on a HTML element instead of on the document. Unfortunately i don't think you can polyfill that on IE6 and 7 (and even 8), as this answer seems to suggest:
How to add my own methods to HTMLElement object?
You can still use document.evaluate to acomplish the functionality you want (hint: the second parameter is a context node; it should be your element), but you need to change the calling code to something like this:
<div onclick="myPolyfill('class', this)[0].innerHTML = 'works'">


text:
Q: Safari failing to follow server-side redirect with https and hash params Safari (8.0.7 in my case) is failing to follow a redirect.  This is working in Chrome and only fails in a very specific scenario.
As best I can tell, the redirect will only fail when moving between two https connections on different domains/subdomains when hash params are involved.  It will work with query params or if one of the domains is localhost.
According to https://bugs.webkit.org/show_bug.cgi?id=24175, it seems that Safari would not honor hash params in redirects at one point in the past, but I cannot confirm if this is still the case.
It's looking to be a security/sandbox issue, but I'd be interested if anyone can put an exact finger on this issue.

A: In the end, this did prove to be a big of a Safari issue, but also a perfect storm of things which resulted in my problem.
tl;dr:
Safari doesn't apply hash params on redirects unless the paths match exactly.  Fixed in Safari 9.x
Specifics:
The server infrastructure was redirecting /foo to /foo/.  Because of this, the original hash params were not re-applied.
http://localhost:<port>/foo#/one
results in
http://localhost:<port>/foo
Forcing the trailing slash fixed the issue
http://localhost:<port>/foo/#/one
results in
http://localhost:<port>/foo/#/one


text:
Q: Enabling SSI on IIS According to this page, I should be able to:
<!-- #include file = "..\myfile.htm" -->

Q: How do I enable SSI on IIS7?
Edit:
Oh, I see what my problem is: I'm on a VPS and they have the "Turn Windows Features on or off" disabled.

A: Try this:-
1) In the IIS Manager, go to "Web Service Extensions" and set server-side includes to "Allowed."
2) In IIS Manager, expand the local computer, right-click the "Web Sites" folder (for all sites) or right-click a specific Web site, and click "Properties."
3) In the "Documents" tab, make sure that index.shtml is included in the default content page list.


text:
Q: Добавление нового json в файл Доброго времени суток. Суть такова: нужно добавить новую запись в json файл. Сам код, который уже есть:
<html>
<head><title>Get requests</title></HEAD>
<?php
$d4=$_GET['message'];
$d5=$_GET['message2']
$jsonobj='{
    "word1": ".$d4.",
    "word2": ".$d5."
}';
if ($d4 != null){
$fz=fopen("/storage/ssd1/822/2911822/public_html/Test.json",'r+') or die("He удалось открыть файл") ;
fwrite($fz, $jsonobj);
fclose($fz);
}
?>
</html>

Что нужно сделать: К примеру, если пришёл ещё один запрос - нужно НЕ перезаписать полностью весь файл, а просто добавить ещё один такой же объект. К примеру:
Если мы отправим "https://mytest/words?message="Hello!"",
то образуется файл
{
    "word1": ".$d4.",
    "word2": ".$d5."
}

Если же мы это повторим, то:
{
    "word1": ".$d4.",
    "word2": ".$d5."
}

{
    "word1": ".$d4.",
    "word2": ".$d5."
}

Можно ли так сделать? Или нужно SQL использовать в таком случае?

A: Обратите внимание на параметр mode функции fopen()
Вы используете r+, который открывает файл для чтения и записи и помещает курсор в начало файла. В Вашем случае, вам подойдет параметр mode "a+"
$fz=fopen("/storage/ssd1/822/2911822/public_html/Test.json",'a+')

Читайте подробнее в документации: http://php.net/manual/ru/function.fopen.php
Также, вы можете попробовать использовать функцию file_put_contents() с флагом FILE_APPEND:
http://php.net/manual/ru/function.file-put-contents.php


text:
Q: Python if statement not executing #   TEST
import sys
a=sys.stdin.readline()    # here the user inputs the string "HELLO"
print a
if a == "HELLO":
    sys.stdout.write("GOOD_BYE")
print "AAAAAAAAAAA"
raw_input('\npress any key to continue')

Hi there. I am new to Python.
I am using Python 2.7.11.
I do not understand why control is not entering the if statement.
The output for the given code comes out as
HELLO
HELLO
AAAAAAAAAAA
press any key to continue

NOTE: The first "HELLO" above is user input
I've tried sys.stdout.flush() for the sys.stdout.write() statement. But it doesn't seem to help.
If I write the same code with a=raw_input() instead of the second line, it works perfectly fine.
Can anyone explain the reason for this.

A: readline comes with a newline character at the end. So what you are actually doing is comparing
HELLO\n == HELLO

which is actually false.
Do a.rstrip() to remove newline.

A: readline() function read newline character from standard input console. Please use rstrip("\n") to remove the same.
import sys
a=sys.stdin.readline().rstrip('\n')
print (a)
if a == "HELLO":
    sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')

A: Try using 'in' instead of '==' in your if condition, sometimes the lines might have some hidden characters.
if "HELLO" in a:

A: You are pressing 'ENTER' after input string to send input. So your input is 'HELLO\n' while your if statement 'if' condition is 'a == "HELLO"'.
Use strip() method. The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
So new working code :
import sys
a=sys.stdin.readline().rstrip('\n')
a=a.strip() # This will remove \n from input
print (a)
if a == "HELLO":
    sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')


text:
Q: sql sum and count functions with inner join select *
from Table1 t1
inner join Table2 t2 on t1.id=t2.tid

returns 102 rows
select sum(t1.val), count(t1.val)
from Table1 t1
inner join Table2 t2 on t1.id=t2.tid

returns 29000  103
That means the second query doesnt work correctly. What the problem?

A: Looks like one of your 103 values has null in val column.
select sum(t1.val), count(*)
from Table1 t1
inner join Table2 t2 on t1.id=t2.tid

This should return 103 for count. At least in MS SQL Server. But I think it's part of SQL ANSI, so should work for all SQL ANSI compliant database engines

A: As you haven't specified a DBMS, I'm answering based on just SQL, as you tagged it. Anyway, this should apply to any DBMS.
You have 2 different queries that have the same join. The join will generate the same amount of results in both cases. It is clear from the first one that there are 102 results after the join.
If you then want to count those rows there is not way that you get more rows than there really are. What can happen is that you get less because the count(field) aggregation function will count only non-null values for field.
However, you stated that you got more and that is absolutely not possible.


text:
Q: Deserialize Json C# Есть интересный вопрос, у меня есть HTTP API, там есть метод getUserById, но API может отдать JSON вида:  {'status: 'ok','id': 1, 'name': 'test', 'age': 18, 'login': 'test', 'code': 200},
так и
{'status': 'error', 'message': 'User not found', 'code': 404}.
Я использую Newtonsoft.Json, и дело такое, что пре десериализации этих данных, мне нужно как то понять, какой именно ответ мне пришел, и если пришла ошибка, сделать соответствующие действия. Пока я делаю так, создаю базовый класс BaseResponse, у него делаю поле public string Code { get; set; }, и при получении ответа десериализую именно этот класс, и при 'status': 'ok' я просто десериализую дочерний класс от BaseResponse (UserResponse), где есть уже нужные поля. Иначе, десериализую дочерний класс от BaseResponse (ErrorResponse), где тоже есть необходимые поля. Можно ли как то улучшить всё это дело? Может есть какие то встроенные методы определения?
internal class BaseResponse
{
    [JsonProperty("status")] public string Status { get; set; }

    [JsonProperty("code")] public string Code { get; set; }
}

internal class ErrorResponse : BaseResponse
{
    [JsonProperty("status")] public string Status { get; set; }

    [JsonProperty("message")] public string Message { get; set; }

    [JsonProperty("code")] public string Code { get; set; }
}

internal class UserResponse : BaseResponse
{
    [JsonProperty("status")] public string Status { get; set; }

    [JsonProperty("name")] public string Name { get; set; }

    [JsonProperty("age")] public int Age { get; set; }

    [JsonProperty("login")] public string Login { get; set; }

    [JsonProperty("id")] public int Id { get; set; }
}


text:
Q: How to get scroll spy to work? I cant get my scroll spy to work, and I have tried everything, what am I doing wrong?  I have looked at countless examples and I seem to have everything correct. Here is the whole file, Im thinking there are maybe some conflicting css?
    <DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TCS Event Rentals</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

About Us

Event Rental Products

Events Served

Gallery

Contact

Serving the Special Events Industry

            View Our Gallery

About Us Check out the feedback

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

Contact Us to plan your next event

Enter your name and email

                <form action="" class="form-inline">

                        Contact Us
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">

                        Email Address
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">

                    <button type="submit" class="btn btn-primary">Contact Us</button>

                </form>

Gallery Check out our Gallery

Event Rental ProductsBrowse our selection of rental products

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

Events ServedPast events we served

Contact UsContact us for more

Send us a message, or contact us from the address below

                    <address>
                        TCS Event Rentals

                        Lear Dr

                        Burlington, NC 27310

                        P: 1-800-888-8888
                    </address>

                    <form action="" class="form-horizontal">

                            Name

                                <input type="text" class="form-control" id="user-name" placeholder="Enter your Name">

                            Email

                                <input type="text" class="form-control" id="user-email" placeholder="Enter your Email Address">

                            Your Website

                                <input type="text" class="form-control" id="user-url" placeholder="If you have any">

                            Any Message

                                <textarea name="user-message" id="user-message" class="form-control" cols="20" rows="10" placeholder="Enter your Message"></textarea>

                                <button type="submit" class="btn btn-primary">Submit</button>

                    </form>

Contact Us to plan your next event

Enter your name and email

                <form action="" class="form-inline">

                        Contact Us
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">

                        Email Address
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">

                        <button type="submit" class="btn btn-primary">Contact Us</button>
                </form>

Twitter

Facebook

Youtube

©Copyright 2017

A: Requires relative positioning: The element with data-spy="scroll" requires the CSS position property, with a value of "relative" to work properly.
body {
  position: relative;
}

It's working just add content for corresponding hashes, and resize the window height in order to see it.

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

About Us

Event Rental Products

Events Served

Gallery

Contact

Section 1

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 2

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 3

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 4 Submenu 1

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 4 Submenu 2

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

A: I finally discovered the solution through more research, I simply had to add css: height: 100%; to the body element. Everything works perfectly now.


text:
Q: How to image USB drives without having OS X mount them afterwards I am using OS X to write USB drives. I have a disk image and am using dd to the raw device to create the drive image. The problem I'm having is that OS X is automatically mounting the drives as soon as they are imaged. I'd like to prevent this behavior. Is there any way to do so?

A: Download, install and start Disk-Arbitrator. Activate it in "block mount" mode.
Now execute sudo dd if=/path/to/file of=/dev/diskN [operands]. The resulting volume won't be mounted and no file will be created nor a folder will be changed:
sh-3.2# ls -laO
total 0
drwxrwxr-x  7 user      staff  -      306 17 Jan 22:21 .
drwxrwxrwt@ 8 root      admin  hidden 272 17 Jan 23:11 ..
drwx------  5 root      wheel  -      170 17 Jan 22:21 .Spotlight-V100
d-wx-wx-wt@ 2 root      wheel  hidden  68 17 Jan 22:21 .Trashes
drwx------  5 root      staff  -      170 17 Jan 22:21 .fseventsd

Original image content:
drwxrwxr-x  7 user      staff  -      306 17 Jan 22:21 .
drwxrwxrwt@ 9 root      admin  hidden 306 17 Jan 23:23 ..
drwx------  5 root      wheel  -      170 17 Jan 22:21 .Spotlight-V100
d-wx-wx-wt  2 root      wheel  hidden  68 17 Jan 22:21 .Trashes
drwx------  5 root      staff  -      170 17 Jan 22:21 .fseventsd

Don't forget to deactivate Disk Arbitrator after finishing the cloning.

My first proposal below modifies at least some metadata of the folders /Volumes/VolumeName/.Trashes and /Volumes/VolumeName/.fseventsd
Simply appending && diskutil eject /dev/diskN after dd'ing should work:
sudo dd if=/path/to/file of=/dev/diskN [operands] && diskutil eject /dev/diskN

Upon completion of the dd command this should immediately eject the thumb drive.


text:
Q: MonoTouch.Dialog with custom base UIViewController I have a requirement to have all controllers inherit from a single base controller. However, some controllers use MonoTouch.Dialog, which requires the DialogViewController.
Is it possible to create a UIViewController, and internally, create a DialogViewController and replace (or AddSubView) the UIViewController's view with the one created from the DialogViewController?
What about rotations? memory warnings? etc? Is this recommended? Is there an alternative approach?

A: You can use UIViewController containment.
This is a new feature on iOS 6:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html
http://www.cocoanetics.com/2012/04/containing-viewcontrollers/


text:
Q: Should I use createRef or useRef and why? In this component I'm not sure if I should use createRef and useRef to get the information from the input. Can you please help me figuring out how I should choose one or the other? Thanks in advance
import React from 'react'

const AddBook = (props) => {

    const handleNewBook = props.handle
    let titleInput = React.createRef();
    let authorInput = React.createRef();

    return (

        Add a book:
        <form>
          <input type="text" ref={titleInput} placeholder="Title" />
          <input type="text" ref={authorInput} placeholder="Author" />
          <button
            type="reset"
            onClick={() =>
              handleNewBook(titleInput.current.value, authorInput.current.value)
            }
          >
            Add
          </button>
        </form>

    );
}

export default AddBook

A: CreateRef is usually used in class components.
useRef (a hook that creates a ref) is used in functional components.
Since you are using functional best use useRef.

A: For the difference between useRef and createRef: What's the difference between `useRef` and `createRef`?
Anyway, in your case, if you need a controlled input you should deal with the component state:
import React, { useState } from 'react';

const AddBook = (props) => {

    const handleNewBook = props.handle
    const [state, setState] = useState({})

    return (

        Add a book:
        <form>
          <input type="text" value={state.title} onChange={e => setState(prev => ({...prev, title: e.target.value}))} placeholder="Title" />
          <input type="text" value={state.author} onChange={e => setState(prev => ({...prev, author: e.target.value}))} placeholder="Author" />
          <button
            type="reset"
            onClick={() =>
              handleNewBook(state.title, state.author)
            }
          >
            Add
          </button>
        </form>

    );
}


text:
Q: Changing background doesn't work in all browsers I have a script that changes my background image every few seconds. It works for me, however, some users reported that it's not working on Safari browsers.
I am using Chrome and it works great, but some of them also have problems on Google Chrome. Any ideas what might cause this problem?
    changeBackground();

    function changeBackground(){
        var currentBackground = $("body").css("background-image");

        setTimeout(function(){
            if(currentBackground == 'url("http://example.com/images/new-home-page/woman.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd2.png")');

            }
            else if(currentBackground == 'url("http://example.com/images/new-home-page/slajd2.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd3.png")');

            }
            else if(currentBackground == 'url("http://example.com/images/new-home-page/slajd3.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/woman.png")');

            }

            changeBackground();

        }, 6000);
    }

A: Try to add a first default background image, probably in safari can't get the CSS url image for the first match:
changeBackground();

    function changeBackground(){
        var currentBackground = $("body").css("background-image");

        setTimeout(function(){
            if(currentBackground == 'url("http://example.com/images/new-home-page/woman.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd2.png")');

            }
            else if(currentBackground == 'url("http://example.com/images/new-home-page/slajd2.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd3.png")');

            }
            else if(currentBackground == 'url("http://example.com/images/new-home-page/slajd3.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/woman.png")');

            // ADD THIS ELSE
            } else {
                  // SET THE FIRST AND DEFAUT BACKGROUND
                $("body").css("background-image", 'url("/images/new-home-page/slajd2.png")')
                currentBackground = 'url("/images/new-home-page/slajd2.png")';
            }

            changeBackground();

        }, 6000);
    }

The JSFiddle tried in safari for windows.
UPDATE
Or you can use a safer way, use a counter instead of the css style like this:
changeBackground();

var currentBackground = 0;

function changeBackground(){
  setTimeout(function(){
    console.log(currentBackground);
    if (currentBackground == 0){
      currentBackground = 1;
      $("body").css("background-image", 'url("https://static.pexels.com/photos/7125/water-trees-lake.jpg")');
    }
    else if(currentBackground == 1){
      currentBackground = 2;
      $("body").css("background-image", 'url("https://static.pexels.com/photos/4243/black-and-white-forest-trees-branches.jpg")');
    }
    else if(currentBackground == 2){
      currentBackground = 0;
      $("body").css("background-image", 'url("https://static.pexels.com/photos/9159/pexels-photo.jpg")');
    }

    changeBackground();

  }, 6000);
}

The JSFiddle update

A: I think the problem is with url standards
use relative url instead:
 changeBackground();

    function changeBackground(){
        var currentBackground = $("body").css("background-image");

        setTimeout(function(){
            if(currentBackground == 'url("/images/new-home-page/woman.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd2.png")');

            }
            else if(currentBackground == 'url("/images/new-home-page/slajd2.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/slajd3.png")');

            }
            else if(currentBackground == 'url("/images/new-home-page/slajd3.png")'){
                $("body").css("background-image", 'url("/images/new-home-page/woman.png")');

            }

            changeBackground();

        }, 6000);
    }


text:
Q: How can I check SMTP server is alive with Python? I want to check if an email exists with Python. I can check the format and DNS records correctly, but how can I check if the SMTP server is alive?
I tried a few libraries because I didn't want to use APIs. For example validate_email
from validate_email import validate_email
is_valid = validate_email(email_address='sample@sample.com', check_format=True, check_dns=True, dns_timeout=10, check_smtp=True, smtp_timeout=10, smtp_debug=False)
print(is_valid)

But I still couldn't check the SMTP server.

A: Try to use https://pypi.org/project/python-nmap/ for check server is up/down and ports are open.


text:
Q: Weak hypercharge assignments in the Standard Model While refreshing my memory on details of the Standard Model, I ran into a muddle.  I might not exist to ask bizarre questions if the neutron, neutrino, and hydrogen atom were not electrically neutral.  Thanks to the cleverly contrived weak hypercharge assignments of the SM, they are.
Weinberg justified these assignments in terms of anomaly cancellation, but the discussion in his book QT of F (1996, v2, p387) assumed the nonexistence of a right-handed neutrino.  He found the ratios of hypercharges to be totally constrained.  (There were actually two discrete solutions, but one was clearly unphysical.)  But nowadays, given the evidence of neutrino mixing, isn't there one more continuously adjustable hypercharge parameter to worry about?  It seems the SM is one constraint short of a unique solution.
Matthew Schwartz's book QFT and SM (2014, p634) acknowledges the problem but offers three lame excuses for the right-handed neutrino's orthodox $Y=0$ assignment:  nonexistence (?), Majorana character (?), or any other reason (?).  I gather that given a different value, the hydrogen atom would still be neutral, but the stability of heavy nuclei would be affected.
Can any of you δημιουργοι offer a better rationale for the values of hypercharge, other than magnetic monopoles, empirical fact, or the anthropic principle?  A grand unifying group, perhaps?

A: Neutrino masses do not prove that there are right-handed neutrinos. The left-handed neutrino can have a Majorana mass, for example by coupling to a SU(2)L triplet Higgs.
The GUT which most compactly gives rise to right-handed neutrinos is SO(10). The hypercharges are underdetermined, but stipulating that the SO(10) Higgses have relatively low-dimensional representations (something implied by string theory, btw) favors the usual hypercharges.


text:
Q: how to get query parameter in lua or nginx? I am trying to implement this-
https://gist.github.com/MendelGusmao/2356310
Lua,nginx based URL shortener,The only change i want to implement is when some query string parameter comes with shortened URL i need to take that parameter and insert into the long URL.
e.g.
http://google.com?test=2  will be like  http://abc.in/abc
while hitting on http://abc.in/abc?test=3 I get redirected to - http://google.com?test=3.
For that i need to take query string parameters from $request_URI, can any one help with some code?

A: You can also use ngx.var.QUERY_STRING to access the query string and unescape and parse it.

A: You can obtain the query parameter with just nginx by using $arg_test, test is the name of the query parameter in this example.
This is documented in http://nginx.org/en/docs/http/ngx_http_core_module.html#var_arg_.

A: You should be able to use ngx.var.arg_name where name is the name of the query parameter you want to access. See Variables with Infinite Names section in this tutorial for details on query parameter handling; you may also check my blog post for Lua nginx/openresty examples.
As an alternative, you can use ngx.req.get_uri_args() to retrieve all query parameters as one table. See this section in the same tutorial for the brief comparison between these methods.


text:
Q: How to make accordion active item clickable After trial-and-erroring for the last couple hours, I realize I should really take a course on the basics of jQuery. Can someone help me with what will likely be a simple answer?
I am putting this accordion into a page, but I want the active panel to be able to click to close. Is there something simple I can do to make it possible?
(function($) {

  //Hide all panels
  var allPanels = $('.accordion > dd').hide();

  //Show first panel
  $('.accordion > dd:first-of-type').show();

  //Add active class to first panel
  $('.accordion > dt:first-of-type').addClass('accordion-active');

  //Handle click function
  jQuery('.accordion > dt').on('click', function() {

    //this clicked panel
    $this = $(this);

    //the target panel content
    $target = $this.next();

    //Only toggle non-displayed
    if(!$this.hasClass('accordion-active')){

      //slide up any open panels and remove active class
      $this.parent().children('dd').slideUp();

      //remove any active class
      jQuery('.accordion > dt').removeClass('accordion-active');

      //add active class
      $this.addClass('accordion-active');

      //slide down target panel
      $target.addClass('active').slideDown();

    }

    return false;
  });

})(jQuery);

A: Try:
  jQuery('.accordion > dt').on('click', function() {
      //this clicked panel
      var $this = $(this),
          $target = $this.next();

      //slide up any open panels and remove active class
      $this.parent().children('dd').not($target).slideUp(); //Slide Up everything but the target one

      //remove any active class
      jQuery('.accordion > dt').removeClass('accordion-active');
      //add active class
      $this.addClass('accordion-active');
      //slide down target panel
      $target.addClass('active').slideToggle();

    return false;
  });

Demo
And actually you can simplify this to:
 jQuery('.accordion > dt').on('click', function () {
        var $this = $(this) ,
            $target = $this.next();

        $('.accordion > dt.accordion-active').not($this.toggleClass('accordion-active')).removeClass('accordion-active');

        $this.siblings('dd').not($target.addClass('active').slideToggle()).slideUp();

        return false;
    });

Demo


text: Q: De Rham cohomology ring of the Stiefel manifold in low dimensions Let $V_k(\textbf{R}^n)$ be the Stiefel manifold : the $k$-frames in the $n$ dimensional real space. I'm trying to understand the de Rham cohomology ring for $k=2$ or $k=n-1$. I had good ideas for $n-1$ since it's the real projective space, but I'm having trouble for $k=2$. I don't want to use something too fancy (like the Serre spectral sequence), but I'm trying to use the sphere fibrations or the principal fibrations with the Grassmannian. How could one do it ?


text:
Q: Bootstrap Column 6 Image Issue Now, this is a new project, so I need some help.
I have the following code. Please press full screen.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<!DOCTYPE html>

  <title>Stack Overflow Question</title>
  <link rel="stylesheet" type="text/css" href="bootstrap.css">
  <link rel="stylesheet" type="text/css" href="style/home.css">

Home

Why Does This

Not

Work

Now, when expanded, this is what the website shows.

However, there is a small gap between both column 6 photos.

        IMAGE TAG

        IMAGE TAG

This produced the following -

You can see that the image on the left is bigger on the right and therefore it is not correct.
My question is, how can I make the gap between the two columns smaller (to around 10px) without needing to change the padding? I want to make the images bigger in order to decrease the size of the gap, but I can't seem to find a way!
Thanks.

A: Make a class :
no-space {
       Width: 100% !important;
       Margin: 0px !important;
}

Then put this class in next to where col-md-6 is seep rated by a space like this :
Class="col-md-6 no-space"

And there should be no spaces between the photos now.

A: To actually solve this question too, what I can also do is go to the Bootstrap CSS file and edit the padding-left and padding-right values to equal amounts. Originally, both values are set at
padding-left:15px;
padding-right:15px;

but looking at other examples such as airBnb, their padding is both set at 12.5 so this is also another solution.


text:
Q: Cannot run as java application in Eclipse, even have correct main() class I get confusing with Eclipse, when I import a project from Git, then I click on a java file, which has correct main function  like:
  public static void main(String[] args) throws Exception { }

and the outside class has same name with java file. But when I right click the java file, only have "run on server" or "run configuration" option, no "run as java application" like normally. Even if I copy a java file which I can run as java application from different project to this project (no error) then it do not have this option ??? I am quite sure it is nothing to do with the code. I checked the code, totally the same and should be able to run.(I am aware of similar questions on the website but I checked and my problem is not there)
So is there any extra steps I need to do with this project (like maven build ? -> I tried this but also can't run, how to run it properly ?) to have this option again ???
Really confusing !

A: If the project is already imported in your workspace, Right click on your and Configure > Convert to Maven... This will enable the Maven builder and force m2e configurators to setup all the required project natures on your project.
You can also install the m2eclipse-git connector to streamline the "import maven project from git" process. It should be available from Preferences > Maven > Discovery > Open Catalog.
Once it's done, you should import your project via Import...> Maven > Checkout Maven Projects from SCM

A: Keep in mind that projects imported from GIT are not necessarily java projects, as Eclipse understands this term. Is the project, as it exists in the repository, an Eclipse project? If it is, it should have two files in its root folder named .classpath and .project. If these two files are missing, you will need to instruct Eclipse to create them, with logical defaults. Also, if the root folder of the project has a pom.xml file, then it is a maven project, which is a whole different kettle of fish.

A: I was facing a similar issue. Below steps solved the problem:

*

*Import project from git

*Right click on Project -> Import -> Import as existing Maven Project

*One maven module will be imported, you can open .java file with main method from that module

*Right click, run as -> you can see the option.

A: This can seem obvious but check if the function main is correctly declared. Function's signature must be :
static void main (String args[])

If you miss this point (ex: you forget scale declaration for args with []) you won't be able to use the option "run as appication", in my case option wasn't displayed.

A: Sometimes it might happen when the maven project in not updated on importing to the workspace.
Right click on Project -> Maven -> Update Project..
Then Run As -> Java Application -> Select class containing main method.

A: If you are handling multi-module project,
you might be trying to execute the java file( main class) within the parent project itself. That would be the mistake.
Make sure to open the sub- module ( would be listed as separate project in the explorer) and then execute the java file.


text:
Q: Unit testing Nativescript application logic on a browser I am trying to set up unit testing for a Nativescript application, run by ng test on a browser. The problem is that whenever there is a tns-core-modules or another plugin import, the module cannot be resolved because of the platform specific files (e.g. "tns-core-modules/application/application.android.js") that never get compiled into the bundle, thus throwing an error like "Module not found: Error: Can't resolve 'tns-core-modules/application'".
I know there is a built-in unit test support in Nativescript. The problem I have with it is that it can't run on CI. I would like to be a ble to have lightweight tests for my business logic, mocking out all platform dependencies.
I have looked for a way to mock the module imports at runtime with no luck. I looked into rewire package but it only runs on node.

A: I finally managed to get it working. Not a very elegant solution and I have yet to see how much maintenance it requires. Key points here:

*

*Use paths section of the tsconfig.json to add mock import
locations

*In the mocks directory create files for any unresolved module

*Some nativescript modules are referencing helper functions on global
scope but they're undefined. My solution was to define them in
test.ts like this

window['__decorate'] = () => {};
window['__extends'] = () => {};
window['__metadata'] = () => {};
window['__param'] = () => {};
window['layout_base_1'] = { CSSType: () => {} };
window['Crashlytics'] = {};
window['Fabric'] = {};

A: You simply can not run NativeScript application on Browser.
In case if you are looking for something like headless mode, Appium has one too, isHeadless in capabilities.
Between, may I know why you think you can not run the {N} unit tests on CI? It should work on CI too, after all it's a machine that runs the same commands based on some trigger.


text:
Q: UIScrollView - using zoomscale and contentsoffset for CGAffineTransform Some background on this-> I'm using a UIScrollview (holding a 10,000x10,000 catiledlayer backed view) and passing it's delegate to a custom overlay view (that is the size of the screen) that will be scaled and moved around depending on the zoom and content offset of the view.
I'm struggling with taming the contentoffset/zoomscale from the didScroll: didZoom: delegates into a CGAffineTransform I can apply to my "overlay" view.  Scrolling is pretty straightforward as it's a simple translate. Zooming seems to be the challenge because I have to combine with the current translate as well.  Once scrolling/zooming
stops I clear the transforms and redraw view (which is the easy part).
(previous question UIScrollView w/ Large CATiledLayer + Overlay that renders fast about best methods for doing this)
So my question: How can i convert the contentoffset & zoomscale into a cgaffinetransform i can apply to another view in order to make it appear that i am pinching/zooming/scrolling the overlay view?


text:
Q: Using an alternate price field in OpenCart I have an OpenCart installation that is running two stores, one wholesale and one retail. The product catalog is shared, but the problem is that OpenCart doesn't natively support multiple pricing options. So I added a new field to the oc_product table, retail_price. The idea is that I would use the price field for wholesale pricing and the retail_price field for -- you guessed it -- retail pricing.
I have everything pretty much covered on the admin side, so my new field is showing in the product section and is being updated in the database.
Now the issue is getting the price to change on the front end for the retail store. Needless to say, product price is used in a ton of different scripts. So I figured the best/sneakiest method would be to change the price field when the database is queried and the price data is initially set. This is kind of where I got lost... I changed it in some places I thought were right but the price doesn't change on the front end. Sometimes OpenCart can be a mysterious fig.
Can anyone give me a clue as to where the best place(s) to change the price would be?

A: I assume that you've already created a different customer type for both wholesale and retail customers in the admin area.
That being the case, it's very simple to add this functionality to the model.
Open:
catalog/model/catalog/products.php
On or around line 22 you should see a line that looks like this:
$query->row['price'] = ($query->row['discount'] ?
                     $query->row['discount'] : $query->row['price']);

Determine the numerical value of your retail customer, let's assume it's 1 and wholesale customers is 2.
The variable $customer_group_id used below is previously set at the open of the getProduct() method.
Replace the previous line with the following:
if ($customer_group_id == 2):
    $query->row['price'] = ($query->row['discount'] ?
                        $query->row['discount'] : $query->row['price']);
else:
    $query->row['price'] = ($query->row['discount'] ?
                        $query->row['discount'] : $query->row['retail_price']);
endif;

Now if your customer is logged in and is not a wholesale customer, or is not logged in, they will see the retail price, if they are logged in as a wholesale customer they will see the wholesale price.


text:
Q: How to interpolate a variable in a twig loop to render a file? I am looping through a list of social profiles to render the logo. Each social item has a field of svg_icon_code that looks like "twitter" or "facebook". I want to use this code to render the correct file. Currently I am just hardcoding in "twitter" resulting in all logos being the Twitter svg. How can I use the icon_code to render the correct svg?
{% for item in options.social_media_links %}

        {% include 'component/svg-twitter-icon.twig' %}

{% endfor %}

A: You need to concat the icon like this,
{% for item in options.social_media_links %}

        {% include 'component/svg-'~item.svg_icon_code~'-icon.twig' %}

{% endfor %}

If an icon doesn't have a template or the template is missing you can do this to render a default icon
{% for item in options.social_media_links %}

        {% include [ 'component/svg-'~item.svg_icon_code~'-icon.twig', 'component/svg-default-icon.twig' ]  %}

{% endfor %}


text:
Q: Control for variables in tableau? I'm pretty new to the charting software tableau. I'm trying to draw some distribution graphs of price per square meeter in tableau:
The price is impacted by two variables i know, time of sale

and total size of the house.

Can I somehow control for theese variables in tableau or should I use another tool for that?

A: Out of the box, Tableau does not have a way to weight variables into Box-plots.
However, as you mention that you are new to Tableau, it is worth noting that 'Calculated fields' are a way that you may customize, aggregate, or qualify your underlying data. These fields can be as simple or as complex as the provided functions will allow.
Another consideration is that statistical packages like R and scripting languages like Python can be linked to Tableau. These tools can be leveraged to perform more complex series of calculations on underlying data. This allows for you to port your Data Science familiarity over to a tool like Tableau.


text:
Q: client side validation not working asp.net mvc5 I am trying to create client side validation. When I keep the fields on page empty and click submit button, the server side validation is working but client side validation is not working. I am also including jqueryval bundle in layout.cshtml file.
@Scripts.Render("~/bundles/jqueryval")

I have also check following line in web.config file
 <add key="ClientValidationEnabled" value="true" />

Model:
public class File
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }

    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    [Required]
    public string FileSrc { get; set; }

}

View:
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

File

        @Html.ValidationSummary(false, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.FileSrc, htmlAttributes: new { @class = "control-label col-md-2" })

                <input type="file" id="FU" multiple />
                @Html.HiddenFor(model => model.FileSrc,new { id="fm"})
                @Html.ValidationMessageFor(model => model.FileSrc, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

AM I missing anything?

A: attach jquery unobtrusive script too


text:
Q: Profile Public Link Generator Similar To Trello Card Profiles I have a task Kanban. I have a program written in Laravel that I am using. Can someone help me with figuring out how to have this data posted to a separate page for PUBLIC users to view via link.
Such as Trello. You register. You create a "board" then you have a backend (which I already have) and then you have a public link/profile that gets generated that ANYONE can view even without registering.
ie. https://yoursite.com/c/2eh9d18y
REAL EXAMPLE:
https://trello.com/b/IRxPRIyB/loot-gen-inventory
IMAGE OF MY OWN THAT NEED TO BE CALLED INTO A PUBLIC VIEW PAGE:
https://www.chocoboe.com/flarum/assets/files/2022-09-16/1663290313-429605-tasks9-15.jpg
Any help or direction is greatly appreciated.


text:
Q: Filter on single element transformed value of ArrayField Assuming I have the following Models defined:
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.db.models import Func, F

class SingleDayEvent(models.Model):
    title = models.TextField()
    day = models.DateField()

class MultiDayEvent(models.Model):
    title = models.TextField()
    days = ArrayField(models.DateField(), default=list)

If I want a queryset with all SingleDayEvent in a given calendar week, I would do:
SingleDayEvent.objects.filter(day__week = week)

How can I achieve the same for the MultiDayEvent defined above given that the dates are stored in an ArrayField?


text:
Q: $\det(xA-B) = 0$ has three distinct solutions Let $A,B \in M_{3\times 3}(\mathbb{C})$ be two complex symmetric matrices, assume $\det(xA-B) = 0$ has three distinct solutions $a,b,c$. Show that there is an invertible $P \in M_{3\times 3}(\mathbb{C})$ such that $P^TAP = I_3$, $P^TBP = diag(a,b,c).$
I have got no clue where to start.

A: Hint: With Takagi's factorization, we see that there exists a unitary $V_1$ such that $D=  V_1^TA V_1$ is diagonal with non-negative entries.  We then have
$$
\det(x\bar V_1 D V_1^* - B) = \det[\bar V_1 (xD - V_1^TBV_1)V_1^*] = \det(V_1)^{-2} \det(xD - [V_1BV_1^T])
$$
For convenience, I'll define $B_1 = V_1BV_1^T$.
Now, consider $p(x) = \det(x D - B_1)$. Note that in order for $p(x)$ to have 3 distinct roots, $p$ must be of degree at least 3, which means that $D$ must have positive diagonal entries.  Thus, we may write
$$
\det(xD - B_1) = \det[D^{1/2}(xI - D^{-1/2}B_1 D^{-1/2})D^{1/2}] =
\det(D) \det(xI - [D^{-1/2}B_1 D^{-1/2}])
$$
Let $B_2 = D^{-1/2}B_1 D^{-1/2}$. It now suffices to consider the problem with $A = I$ and $B = B_2$ an arbitrary complex-symmetric matrix.