text:
Q: boost::any_range and operator [] Consider the following code:
#include <boost/range.hpp>
#include <boost/range/any_range.hpp>
#include <boost/range/join.hpp>

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <list>

struct TestData {
  TestData() : m_strMem01("test"), m_intMem02(42), m_boolMem03(true) {}
  std::string m_strMem01;
  int m_intMem02;
  bool m_boolMem03;
};

struct IntComp {
  bool operator()(const TestData &s, int i) { return s.m_intMem02 < i; }
  bool operator()(int i, const TestData &s) { return i < s.m_intMem02; }
  bool operator()(const TestData &i, const TestData &s) {
    return i.m_intMem02 < s.m_intMem02;
  }
};
struct StrComp {
  bool operator()(const TestData &s, const std::string &str) {
    return s.m_strMem01 < str;
  }
  bool operator()(const std::string &str, const TestData &s) {
    return str < s.m_strMem01;
  }
  bool operator()(const TestData &i, const TestData &s) {
    return i.m_strMem01 < s.m_strMem01;
  }
};

typedef boost::any_range<TestData, boost::forward_traversal_tag,
                         const TestData &, std::ptrdiff_t> TestRange;

std::vector<TestData> vecData(10);
std::list<TestData> listData(20);

TestRange foo() {
  TestRange retVal;

  auto tmp1 = std::equal_range(vecData.cbegin(), vecData.cend(), 42, IntComp());
  retVal = boost::join(retVal, tmp1);
  auto tmp2 =
      std::equal_range(listData.cbegin(), listData.cend(), "test", StrComp());
  retVal = boost::join(retVal, tmp2);
  return retVal;
}

int main(int argc, char *argv[]) {
  auto res = foo();
  for (auto a : res) {
    std::cout << a.m_strMem01 << std::endl;
  }
  //std::cout << res[4].m_intMem02 << std::endl;
}

If you uncomment the last line the code fails since distance_to not implemented for any_forward_iterator_interface. I'm not sure what exactly I'm missing here, like implementing operator[] or distance_to but for what? My own version traversal tag? And why it doesn't work in the first place?
Coliru version

A: I would say the answer depends on your performance needs and your laziness when it comes to implementing a new iterator abstraction. The core reason for your [] operator not working is the fact that std::list<...> does not provide a random access traversal iterator. If you would have chosen a container that provides such an iterator. You any_range<...> could have taken the random_access_traversal_tag and everything would be fine.
I think it's fair to say that it is not such a big deal to implement a random access iterator on top of a list by simply encapsulating the current index and count forward and backward within the list whenever a specific position is meant to be accessed, but it's clearly against the nature of the list performance-wise.

*

*Is there a good reason to hold one of the collection in a list ?

*Is there a good reason to access the resulting any_range by random ?

*Is it worth the effort to provide a inefficient random access interface for std::list ?

A: Of course any_iterator (which underlies the any_range implementation) doesn't gratuitously emulate RandomAccess iterators for any odd iterator you pass.
If you want that, just make an iterator adaptor that does this (making it very slow to random access elements in a list - so don't do this).


text:
Q: Is there a static analysis tool for identifying sql injection for php/mysql Is there a static analysis tool for identifying sql injection for php/mysql.
A tool which run on a php script would analyze the sql statements and find if there are any possible sql injection possibilities for the sql statements.

A: Not sure if a tool like that exists for PHP Script, but the security compass tools are great for a first analysis :
http://labs.securitycompass.com/index.php/exploit-me/

A: What I found is rather disappointing.
RATS (branded as Fortify) has some PHP suport, but it doesn't detect SQL injections. Apparently HP guys are focused on .NET and Java apps.
OWASP SWAAT Project seems to be dead to me.
RIPS Scanner is a tool you can install on your web server and navigate in the source of your application on the web interface. Unfortunately it just hangs for me when I open it.
There is an online tool called DevBug. It is not very useful to scan your entire codebase, but it's good for beginners to practice security.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to encode square brackets in spring url? I have a path variable which has square brackets in spring url.But i am getting bad reuqest for the same. I am encoding the url in backbone framework using encodeUriComponent. But still even after url being encoded correctly i am getting bad request.

A: Actually the problem was because of backward slash in the path variable and it needs a double encoding for it to get encoded correctly.


text:
Q: Find all pixels on a line in Java To get right to it: Say I've got two specific pixels a & b, as well as a list of random others. I now want to check all pixels in that list if they are on the line which passes through a & b (but which is NOT restricted to have a & b as endpoints!)
I looked at Bresenham's line algorithm, but that seems to only find the points between a & b?
I've also had a look at linear equations in general but I'm kind of stuck on how to properly discretize the continuous line into pixels...
(I'm trying to implement a random sampling algorithm in java, which tries to find the line with the most pixels on it, if that matters).
Thanks a lot for any help with this :)

A: I strongly suggest that you compute the distance between the point and the line.
If you use one pixel as unit of measurement (which you will if you work in a pixel coordinate system), you can simply check if the distance from the point to the line is < 1.
Here's how to compute the distance between a point and a line:

*

*Minimum Distance between a Point and a Line

*Wolfram: Point-Line Distance--2-Dimensional

A: You could search not between a and b, but between the points that are on the same line, but out of the borders of image. You can get them simply putting vector (b-a) necessary amount of times to the a side and to the b side. And the use your Bresenham's line algorithm.
As for more concrete answers, define the question better, please.  Do you consider pixels as points or squares or circles?  What is "pixel is on the line" in your terms? What width has your line? You are looking for the line with max number of pixels on the cm length or in the rectangle borders? Among what lines do you search?


text:
Q: hide some button in asp.net 4.0 I want to ask how can I hide some button for different users? For example, an admin can access all buttons, but a regular member cannot access some buttons (e.g. add new user button).

A: Set the Visible property to true or false depending on your condition (check user),to hide or show.
  if(someConditionExpressionHere)
  {
     btnSave.Visible=true;
  }
  else
  {
    btnSave.Visible=false;
  }

Assuming btnSave is the Id of the button you want to hide/ show. You should udpdate the someConditionExpressionHere with a check to see whether the user is admin or normal user.


text: Q: How to change from HyperLight Load mode to forced PWM mode In the MIC33M650 step-down module, is there a possibility/workaround to deactivate the HyperLight Load mode? Or decrease the threshold of the current needed to activate forced-PWM mode?


text:
Q: Jquery document.on event What is the difference between  these event handling
       $(document).on("click","selector",function(event){

        });

and
       $("selector").live("click",function(event){

       });

A: In the first case, the event is attached on "document" DOM, right ?
In the second case, the event is attached on the "selector" DOM, right ?
The first was chosen by jQuery : just few elements catch the events in the solution 1/ (document can be attached to every events), but in the solution 2/ many elements of the page are in memory, attached to events.
For instance :
$(".test").live("click",function(event){"do something"}
$(".test1").live("click",function(event){"do something1"}
$(".test2").live("click",function(event){"do something2"}

3 elements are listening to the click event, right ?
Now these elements are in a div "myDiv"
$("#myDiv").on("click",".test",function(event){"do something"}
$("#myDiv").on("click",".test",function(event){"do something"}
$("#myDiv").on("click",".test",function(event){"do something"}

Only myDiv is attached the event click by bubbling !
But don't use on on the document tag, use this function on a few global div !

A: First of all the .on() method is the actual event listener which you should use.
Second  .live() used to be the #1 but was deprecated in the last versions so you should not use it anymore.
The work the same way, you can call it the same way.


text:
Q: DOM Document - How to get the text inside a tag without the inner tags Assume I have a dom_document containing the following html and it is put in a variable called $dom_document

  some text here
  I want this

What i would like is retrieve the text that is inside the div tag ('I want this'), but not the a tag. What i do is the following:
$dom_document->nodeValue;

Unfortunately with this statement I have the a tag in with it. Hope someone can help. Thank you in advance. Cheers. Marc

A: You can use XPath for it:
$xpath = new DOMXpath($dom_document);
$textNodes = $xpath->query('//div/text()');

foreach ($textNodes as $txt) {
    echo $txt->nodeValue;
}


text:
Q: glfwSwapBuffers(window) causing a segfault I was having a problem with code from a GLFW tutorial (open.gl) and I narrowed it down to it being caused by
glfwSwapBuffers(window);

The full code: http://pastebin.com/Evtf5PRf
The CMakeLists.txt I am using: http://pastebin.com/vKUQiMtf
This is on Ubuntu 12.04
Changing to the proprietary drivers has fixed the issue! (See answer from me below)

A: This issue is caused by GLFW not interacting properly with the drivers Ubuntu provides. To solve this, change to the proprietary drivers.
How to change your graphics drivers to the proprietary drivers:

*

*Open System Settings (Icon is a gear with a wrench)

*Open Software and Updates

*Go to the Additional Drivers tab

*Select the proprietary graphics drivers for you graphics card.

*Restart your computer for the changes to apply


text:
Q: Can NSArrayController bounds to core data run fetch in background thread? I made NSArrayController bound to core data, which has more than 100k rows to fetch, and set UseLazyFetching as TRUE. surely NSTableView is bound to NSArrayController. all are set programmatically like this:
@implementation MainWindowController {
    NSArrayController *_arrayController;
}

- (void)windowWillLoad
{
    _arrayController = [[NSArrayController alloc] init];
    [_arrayController setManagedObjectContext:self.managedObjectContext];
    [_arrayController setEntityName:@"User"];
    [_arrayController setUsesLazyFetching:YES];
    [_arrayController setSelectsInsertedObjects:NO];
    [_arrayController setPreservesSelection:NO];
    [_arrayController fetchWithRequest:nil merge:NO error:NULL];
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    [self.tableView bind:NSContentBinding
                toObject:_arrayController
             withKeyPath:@"arrangedObjects"
                 options:nil];
}

and I've found that all fetch operations, triggered by lazy fetching option while scrolling, are running in main thread and this cause UI is blocked while fetching is running. the following is from instrument.

Is there any way to run fetching in background thread?
I've tried using managed object context inited with NSPrivateQueueConcurrencyType, but it makes no difference. :(
Or is it bad to use cocoa binding & core data to handle a lot of rows in table view? I'm quite familiar with NSFetchedResultsController from iOS and looking for something operating like it in OS X.

A: You're in for a world of heck if you try to do BOTH lazy AND multi-threaded fetches...BUT! There's a solution that might would work for you.
If your objects aren't too big (less than 30K each on average) you can fit them all in memory. So, when you first load your tableView just fetch the first 100 (or 1000?) objects, then dispatch to a separate thread with its own sub-managedObjectContext and fetch ALL the rest, then just move those objects into the main managedObjectContext.
This is still work, but it seems do-able, to me.


text:
Q: Show/hide password with Javascript I am new to JS world, and for my practice am trying to build a simple input field where users can toggle (show/hide) their password.
So far I add everything (icons and css) but I don't know why I have this error in my JS code, just run the code and you will see.
Also, my icons are messed up somehow, I don't know how to fix this.

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Title</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

      <form id="login-form" method="post" name="f">

          Pass
          <input id="password" name="password" type="password" tabindex="2">
          <img src="data:image/png;base64,[encoded data, 9448 characters]"
            class="input_img" alt="">

          <input type="checkbox" id="toggle-password" />
          Show Password

        <button type="submit" class="login-btn" tabindex="3" name="Submit">Login</button>

      </form>

Can anybody help me with this?

A: You are trying to execute a sf function that is undefined. I dont see this function in your code. You try to find toggle-password before it is rendered on page.
Remove onload from body and add your scripts on end of your body tag.
For quick fix for toggle label add this to your style #toggle-password + label, but i think the idea with using this label is bad:
#toggle-password + label {
{
    position: absolute;
    top: 50%;
    right: 20px;
    transform: translateY(-50%);
}

You should also improve padlock styline use this:
.input_img {
    position: absolute;
    top: 50%;
    left: 13px;
    height: 30px;
    transform: translateY(-50%);
}

I change bottom from to top 50% and add the translate transfrom to the calc position from the center of the icon


text:
Q: How to trim (cut) UIView in Swift I made UIView the frame is x: UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width*3, height: UIScreen.main.bounds.size.height.
When moved to other ViewController by self.navigationController?.popViewController(animated: true), the left side of view is shown during screen transition.
When I set the point to x:0, y:0, the screen transition was smooth, didn't show the left side of the view during screen transition.
So I want to cut only the left side of the view before screen transition. How can I do it in Swift?


text:
Q: Wolfram Alpha equation I couldn't find anywhere I was just playing around with Wolfram Alpha and n-th derivatives of functions, and I found this....n-th derivative of W(x) equation
As you can see, there are some weird functions. I found most of them in the bottom-right corner. However, that Y function isn't anywhere. I typed in that, and it returned nothing. My phone is really laggy so I couldn't see how Mathematica interprets it. Does anybody know the name of that function?


text:
Q: ASP.NET: Store user information on submit i'm kinda new into asp.net so i need some help.
i have this form, that the data is stored in a SQL db using Linq.
my question is, how can i add a column, that will have all the information about the sender, meaning IP address, browser, referrer etc.
the thing is is i want to store it in one field.
i come from a php knowledge that has been long forgotten by me, but i still remember there was some serialize command, that you could run on an array and store it in a db, then when you want it back to an array you would just run deserialize command and it would go back to an array.
so what you guys think the best way of preforming this action is?
Thanks in advance!

A: Assemble the data in any serialized form yourself and save it to the DB column. One way could be to use xml format
var sb = new StringBuilder();

sb.Append("<userdata>");
sb.Append("<browser>").Append(Request.Browser.Browser).Append("</browser>");
sb.Append("<ipaddress>").Append(Request.UserHostAddress).Append("</ipaddress>");
sb.Append("<referrer>").Append(Request.UrlReferrer.AbsoluteUri).Append("</referrer>");
sb.Append("</userdata>");

string SenderData = sb.ToString();
// Save the SenderData string to a varchar DB column.

// The above code only proposes the serialization idea.
// As commented, it doesn't encode the user values.
// One of the way to take care of that could be using XmlTextWriter.

var sb = new StringBuilder();

var xtw = new XmlTextWriter(new StringWriter(sb));

xtw.WriteStartElement("userdata");
xtw.WriteElementString("browser", Request.Browser.Browser);
xtw.WriteElementString("ipaddress", Request.UserHostAddress);
xtw.WriteElementString("referrer", Request.UrlReferrer.AbsoluteUri);
xtw.WriteEndElement();

xtw.Close();

string SenderData = sb.ToString();
// Save the SenderData string to a varchar DB column.

// Another suggested way

public class UserData
{
    public string Browser { get; set; }
    public string IPAddress { get; set; }
    public string Referrer { get; set; }

    public UserData()
    {
    }

    public UserData(string browser, string iPAddress, string referrer)
    {
        Browser = browser;
        IPAddress = iPAddress;
        Referrer = referrer;
    }
}

var userData = new UserData(Request.Browser.Browser, Request.UserHostAddress, Request.UrlReferrer.AbsoluteUri);

var xmls = new System.Xml.Serialization.XmlSerializer(typeof(UserData));
var sb = new StringBuilder();
var xtw = new XmlTextWriter(new StringWriter(sb));

xmls.Serialize(xtw, userData);

xtw.Close();

string SenderData = sb.ToString();
// Save the SenderData string to a varchar DB column.


text:
Q: how to linstall texlive without lcdf-typetools For some reasons (i.e, openmpi conflicts with lcdf-typetools a b, which is not the main topic here), I need to install texlive of any version without lcdf-typetools. Anyone please shed lights on how to do this? What is the consequence that install texlive without lcdf-typetools?
note:
  I have found that both texlive2012 and texlive 2014 requires lcdf-typetools


text:
Q: Excel Function to find any given column value as substring in another cell How do I find out in excel or sql if any member cell of an excel column is a substring of another excel column cell value, and put it as a function output in adjacent cell?
I also tried to run SQL query (HP Quality Center database), tried multiple excel built in formulas, but I never get correct result.
This is my SQL code snippet, I used which does not return correct results.
WITH FH_HEIRARCHY (AL_DESCRIPTION, AL_ITEM_ID, AL_FATHER_ID, PATH) AS

(

SELECT
 A.AL_DESCRIPTION /*Test Plan Folder.Name*/,
 A.AL_ITEM_ID /*Test Plan Folder.Item Id*/,
 A.AL_FATHER_ID /*Test Plan Folder.Parent Folder*/,
 CAST(A.AL_DESCRIPTION AS varchar(1000)) AS PATH

 FROM ALL_LISTS A /*Test Plan Folder*/

 WHERE A.AL_FATHER_ID = 0

 UNION ALL

 SELECT

 B.AL_DESCRIPTION /*Test Plan Folder.Name*/,
 B.AL_ITEM_ID /*Test Plan Folder.Item Id*/,
 B.AL_FATHER_ID /*Test Plan Folder.Parent Folder*/,
 CAST(F.PATH + '\' + B.AL_DESCRIPTION AS varchar(1000)) AS PATH

 FROM ALL_LISTS B /*Test Plan Folder*/

 INNER JOIN FH_HEIRARCHY F ON B.AL_FATHER_ID = F.AL_ITEM_ID
)

SELECT

 TS.TS_TEST_ID,
 TS.TS_NAME,
 TS.TS_STEPS,
 TS.TS_EXEC_STATUS,
 TS.TS_DESCRIPTION,
 TS.TS_USER_02,
 DS.DS_ID, /*Design Step.Step ID*/
 DS.DS_STEP_NAME, /*Design Step.Step Name*/
 DS.DS_DESCRIPTION, /*Design Step.Step Description*/
 DS.DS_EXPECTED,
 DS.DS_USER_01, /*Design Step.Tcode*/
 FH.AL_ITEM_ID AS FOLDER_ID /*Test Plan Folder.Item Id*/,
 FH.AL_DESCRIPTION AS FOLDER_NAME /*Test Plan Folder.Name*/,
 FH.PATH AS FOLDER_PATH /*Test Plan Folder.Path*/

FROM TEST TS /*Test*/

 LEFT OUTER JOIN FH_HEIRARCHY FH /*Test*/

  ON FH.AL_ITEM_ID = TS.TS_SUBJECT /*CTE*/

 LEFT OUTER JOIN DESSTEPS DS /*Design Step*/

  ON DS.DS_TEST_ID = TS.TS_TEST_ID

WHERE TS.TS_NAME IS NOT NULL AND FH.PATH LIKE '%MASTER%TESTS%' AND (

DS.DS_DESCRIPTION Like ('%' +         ' /SAPAPO/AC03 '         + '%')
OR DS.DS_DESCRIPTION Like ('%' +         ' /SAPAPO/C3 '         + '%')
);

Basically, I want to put in column C true if any value in column B is present for the given cell value of Column A as a substring, and false otherwise.
C
olumn A    | Column B    | Column C

Hi there    | Hi          | TRUE

Hello there | Ho          | FALSE

A: Excel Formula:
=ISNUMBER(SEARCH(B1,A1))

If complete word matches are wanted, for example Hi is does not match in Hillside then we can use:
=ISNUMBER(SEARCH(" " & B1 & " "," " & A1 & " "))

SEARCH is Case in-sensitive.  If case sensitivity is desired replace SEARCH with FIND

To see if any in B match in A1 then use SUMPRODUCT wrapper:
=SUMPRODUCT(--(ISNUMBER(SEARCH(" "&$B$1:$B$2&" "," "&A1&" "))))>0


text:
Q: Android EditText issue findviewbyId Assigning ids to few edit texts results in the following error :
the error is in the parameters of findViewById token

Here is the line of code that its on
final EditText myEditField = (EditText) findViewById(R.id.percentText1);

...This is the Xml code sorry again to nerd for posting the java...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/percentText1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/enterButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="224dp"
        android:onClick="onEnterClick"
        android:text="Calculate Tip" />

    <EditText
        android:id="@+id/percentText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="53dp"
        android:ems="10"
        android:singleLine="true"
        android:text="Percent" />

    <EditText
        android:id="@+id/percentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/percentText"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:singleLine="true"
        android:text="Bill Amount" >

        <requestFocus />
    </EditText>

</RelativeLayout>

...The Java Code... The error i figure is that i improperly gave the edit text an id...
package tip.calculator;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import tip.calculator.R;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText myEditField = (EditText) findViewById(R.id.percentText); //error here

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void onEnterClick(String args []){

        int percentage;
        int percentageInp;
        int billAmount;
    }

}

A: Make sure that you dont have this in your imports
import android.R;

Eclipse sometimes imports this class which instead should be
import your.application.packagename.R;

usually this happens when we ctrl+shft+o to fix imports. Eclipse adds the R class when we do that. :)
EDIT:
from your new question, there is a spelling error.
Try to paste this line inside the onCreate() method:
EditText myEditField = (EditText) findViewById(R.id.percentText);

A: change
final EditText myEditField = (EditText) findViewById(R.id.percentText1);

to
final EditText myEditField = (EditText) findViewById(R.id.percentText);

percentText1 is the id for RelativeLayout not for EditText.

A: What you need to understand is that if there is any problem with a resource nothing than nothing works anywhere.  So check if the there are any errors in the resource folder? Are there any problems listed? Then just attempt to find one of buttons, comment everything else out.  You will not find anything until you resolve all the layout errors.  Then just make sure you are declaring the id like this
  android:id="@+id/myTextId"

A: import tip.calculator.R; <- there it's the problem i think


text:
Q: combine lists to make one list that has each element a sum of the individual elements I have 3 lists:
['1','2']

['a','b','c']

['X','Y']

and the result I am looking to get:
['1aX','1bX','1cX','2aX','2bX','2cX','1aY','1bY','1cY','2aY','2bY','2cY']

is there a way to set this up quickly?

A: >>> x,y,z=['1','2'],['a','b','c'],['x','y']
>>> s=[a+b+c for c in z for a in x for b in y]
>>> s
['1ax', '1bx', '1cx', '2ax', '2bx', '2cx', '1ay', '1by', '1cy', '2ay', '2by', '2cy']

This way you can choose the order you want

A: You can use itertools.product():
map("".join, itertools.product(list1, list2, list3))

A: To get the exact result that you specified, you can use the following:
import operator
import itertools

list1 = ['1','2']
list2 = ['a','b','c']
list3 = ['X','Y']
getter = operator.itemgetter(1, 2, 0)
result = [''.join(getter(seq)) for seq in itertools.product(list3, list1, list2)]

The final argument to itertools.product() will be the first to change, so based on your example output we want list2 to be last, then list1, and then list3, since first the middle element advances, then the first element, then the last.  The operator.itemgetter() call is used to reorder the elements so that the element from list1 comes first, etc.
I find list comprehensions easier to read here, but here is a one-line alternative that uses map():
map(''.join, map(operator.itemgetter(1, 2, 0), itertools.product(list3, list1, list2)))

(You could do the list comprehension in one line as well, but you shouldn't because then the operator.itemgetter() call would be executed on each iteration)


text:
Q: Mocking Modules in Jest I have a method in App.js for which I want to write test cases. But when I import App.js in the test file all the import statements inside App.js are also getting imported and causing an error. Is it possible to mock a dependency which is imported insde my App.js using jest. Consider the example below
//App.js
import user from '../user.js';
//some functions which needs to be tested

Is it possible to mock user.js when I try in my App.spec.js file ?

A: You can use sinonjs https://sinonjs.org/how-to/stub-dependency/
sinon.stub(user, 'functionToMock').callsFake(() => {})

A: You could simply mock any user module in the jest by the following statement.
jest.mock('./moduleName')

for further understanding, you could refer to the following document.
https://jestjs.io/docs/en/manual-mocks#:~:text=When%20a%20manual%20mock%20exists,moduleName'


text:
Q: Parameter index out of range in SQL Java use phmyadmin My version table has 8 attributes, all are populated when inserting a Project (One to many relationship, projects - versions). Why do I get this error if I have the complete fields? Or how are values loaded to a table (version) that depends on another (project)?
(codeProject is FK -Cascade-)
Parameter index out of range (8 > number of parameters, which is 7). Error in VersionDAO
public class VersionDAO {
    ConexionSQL conectar = new ConexionSQL();
    Connection con;
    PreparedStatement ps;
    ResultSet rs;
    String changeVersion;

    public int insertarVer(Version ver, Proyecto pro) {
        String sql = "INSERT INTO version (idVersion, nameVersion, efficVersion, acumCases, acumFail, acumTime, contPruebas, codeProject) VALUES (?,?,?,?,?,?,?,(SELECT code FROM proyecto))";
        try {
            con = conectar.getConexionSQL();
            ps=con.prepareStatement(sql);
            ps.setInt(1, ver.getIdversion());
            ps.setString(2, ver.getNameVersion());
            ps.setDouble(3, 0.0);
            ps.setInt(4, ver.getAcumCasos());
            ps.setDouble(5, 0.0);
            ps.setDouble(6, 0.0);
            ps.setInt(7, ver.getContPruebas());
            ps.setInt(8, pro.getCod());
            ps.executeUpdate();
            return 1;

        } catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }

Table Project (Proyecto in spanish)
public class ProyectoDAO {
ConexionSQL conectar = new ConexionSQL();
Connection con;
PreparedStatement ps;
ResultSet rs;

    public int insertar(Proyecto p) {
        String sql = "INSERT INTO proyecto (code, name, status, language, duration, advance, effec) VALUES (?,?,?,?,?,?,?)";
        try {

            con = conectar.getConexionSQL();
            ps=con.prepareStatement(sql);
            ps.setInt(1, p.getCod());
            ps.setString(2, "Prueba");
            ps.setInt(3, p.getStatus());
            ps.setString(4, "PHP");
            ps.setInt(5, p.getDuracion());
            ps.setInt(6, p.getAvance());
            ps.setDouble(7, 0.0);
            ps.executeUpdate();

            return 1;

        } catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }

A: I see 7 question marks in your upper SQL statement but 8 calls of ps.setXXXX().

A: for the first code, instead you should get the code of the project out of the request.
//You should do something like this

public class VersionDAO {
  // all you private attributes

  public int insertarVer(Version ver, Proyecto pro) {

    // you should avoid to make any calculation or getting value directly when you set values on the PreparedStatement

    int idVersion = ver.getIdversion();
    String nameVersion = ver.getNameVersion();
    int acumCasos = ver.getAcumCasos();
    int contPruebas = ver.getContPruebas();
    int code = pro.getCode(); // get the code of you project here
    String query = "INSERT INTO version(idVersion, nameVersion, efficVersion, acumCases, acumFail, acumTime, contPruebas, codeProject) VALUES (?,?,?,?,?,?,?,?)";

    try {
            con = conectar.getConexionSQL();
            ps=con.prepareStatement(sql);
            ps.setInt(1, id);
            ps.setString(2, nameVersion);
            ps.setDouble(3, 0.0);
            ps.setInt(4, acumCasos);
            ps.setDouble(5, 0.0);
            ps.setDouble(6, 0.0);
            ps.setInt(7, contPruebas);
            ps.setInt(8, code);
            ps.executeUpdate();
            return 1;

        } catch(Exception e){
            e.printStackTrace();
            return 0; // change the return position other way you will always have 0 as retrun value
        }
  }
}


text:
Q: Python, Flask ошибка: AttributeError: module 'json' has no attribute 'dumps' День добрый подскажите в чём проблема до сегодняшнего дня всё работало, сегодня открыл проект и вижу следующее, работаю в среде пайчарм
E:\python\app\venv\Scripts\python.exe E:/python/app/app.py
Traceback (most recent call last):
  File "E:/python/app/app.py", line 1, in <module>
    from flask import Flask, render_template
  File "E:\python\app\venv\lib\site-packages\flask\__init__.py", line 19, in <module>
    from jinja2 import Markup, escape
  File "E:\python\app\venv\lib\site-packages\jinja2\__init__.py", line 33, in <module>
    from jinja2.environment import Environment, Template
  File "E:\python\app\venv\lib\site-packages\jinja2\environment.py", line 15, in <module>
    from jinja2 import nodes
  File "E:\python\app\venv\lib\site-packages\jinja2\nodes.py", line 19, in <module>
    from jinja2.utils import Markup
  File "E:\python\app\venv\lib\site-packages\jinja2\utils.py", line 41, in <module>
    _slash_escape = '\\/' not in json.dumps('/')
AttributeError: module 'json' has no attribute 'dumps'

Process finished with exit code 1

A: В итоге решил удалить python и всё его окружение с компа, перезагрузил и заново поставил в и тоге заработало но с ошибками. Вот они, что ему опять не так)))
E:\python\app\venv\Scripts\python.exe E:/python/app/app.py

Error processing line 1 of E:\python\app\venv\lib\site-packages\json_extensions-0.2.1-py3.7-nspkg.pth:
Traceback (most recent call last):
    File "C:\Users\Администратор\AppData\Local\Programs\Python\Python37-32\lib\site.py", line 168, in addpackage
      exec(line)
    File "", line 1, in
    File "", line 580, in module_from_spec
  AttributeError: 'NoneType' object has no attribute 'loader'
Remainder of file ignored
Error processing line 1 of E:\python\app\venv\lib\site-packages\json_extensions-0.2.1-py3.7-nspkg.pth:
Traceback (most recent call last):
    File "C:\Users\Администратор\AppData\Local\Programs\Python\Python37-32\lib\site.py", line 168, in addpackage
      exec(line)
    File "", line 1, in
    File "", line 580, in module_from_spec
  AttributeError: 'NoneType' object has no attribute 'loader'
Remainder of file ignored
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
Error processing line 1 of E:\python\app\venv\lib\site-packages\json_extensions-0.2.1-py3.7-nspkg.pth:
Traceback (most recent call last):
    File "C:\Users\Администратор\AppData\Local\Programs\Python\Python37-32\lib\site.py", line 168, in addpackage
      exec(line)
    File "", line 1, in
    File "", line 580, in module_from_spec
  AttributeError: 'NoneType' object has no attribute 'loader'
Remainder of file ignored
Error processing line 1 of E:\python\app\venv\lib\site-packages\json_extensions-0.2.1-py3.7-nspkg.pth:
Traceback (most recent call last):
    File "C:\Users\Администратор\AppData\Local\Programs\Python\Python37-32\lib\site.py", line 168, in addpackage
      exec(line)
    File "", line 1, in
    File "", line 580, in module_from_spec
  AttributeError: 'NoneType' object has no attribute 'loader'
Remainder of file ignored
 * Debugger is active!
 * Debugger PIN: 279-512-791
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Mar/2019 11:21:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Mar/2019 11:21:47] "GET /python HTTP/1.1" 200 -


text:
Q: Codeigniter , classe Session é segura? O Codeigniter possui uma classe própria para Session, isto é, não utiliza as Sessions nativas do PHP.
Note: The Session class does not utilize native PHP sessions. It generates its own session data, offering more flexibility for developers.
Voce pode setar uma session da seguinte forma:
$data_session = array(
                              'id_login'                    => $id_user,
                              'nome'                         => $nome,
                              'userPermission'                   => 1
                              );
$this->session->set_userdata($data_session);

Minhá dúvida é:
É realmente seguro utilizar esta classe para gravar ID's que deveriam ser secretos?
Existe alguma contra-indicação na qual não deveríamos utilizar esta classe?

A: Sem o devido cuidado não!
Você pode setar algumas opções de segurança para a sua Session, como uma chave de encriptação (hash) e modificar o tempo de duração da sessão (por padrão 1 hora).
Uma situação (obviamente) não recomendável é deixar a Sessão ativa após fechar o navegador, que vinha por padrão ativada no arquivo config.php ou dados de recuperação;

A: Acredito que se você usar uma encriptografia (hash) e também , no arquivo config.php tornar false a opção de deixar a sessão ativa após o encerramento do navegador


text:
Q: How to use reactive values in substr? I'm having trouble with my shiny app. I want that the user can type in all the variables needed for the substr function to filter data from a data frame using dplyr.
I made an example using the dataframe iris.
In the textInput(select1) I like to type in "Species".
In the numericInput(start1) I like to type in "4".
In the numericInput(end1) I like to type in "6".
In the textInput(match1) I like to type in "osa".
Now I want that the tableOutput only shows the rows which matches the criteria "osa" in the column "Species" from digit 4 to 6.
The numericInput(start1), the numericInput(end1) and the textInput(match1) are working. But the textInput(select1) doesn't work. When I'm using the input as variable I'm getting an empty data frame.
When I change the code an type in "Species" instead of reactivevar1() in the substr function I get the data frame I want.
Example:
filter(substr(Species, reactivevar2(), reactivevar3()) == reactivevar4())

This alternative works. But this is not what I want.
I want this to work:
filter(substr(reactivevar1(), reactivevar2(), reactivevar3()) == reactivevar4())

I tried different functions like substring and stringr::str_sub. I also tried as.character.
This is the full example:
library(shiny)
library(dplyr)

ui = fluidPage(
  textInput(inputId="select1", label="Type in variable", value = "", width = NULL, placeholder = NULL),
  numericInput(inputId="start1", label="Start digit", value=NULL, min = NA, max = NA, step = NA,
               width = NULL),
  numericInput(inputId="end1", label="End digit", value=NULL, min = NA, max = NA, step = NA,
               width = NULL),
  textInput(inputId="match1", label="Criteria to match", value = "", width = NULL, placeholder = NULL),
  actionButton(inputId="startfil", label="Start filter", icon = NULL, width = NULL),

  tableOutput('table')

)
server = function(input, output,session) {

  obs <- observeEvent(input$startfil, {

  var1 <- NA
    reactivevar1 <- reactive({
    var1 <- input$select1
    return(var1)})

  var2 <- NA
  reactivevar2 <- reactive({
    var2 <- input$start1
    return(var2)})

  var3 <- NA
  reactivevar3 <- reactive({
    var3 <- input$end1
    return(var3)})

  var4 <- NA
  reactivevar4 <- reactive({
    var4 <- input$match1
    return(var4)})

  irisfiltered <- iris %>%
    filter(substr(reactivevar1(), reactivevar2(), reactivevar3()) == reactivevar4()) #reactivevar1() doesn't work
  output$table <- renderTable(irisfiltered)

  })

}

shinyApp(ui = ui, server = server)

I just can't figure out what is wrong with my code. It is important that the user can type in a start and an end digit to filter the substring.

A: Welcome to SO!
reactivevar1() has the value  "Species", so your substr function returns "cie". And
substr(reactivevar1(), reactivevar2(), reactivevar3()) == reactivevar4()

returns FALSE, when you type i.e. "osa" in reactivevar4()
You could use getin your pipe statement like this:
irisfiltered <- iris %>%
      filter(substr(get(reactivevar1()), reactivevar2(), reactivevar3()) == reactivevar4())
output$table <- renderTable(irisfiltered)

Or make use of !! and as.name
    iris %>%
        filter(substr(!!as.name(reactivevar1()), reactivevar2(), reactivevar3()) == reactivevar4())
 output$table <- renderTable(irisfiltered)

Hope this helps


text:
Q: Find $\frac{\partial (x,y)}{\partial (u,v)}$ Given $$x=\frac{u+v}{1-uv}$$ and $$y=\arctan\left(u\right)+\arctan\left(v\right)$$
Then find $$\frac{\partial (x,y)}{\partial (u,v)}$$

I don't understand the notation $(x,y)$ or $(u,v)$,since I've always seen a function instead of $(x,y)$ and a variable instead of $(u,v)$,can someone help?

A:
I don't understand the notation $(x,y)$ or $(u,v)$,since I've always seen a function instead of $(x,y)$ and a variable instead of $(u,v)$,can someone help?

It could be confusing if you're thinking about the standard notation for a partial derivative of a function of several variables, but it's not that different: $x$ and $y$ are in fact functions of $u$ and $v$.
The notation
$$\frac{\partial (x,y)}{\partial (u,v)} \tag{1}$$
refers to the Jacobian (determinant) which is, in this case:
$$
\det\begin{bmatrix} \dfrac{\partial x}{\partial u} & \dfrac{\partial x}{\partial v} \\[4pt] \dfrac{\partial y}{\partial u} & \dfrac{\partial y}{\partial v} \end{bmatrix}\tag{2}
$$
So you should remember $(1)$ as a (compact) notation for $(2)$.
I would expect your text(book) to introduce this notation, if you're giving this kind of exercise.

A: As far as I understand, $$\frac{\partial (x,y)}{\partial (u,v)}$$ means, that you have to find the determinant of a Jacobian matrix, given $x(u,v)$ and $y(u,v)$, i.e.:
$$\frac{\partial (x,y)}{\partial (u,v)} =
\begin{vmatrix}
\frac{\partial x}{\partial u} & \frac{\partial x}{\partial v} \\
\frac{\partial y}{\partial u}  & \frac{\partial y}{\partial v}
\end{vmatrix}.$$
Taking partial derivatives of your given $x(u,v)$ and $y(u,v)$.


text:
Q: PyQt Send a signal from a class (sub-window) back to the MainWindow (class) How can I send a signal from my class ScanQrCode() back to the calss MainDialog()? I am using Python 2.7 and PyQt with windows generated by QtDesigner4.
I did manage to send the signal from within the class ScanQrCode() to a receiving function also within the class. However the signal gets lost when I try to receive it by another class MainDialog() but in the same file
class ScanQrCode( QtGui.QDialog, Ui_ScanQrCode ):
    trigger = QtCore.pyqtSignal()

    def __init__( self, parent = None ):
        super( ScanQrCode, self ).__init__( parent )
        self.setupUi( self )
        self.pushButton_Scan.clicked.connect( self.scan )
    # End of __init__

    def scan( self ):
        print 'Scanning'
        # Place holder for the functionality to scan the QR code
        self.lineEdit_QrCode.setText( "QR-123456789" ) # Dummy QR code
        if ( not self.signalsBlocked() ):
            print 'emit trigger'
            self.trigger.emit()
    # End of sub-function scan
# End of class ScanQrCode

class MainDialog( QtGui.QMainWindow, agpt_gui.Ui_MainWindow ):
    def __init__( self, parent = None ):
        super( MainDialog, self ).__init__( parent )
        self.setupUi( self )
        self.connectActions()
        self.windowScanQrCode = None

        #Define threads
        self.thread = ScanQrCode()
        self.thread.trigger.connect( self.updateQrCode )
    # end of __init__

    def main( self ):
        self.show()

    def connectActions( self ):
        # Define the connection from button to function
        self.pushButton_ScanQrCode.clicked.connect( self.scanQrCode )
        self.pushButton_Exit.clicked.connect( self.exit )
    # End of sub-function connectActions

    @QtCore.pyqtSlot()
    def updateQrCode( self ):
        """
        Update the new scanned QR code in the main window
        """
        print 'Update QR code'
        self.lineEdit_QrCode.setText("123456789")
    # End of sub-function updateQrCode

    def scanQrCode( self ):
        if self.windowScanQrCode is None:
            self.windowScanQrCode = ScanQrCode( self )
        self.windowScanQrCode.show()
    # End of sub-function scanQrCode
# End of class MainDialog

There is no error. Simply the main window does not update.
I think in principle the Signal and connect are working but there must be something missing which I can not see.
Any help would be appreciated.

A: It looks like the ScanQrCode instance that you show (windowScanQrCode) never has its trigger signal hooked up to updateQrCode. Meanwhile, the ScanQrCode instance that you hook up properly (thread) is never shown.
The simplest solution is to delete the method scanQrCode and replace the line
self.pushButton_ScanQrCode.clicked.connect( self.scanQrCode )

with the line
self.pushButton_ScanQrCode.clicked.connect( self.thread.show )

and then call connectActions() after you define thread.


text:
Q: gpg: overwriting .pdf on encryption => decryption fails I use gpg (GnuPG) 1.4.11. to encrypt a file foo.pdf via gpg -c foo.pdf. The encrypted file is then foo.pdf.gpg and, additionally, the original file foo.pdf exists. I can then decrypt foo.pdf.gpg via gpg foo.pdf.gpg as expected. However, if I use gpg -o foo.pdf -c foo.pdf and choose to overwrite the existing file on encryption, then use gpg foo.pdf to decrypt the encrypted file, and finally choose to overwrite the existing file foo.pdf (again), the file is still protected and can't be viewed.
I then tried to execute gpg foo.pdf again (I thought decrypting failed the first time, that's why I tried it again). Now the file seems to be corrupted: gpg: [don't know]: 1st length byte missing. Any ideas? Is it generally not a good idea to overwrite the files? I expected to obtain one file foo.pdf.gpg after encryption (with the original file foo.pdf being removed automatically).

A: GPG is writing to the same file it's reading from (no temp files).   As it reads plaintext to encrypt, that data is being clobbered by the already-encrypted data GPG is writing out (or vice versa on decryption).  In general, this won't work (it's like a filter that is modifying its input with its output).


text:
Q: Enter causing postback even if no submit button is present I have a form in asp.net page. Whenever enter key is pressed the page is posted back.
I don't have any submit button in my form and using javascript to submit form.

                     Add

                <asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CssClass="btn" CausesValidation="false" OnClick="btnCancel_Click">
                 Cancel
                </asp:LinkButton>

row('#saveConfirm').click(function (){
    //submit form
});

A: This can be addressed I believe with the accepted solution of the following post:
ASP.Net page enter key causing post back
Quoting:

*

*You could set the DefaultButton on the Form or a Panel. This way you have full control what happens.

*Set UseSubmitBehavior="False" on your Buttons. This disables the "AutoPostback" on Enter.

A possible javascript solution for ASP.NET is covered under this solution:
Disable default button in ASP.NET [duplicate]

A: use Updated Panel which avoid postback while enter.


text:
Q: Python web app - question about long timed requests I have a question for example I've created a Python flask app and everything works well, but here's a thing one of the functions take around a minute to two minutes to complete.
Is there a way to make user not wait 1 - 2 minutes for a function to complete? for example user would use app normally on front end, make request to backend API and use the rest of the app while that request is completed? has anyone done anything similar and are there libraries for such cases when there are long requests? or is that due to how my functions are structured?

A: I've already implemented REST api similar this.
I used celery library and redis as broker and backed.
Request API is like below and func is celery task.
def your_api():
    ...
    async_task = func.delay(your_params)
    return async_task.task_id

and you should inquiry by your task_id like below:
def inquiry_result():
    task_id = ... # get from client
    res = celery.AsyncResult(task_id)
    if res.ready(): # if result is ready
        return res.get() # you can get result
    return None

celery task sample code:
@celery_app.task
def func(...):
    # do some thing
    result = ...
    return result


text:
Q: Animation is setting Wrong Values for Opacity I created a, somewhat, reusable Opacity animation in code that exposes two dependency properties so the animation can be run without having to define animations for all the elements.
If anyone is wondering then yes, I also created these animations in UWP XAML with the help of behaviors but I am getting the same results. The problem is while in XAML I can't actually see the end result of Opacity values of the element but with code-behind I can insert breakpoints and see the values.
The class that I am using is:
public static class VisibilityAnimationHelper
    {
        private static Storyboard visibleSB = null;
        private static Storyboard collapseSB = null;
        private static DoubleAnimation collapsedAnim = null;
        private static DoubleAnimation visibleAnim = null;

        public static readonly DependencyProperty AnimationProperty = DependencyProperty.RegisterAttached("AnimationProperty", typeof(Visibility), typeof(VisibilityAnimationHelper), new PropertyMetadata(Visibility.Visible, AnimationChangedCallback));

        public static readonly DependencyProperty ParentProperty = DependencyProperty.RegisterAttached("Parent", typeof(FrameworkElement), typeof(VisibilityAnimationHelper), null);

        private static void AnimationChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is UIElement element)) return;

            collapsedAnim = new DoubleAnimation()
            {
                To = 0.01,
                FillBehavior = FillBehavior.Stop
            };
            collapsedAnim.Completed += delegate
            {
                element.Visibility = Visibility.Collapsed;
            };

            visibleAnim = new DoubleAnimation()
            {
                To = 1.01,
                FillBehavior = FillBehavior.Stop
            };
            visibleAnim.Completed += delegate
            {

            };

            visibleSB = new Storyboard()
            {
                AutoReverse = false,
                Duration = new Duration(TimeSpan.FromSeconds(0.2))
            };
            Storyboard.SetTarget(visibleAnim, element);
            Storyboard.SetTargetProperty(visibleAnim, "Opacity");
            collapseSB = new Storyboard()
            {
                AutoReverse = false,
                Duration = new Duration(TimeSpan.FromSeconds(0.2))
            };
            Storyboard.SetTarget(collapsedAnim, element);
            Storyboard.SetTargetProperty(collapsedAnim, "Opacity");

            if ((Visibility)e.NewValue == Visibility.Collapsed)
            {
                if (!collapseSB.Children.Contains(collapsedAnim))
                    collapseSB.Children.Add(collapsedAnim);
                collapseSB.Begin();
            }
            else
            {
                element.Visibility = Visibility.Visible;
                if (!visibleSB.Children.Contains(visibleAnim))
                    visibleSB.Children.Add(visibleAnim);
                visibleSB.Begin();
            }

        }

        public static void SetParent(DependencyObject element, FrameworkElement value)
        {
            element.SetValue(ParentProperty, value);
        }

        public static FrameworkElement GetParent(DependencyObject element)
        {
            return (FrameworkElement)element.GetValue(ParentProperty);
        }

        public static void SetAnimationProperty(DependencyObject element, Visibility value)
        {
            element.SetValue(AnimationProperty, value);
        }

        public static Visibility GetAnimationProperty(DependencyObject element)
        {
            return (Visibility)element.GetValue(AnimationProperty);
        }
    }

You can use this class to test how it's working. For me the end result looks like below:

If you look at the above picture, in the first row, right most item is showing 2 hearts with opacity set to 1 (as a normal thing), middle item shows one heart as normal and other one a little fainted. The fainted one has just been animated, once hiden and then shown again. If I keep animating the hearts they keep fading away bit by bit.
I also inserted two breakpoints when the animations completed and the result of the opacity is wrong. I am not sure why the animation is not setting proper values. It can be a bug within the SDK maybe.

In the above 2 pics you can see the end result of the Opacity of the element. When the collapsed animation completes the Opacity gets set to around 0.8 (when it should be 0) and then after the visible animation completes then the opacity is around 0.84 (when it should be 1). In the UI it animates correctly but the actual opacity of the eement gets se wrongly somehow.
Maybe I am running the animations wrongly? Please provide some suggestions here. Thanks

A: Changing the Storyboards and Animations to following seems to be helping with setting the correct vaues.
collapsedAnim = new DoubleAnimation()
{
    To = 0,
    AutoReverse = false,
    Duration = new Duration(TimeSpan.FromSeconds(0.2))
};
visibleAnim = new DoubleAnimation()
{
    To = 1,
    AutoReverse = false,
    Duration = new Duration(TimeSpan.FromSeconds(0.2))
};
visibleSB = new Storyboard();
collapseSB = new Storyboard();


text:
Q: How to 'await' ads load call back? I want to load the ad first and showAd() later. Although I use await on load, it still does not 'await' in InterstitialAdLoadCallback() since it is a callback.
InterstitialAd? _interstitialAd;
print("OUTPUT 1");
await InterstitialAd.load(
  adUnitId: '123456789',
  request: AdRequest(),
  adLoadCallback: InterstitialAdLoadCallback(
    onAdLoaded: (ad) {
      print("OUTPUT 2");
      _interstitialAd = ad;
    },
    onAdFailedToLoad: (err) {
      _interstitialAd = null;
    },
  ),
);
print("OUTPUT 3");

Output:
OUTPUT 1
OUTPUT 3
OUTPUT 2

How to 'await' in InterstitialAdLoadCallback()?

A: If you want to await an operation that does not directly expose a Future, you can use a Completer to create and manage one:
var adCompleter = Completer<void>();
InterstitialAd? _interstitialAd;
await InterstitialAd.load(
  adUnitId: '123456789',
  request: AdRequest(),
  adLoadCallback: InterstitialAdLoadCallback(
    onAdLoaded: (ad) {
      _interstitialAd = ad;
      adCompleter.complete();
    },
    onAdFailedToLoad: (err) {
      _interstitialAd = null;
      adCompleter.completeError(err);
    },
  ),
);
await adCompleter.future;


text:
Q: CollectionView.Refresh() slowed down mysteriously I have a DataGrid bound to an ObservableCollection in the view model and a CollectionView to filter the elements of the collection. I now made a change: I declared the view model as IEnumerable<T> and hand out the Enumerator of the ObservableCollection in GetEnumerator(). And the DataGrid is now bound to the view model itself. Here is the construction:
public class ViewModel : ModelBase, IEnumerable<Person>
{
    public IEnumerator<Person> GetEnumerator() => Employees.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => Employees.GetEnumerator();

    private ObservableCollection<Person> employees = new ObservableCollection<Person>();
    public ObservableCollection<Person> Employees { get => employees; set => SetField(ref employees, value); } ...

What happens is that CollectionView.Refresh() is considerably slower after the change. I have created a demo program showing the effect. The program has two DataGrids the same data (Employees).
XAML
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>

    <Button
        Grid.Row="1" Grid.Column="0" Margin="5"
        Content="Run"
        Click="RunCommand"
        />
    <TextBlock
        Grid.Row="1" Grid.Column="1" Margin="5"
        Text="{Binding Message}"
        />
    <DataGrid
        Grid.Row="0" Grid.Column="0" Margin="5"
        ItemsSource="{Binding Employees}"
        AutoGenerateColumns="True"
        Height="400"
        />
    <DataGrid
        Grid.Row="0" Grid.Column="1" Margin="5"
        ItemsSource="{Binding }"
        AutoGenerateColumns="True"
        Height="400"
        />
</Grid>

Code
public partial class MainWindow : Window
{
    private readonly ViewModel vm;
    public MainWindow()
    {
        InitializeComponent();
        vm = new ViewModel();
        DataContext = vm;

        int max = 1_000_000;
        for(int i=0; i< max; i++)
        {
            vm.Employees.Add(new Person()
            {
                FirstName = "Walter_" + i.ToString(),
                Lastname = "Winter_" + i.ToString(),
                Age = i
            });
        }
    }

    private void RunCommand(object sender, RoutedEventArgs e)
    {
        vm.MinAge++;
        Stopwatch sw = new Stopwatch();

        sw.Start();
        vm.EmpView1.Refresh();
        long t1 = sw.ElapsedMilliseconds;

        sw.Restart();
        vm.EmpView2.Refresh();
        long t2 = sw.ElapsedMilliseconds;

        vm.Message = $"{t1} - {t2}";
    }
}

public class ViewModel : ModelBase, IEnumerable<Person>
{
    public IEnumerator<Person> GetEnumerator() => Employees.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => Employees.GetEnumerator();

    private ObservableCollection<Person> employees = new ObservableCollection<Person>();
    public ObservableCollection<Person> Employees { get => employees; set => SetField(ref employees, value); }

    private string message;
    public string Message { get => message; set => SetField(ref message, value); }
    public CollectionView EmpView1 { get; private set; }
    public CollectionView EmpView2 { get; private set; }
    public int MinAge { get; set; } = 0;
    public int MaxAge { get; set; } = 100;

    public ViewModel()
    {
        EmpView1 = CollectionViewSource.GetDefaultView(Employees) as CollectionView;
        EmpView2 = CollectionViewSource.GetDefaultView(this) as CollectionView;
        EmpView1.Filter = Filter;
        EmpView2.Filter = Filter;
    }

    public bool Filter(object o)
    {
        Person p = o as Person;
        return p.Age > MinAge && p.Age < MaxAge;
    }
}

public class Person : ModelBase
{
    private string firstname;
    public string FirstName { get => firstname; set => SetField(ref firstname, value); }

    private string lastname;
    public string Lastname { get => lastname; set => SetField(ref lastname, value); }

    private int age;
    public int Age { get => age; set => SetField(ref age, value); }
}

public class ModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return;
        field = value;
        RaisePropertyChanged(propertyName);
    }

    public void RaisePropertyChanged([CallerMemberName] string propertyName = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}


text:
Q: Prove a sequence is a Cauchy and thus convergent
Suppose that $0<\alpha<1$ and that $\{ x_n\}$ is a sequence which satisfies $$|x_{n+1}-x_n| \le \alpha^n$$ $$n= 1,2,....$$
Prove that  $\{x_n\}$ is a Cauchy sequence and thus converges.
Give an example of a sequence  $\{ y_n\}$ s.t $y_n \to \infty $ but $$|y_{n+1}-y_n| \to 0$$ as $n \to \infty$

So here's my take so far, in order to understand from the beginning the definition of Cauchy is $\{v_n\}_n$ is a Cauchy sequence if for all $\varepsilon>0$ there exists $N\in \Bbb N$ such that for all natural numbers $n,m\geq N$: $|v_n-v_m|<\varepsilon$.
and I said if $n > m$ $$|x_n-x_m| \le |x_n-x_{n-1}|+|x_{n-1}-x_{n-2}|....+|x_{m+1}-x_m|$$ $$\le \alpha^{n-1}+\alpha^{n-2}+.............+\alpha^{m}$$
$$= 1-\frac{\alpha^{n-m}}{1-\alpha}$$
but from here I'm not quite convinced how I could process further...
Could i get some help?

A: You have just have to find an $N$ so that $\alpha^N < \epsilon(1-\alpha)$.  Then for $n > m \geq N$, $$\alpha^{n-1} + \cdots +  \alpha^m = \alpha^{m}(1 + \alpha + \cdots + \alpha^{n-m-1}) = \alpha^{m} \frac{(1-\alpha^{n-m})}{(1-\alpha)} \leq \frac{\alpha^{m}}{1-\alpha} \leq \frac{\alpha^N}{1-\alpha}$$

A: An example for the second part can be:
$y_n = \sum_{k=1}^n \frac1n$. Then, $|y_{n+1} - y_n|= \frac1{n+1}$, which tends to 0, but $y_n \rightarrow +\infty$ as $n\rightarrow \infty$


text:
Q: Get List of Multiple Selected Options in Select Box I am doing a function where i am displaying a multile select box, it shows the items in the select box and some comes up as already selected, What i am trying to do is;
select the items by dragging a mouse to select all, using a click on the item or there are all ways by which which we can select the items within the select box, be it mouse or keyboard., I am trying to show/hide contents based upon one of the selection of select box which is MD. On Page, i am trying that if MD is selected, it should keep the div opened.
here is my try but i am failing in this because my knowledge in javascript is very less, if someone can point me in right direction, that will be great
Here is my try:
<select id="assignType" onChange="checkASelection()" size="5" name="assignType" class="inputMultiLong" multiple>
                                <option value="M">List 1</option>
                                <option value="MS">List 2</option>
                                <option value="MD">List 3</option>
                            </select>

<div class="tabRow" id="annsection" style="display:none;">
my code here
</div>

Javascript Code:
function checkASelection() {
        var thisVal = document.getElementById('assignType').value;
        alert(thisVal);
        if(thisVal == 'MD') {
            document.getElementById('annsection').style.display='block';
        }
    }

Want to in javascript but jquery is also an option which i am check

A: Not sure what you trying to archieve, but i guess you want to get all the selected options, do you?
If so, you could do something like this in JQuery:
$('select#assignType').val();

This will return you all the selcted options
Here is a fiddle: http://jsfiddle.net/gya6mwmb/3/

A: You could use jquery inArray method:
$(function(){
$("#assignType").click(function(){
    var indice = $.inArray("MD",$(this).val()) ;
    if(indice == -1){
        $("#annsection").hide();
    }
    else{
         $("#annsection").show();
    }
});
});

Working fiddle: http://jsfiddle.net/robertrozas/voknxtL0/3/


text:
Q: Getting stuck doing a complicated SQL query for patent research purposes I am trying to gather data for a research study for my university thesis. Unfortunately I am not a computer science or programming expert and do not have any SQL experience.
For my thesis I need to do a SQL query answering the question: "Give me all patents of a company X where there is more than one applicant (other company) in a specific time span". The data I want to extract is stored on a database called PATSTAT (where I have a 1 month trial) and is using - dont be surprised SQL.
I tried a lot of queries but all the time I am getting different syntax errors.
This is how the interface looks like:
http://www10.pic-upload.de/07.07.13/7u5bqf7jsow.png
I think I have a really good understanding of what (also from an SQL POV) needs to be done but I cannot execute it.
My idea: As result I want the names of the companies (with reference to the company entered below)
SELECT person_name from tls206_person table

Now because I need a criteria like
WHERE nb_applicants > 1 from tls201_appln table

I need to join these two tables tls206 and tls201. I did read some brief introduction guide on SQL (provided by european patent office) and because both tables have no common "reference key" we need to use the table tls207_pers_appln als "intermediate" so to speak. Now thats the point where I am getting stuck. I tried the following but this is not working
SELECT person_name, tls201_appln.nb_applicants
FROM tls206_person
INNER JOIN tls207_pers_appln ON tls206_person.person_id= tls207_pers_appln.person_id
INNER JOIN tls207_pers_appln ON tls201_appln.appln_id=tls201_appln.appln_id
WHERE person_name = "%Samsung%"
AND tls201_appln.nb_applicants > 1
AND tls201_appln.ipr_type = "PI"

I get the following error: "0:37:11 [SELECT - 0 row(s), 0 secs] [Error Code: 1064, SQL State: 0] Not unique table/alias: 'tls207_pers_appln'"
I think for just 4 Hours SQL my approach is not to bad but I really need some guidance on how to proceed because I am not making any progress.
Ideally I would like to count (for every company) and for every row respectively how many "nb_applicants" were found.
If you need further information for giving me guidance, just let me know.
Looking forward to your answers.
Best regards
Kendels

A: You are referencing the table tls201_appln, but it is not in the from clause.  I am guessing that the second reference to tls207_pers_appln should be to the other table:
SELECT person_name, tls201_appln.nb_applicants
FROM tls206_person
INNER JOIN tls207_pers_appln ON tls206_person.person_id = tls207_pers_appln.person_id
INNER JOIN tls201_appln ON tls201_appln.appln_id = tls207_pers_appln.appln_id
WHERE person_name like '%Samsung%"'
AND tls201_appln.nb_applicants > 1
AND tls201_appln.ipr_type = "PI"

A: another way of doing the same thing, which you might find easier to understand (if you are new to sql it is impressive you have got so far), is:
SELECT tls206_person.person_name, tls201_appln.nb_applicants
  FROM tls206_person, tls207_pers_appln, tls201_appln
 WHERE tls206_person.person_id = tls207_pers_appln.person_id
   AND tls201_appln.appln_id = tls201_appln.appln_id
   AND tls206_person.person_name LIKE "%Samsung%"
   AND tls201_appln.nb_applicants > 1
   AND tls201_appln.ipr_type = "PI"

(it's equivalent to the other answer, but instead of trying to understand the JOIN syntax, you just write out all the logic and SQL is smart enough to make it work - this is often called the "new" or "ISO" inner join syntax, if you want to google for more info) (although it is possible, i suppose, that this newer syntax isn't supported by the database you are using).

A:
For my thesis I need to do a SQL query answering the question: "Give me all patents of a company X where there is more than one applicant (other company) in a specific time span".

Let me rephrase that for you :
SELECT * FROM patents p         -- : "Give me all patents
WHERE p.company = 'X'           -- of a company X
AND EXISTS (                    -- where there is
        SELECT *
        FROM applicants x1
        WHERE x1.patent_id = p.patent_id
        AND x1.company <> 'X'   -- another company:: exclude ourselves
        AND x1.application_date >= $begin_date -- in a specific time span
        AND x1.application_date < $end_date
                -- more than one applicant (other company)
                -- To avoid aggregation: Just repeat the same subquery
        AND EXISTS (                    -- where there is
                SELECT *
                FROM applicants x2
                WHERE x2.patent_id = p.patent_id
                AND x2.company <> 'X'           -- another company:: exclude ourselves
                AND x2.company <> x1.company -- :: exclude other other company, too
                AND x2.application_date >= $begin_date -- in a specific time span
                AND x2.application_date < $end_date
                )
        )
        ;

[Note: Since the OP did not give any table definitions, I had to invent these]
This is not the perfect query, but it does express your intentions. Given sane keys/indexes it will perform reasonably, too.


text:
Q: How to create software .exe file attached it with database which can able to run on different machine? i have developed application using vb.net for windows system.  which have sql server 2008 database and also includes crystal reports. and i want to create .exe of project. For distribution.Then how can i do that. Please help.. I am trying to do this with visual studio 2010.. Using traditional method...
1.Go to File | Add and click New Project.
2.In the Add New Project dialog box, select Other Project 3.Types and choose the Setup And Deployment Projects folder..and so on..till adding project output and primary output.but after clicking on primary output it give message like..The following files may have dependencies that can not be determinited automatically. Please confirm that all dependencies have been added to the project c:\windows\system32 \macromed\flash\flash.ocx.. Please help me to solve this..

A: Your question and your error arent related.
For your client, you need to install Sql Express.
LocalDB deployment on client PC
For the flash error, you need to check where you are using flash and make sure is also installed.


text:
Q: Организация хранения изображений в android приложении В приложении предполагается организация статического перечня материалов, организованных в виде статей ("база знаний"), ~100 шт. В каждой статье содержится текст, порядка 1000 символов и 1-2 изображения (оригинальный размер, xhdpi - ~500 Kb).
Итого получаем около 150 изображений, общим весом 75 Mb, и это только для одной плотности экрана.
Подскажите каким образом можно организовать хранение изображений для уменьшения размеров сборки? Отдельно интересуют варианты для offline приложения (предпочтительный вариант) и для приложения с загрузкой изображений через сеть после установки приложения.
Спасибо

A: Для картинок в тексте статей (тем более 1- 2 штук на страницу) можно сделать один комплект среднего качества и масштабировать под нужный размер на экране средствами системы (например параметр match_parent для ширины) - это нормальная практика.
Разделение на плотности применяется для интерфейсной графики с целью отимизации (ее обычно довольно много, а масштабирование отнимает ресурс (лаги) и память) и исключения артефактов при масштабировании (для небольших изображений увеличение/уменьшение в 2-4 раза критично). С одной картинкой справится даже бюджетное устройство, масштабирование больших картинок тоже не сильно сказывается на качесте изображения, как правило.
Оптимизировать можно (и нужно) сами картинки для уменьшения размера: формат png и его отимизицация.


text:
Q: How to add asset to cache on Laravel PWA ladumor/laravel-pwa im using
ladumor/laravel-pwa

on my laravel web and the PWA works fine but i want to optimize the loading time caching some asset, i read that can be done with the service worker but im not sure if the routes need to be explicits
there is a sw.js file with this
self.addEventListener("install", function (event) {
    event.waitUntil(preLoad());
});

var filesToCache = [
    '/',
    '/offline.html'
];

var preLoad = function () {
    return caches.open("offline").then(function (cache) {
        // caching index and important routes
        return cache.addAll(filesToCache);
    });
};

i have a logo image on /public is just easy like putting?
var filesToCache = [
    '/',
    '/myimagelogo.png'
    '/offline.html'

];

how can i know if its working?
There is an installed directory where i can look ? (Using Linux)


text:
Q: Comparing two string in android I have a method which retrieves rows from an sqlite database and returns them in a cursor.I am retreiving values from the query ok as shown below.
    private void checkWatchList() {
    Log.i("watch list", "watch list started");
    Cursor cursor = null;
    try {
        cursor = dbhandler.getAlerts();
        while (cursor.moveToNext()) {
            Log.i("watch list", "checked");

            String share_name = cursor.getString(cursor
                    .getColumnIndex(KEY_SHARE_NAME));
            String max_price = cursor.getString(cursor
                    .getColumnIndex(KEY_MAX_PRICE));
            String min_price = cursor.getString(cursor
                    .getColumnIndex(KEY_MIN_PRICE));
            int action = cursor.getInt(cursor.getColumnIndex(KEY_ACTION));
            Log.i("name", share_name + "/" + min_price + "/" + max_price);

            if (min_price.equalsIgnoreCase("null")) {
                Log.i("min", "msg");
                double maxprice = Double.parseDouble(max_price);
                compareMax(share_name, maxprice, action);
            } else if (max_price.equalsIgnoreCase("null")) {
                Log.i("max", "msg");
                double minprice = Double.parseDouble(min_price);
                compareMin(share_name, minprice, action);
            } else {
                Log.i("minmax", "msg");
                double maxprice = Double.parseDouble(max_price);
                double minprice = Double.parseDouble(min_price);
                compareMinMax(share_name, minprice, maxprice, action);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
    }
}

Problem is
when checking column values for null.For example for a row with values (KEY_SHARE_NAME=name,KEY_MAX_PRICE=12,KEY_MIN_PRICE=null),the program raises a null pointer exceptiuon at "else if (max_price.equalsIgnoreCase("null"))" section.what am i doing wrong?I cant seem to point the exact issue.

A: "null" and null are not the same. "null" is a String and read more about null at What is null in Java?. So you can not do the min_price.equalsIgnoreCase("null") for null check. Read How to check a string against null in java?

Change
if (min_price.equalsIgnoreCase("null")) {
                Log.i("min", "msg");
                double maxprice = Double.parseDouble(max_price);
                compareMax(share_name, maxprice, action);
            } else if (max_price.equalsIgnoreCase("null")) {
                Log.i("max", "msg");
                double minprice = Double.parseDouble(min_price);
                compareMin(share_name, minprice, action);
            }

to
if (min_price == null) {
                Log.i("min", "msg");
                double maxprice = Double.parseDouble(max_price);
                compareMax(share_name, maxprice, action);
            } else if (max_price == null) {
                Log.i("max", "msg");
                double minprice = Double.parseDouble(min_price);
                compareMin(share_name, minprice, action);
            }

A: null and String "null" are not the same thing. Therefore for example this code:
min_price.equalsIgnoreCase("null")

should be changed to:
min_price == null

A: min_price.equalsIgnoreCase("null")

will throw a NullPointerException if min_price is null.
Also, the above statement compares with "null", which is a string. You want to compare it with null reference.
Use min_price == null in that case


text:
Q: How to set correctly jQuery progressbar height? I am trying to set the jQuery UI progressbar height, using jQuery UI 1.10.3
Although the div seems to be correctly sized, the inside progress obviously not, the right bottom seems to be cut.
I am using the following code:
$div = $("#mydiv");
$div.progressbar({
    value: percent
});
$div.height(20);

What am I missing?


text:
Q: Hover/mouseover not firing in IE, image in the way I have a div and within that div is an image, and layed on top of those is 2 divs which have jquery hover attached to them (same issue with onmouseover though, so not jquery).
Problem is when the image is loaded, even though the divs are layed on top of the image they won't fire because the image is always on top (even though it isn't actually, and i've tried putting it lower down on z-index but it didn't help).
jquery:

Html:

    <img src="<?php  echo $img[0]; ?>" border="0" alt="" title="" />

            [content]

 (loop fills this)

                [content]

Is this a known IE bug that I just haven't come accross before? Or is there a bug in my code? When filled with content the largeInset and largeArticles divs should fire on hover and slide out across the image, works in chrome but not IE as IE seems to select the image on top of the divs even though they are actually below it (Would work fine if the image didn't load).
Any ideas? Hopefully I made sense.
CSS:
    .articles { position: relative; width: 100%; padding: 0; float: left; background-color: #fff; }
.large { margin: 0 0 10px; border: 0px solid #000; min-height: 200px; }
.large img { max-width: 100%; min-width: 100%; min-height: 350px; z-index: -1; }

.largeContent { z-index: 99; position: absolute; top: 0; width: 100%; height: 100%; }
.filler { width: 100%; height: 100%; }
#largeInset { position: absolute; top: 0; right: 0; min-height: 100%; width: 25%; color: #fff; }
#largeInset .head { padding: 10px 0; }
#largeInset p { font-size: 0.9em; margin: 5px 10px; }
#largeInset .content { overflow: hidden; position: absolute; top:0; background-color: #000; right: 0; color: #fff; }

#largeArticles { position: absolute; top: 0; left: 0; width: 25%; min-height: 100%; }
#largeArticles .content { overflow: hidden; position: absolute; top: 0; left: 0; width: 40%; background-color: #000; }

A: I've solved this for now by adding content to the divs. IE will only fire when you mouseover the content in the div (maybe because position is absolute?). I added a transparent 1px image to the divs, but stretched to 100% x 100%, so you hover over the image and it will fire.
This seems a bit hacked together though
See http://iamnotahippy.com/ice/web/?cat=5 (hover over sides of image)


text:
Q: Function1[T, U] => Function1[T, Option[U]] How can I take a Function1[T, U] and make it a  Function1[T, Option[U]]?
Something like:
def wrapAsOption[T, U](f: T => U): T => Option[U] = ???

It's totally ok to make it always a Some(U).

A: def optionalize[T, U](f: T => U): T => Option[U] = f.andThen(Option(_))


text:
Q: How can i place a echo within the 'define' of another echo i use auto generated sections of my website a lot, and i have started to include tooltips on important features, using the define function is a must have.
so i currently have:
define('Raeger_PATH', '<?php echo ALIGNMENT_CRUSADER; ?>');

this was
define('Raeger_PATH', 'CRUSADER');

until i wanted the tooltip, so i need to add the code, now i CAN just add the code, but didnt want the same code repeated over and over so i attempted to ad the echo, but nothing appears.
So how do i place the eccho within the defination of another echo, it might not be possible, it might just require something i doont know about.
thanks for any help

A: you can make this by:
define('Raeger_PATH',ALIGNMENT_CRUSADER);


text:
Q: How can I apply the same condition in the different datasets in the python pandas data frame? I am doing a machine learning project to predict the strong area of a department using many datasets. In that case, I need to apply the same condition to different columns of different datasets.
For example:
Condition = [
(X['Y'] >= 3.75) & (X['Y'] <= 4.00),
(X['Y'] >= 3.50) & (X['Y'] < 3.75),
(X['Y'] >= 3.25) & (X['Y'] < 3.50),
(X['Y'] >= 3.00) & (X['Y'] < 3.25),
(X['Y'] < 3.00)
]

category = ['1', '2', '3', '4', '5']
X['Y'] = np.select(Condition , category, default='0') #np for numpy libraries

Here, X is the particular dataset, and Y is the column name.
When I run the code, it shows
NameError: name X is not defined

How can I use "X" as the different dataset name and Y as the column name?


text:
Q: Opengl calculate triangle derivatives I have a triangle in 2D space.
I have  screen space coordinates of each vertex, and I have attribute values of each vertex.
How can I calculate dFdx / dFdy for those attributes? In other words, how will change attribute from screen pixel to pixel.
//fragment shader
varrying vec2 myAttr;

void main(void)
{
  vec2 px = dFdx(myAttr);
  vec2 py = dFdy(myAttr);
}

I want to get px, py. I need to know delta(grow) of myAttr from next pixel for x and y axis.
I need formula /algorithm how to calculate them manually (for example for cases when hardware does not support derivatives).
P.S. Attribute value linear interpolated between 3 vertices (according to OpenGL doc).

A: assuming your vertex are structured like this:
struct vertex
{
  double x; // screenspace x coordinate
  double y; // screenspace y coordinate
  double a; // your attribute
};

The derivation you're looking for are calculated like this:
      d    = (v0.x - v2.x) * (v1.y - v2.y) -
             (v1.x - v2.x) * (v0.y - v2.y);

      dfdx = ((v0.a - v2.a) * (v1.y - v2.y) -
              (v1.a - v2.a) * (v0.y - v2.y)) / d;

      dfdy = ((v0.a - v2.a) * (v1.x - v2.x) -
              (v1.a - v2.a) * (v0.x - v2.x)) / d;

Note that this equation becomes unstable as d approaches zero. It will also cause a divide by zero if d is exactly zero. This is not a problem in practice because in this case the triangle also has a area of zero and nothing needs to be rendered.


text:
Q: ejs-pager click and dropDownChanged method call simultaneously issue I am using ejs-pager in Angular. But facing problem during dropDownChanged method calling as it also calls click method. is there any way to prohibit this nature?
there is a condition that both pageChange and dropDownChanged custom methods can't be called simultaneously.

<ejs-pager #pager (click)="pageChange($event)" (dropDownChanged)="dropDownChanged($event)"
                     [locale]='locale' [pageCount]='pageSettings.pageCount'
                     [pageSize]='pageSettings.pageSize'
                     [pageSizes]='pageSettings.pageSizes'
                     [totalRecordsCount]='totalCount' *ngIf="apiSupportsPagination">
</ejs-pager>


text:
Q: How to use CreateCompletedEventHandler with the web service I am using a web service connection to my company's test NAV environment (NAV 2013).  I need to add a customer to the NAv environment.  So for I have been able to make this code work:
var customerService = new CustomerService.Customer_Service()  {UseDefaultCredentials = true};
var cust = new CustomerService.Customer()  {Address = "100 Orion Way", Name = "Test") };
customerService.Create(cust);

Now I need to create the customer Asynchronously and track of the call is complete.  I know I need to use CreateAsync(Customer _customer, Object _userState) and CreateCompletedEventHandler but I cannot find anywhere how to it.  Does anyone have an example?

A: When you create your service references in Visual Studio, make sure you select the "Generate asynchronous operations" checkbox.  Otherwise the generated proxy class will not have any async methods, which I'm guessing is your issue.  Here is an MSDN article with more details.


text:
Q: call a WebAPI from Windows Service
I have errors after call webapi from Windows Service
first error is :

An error occurred while sending the request.

second error  is :

The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel.

A: You could use System.Net.Http.HttpClient.. You will obviously need to edit the fake base address and request URI in the example below but this also shows a basic way to check the response status as well.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8888/");

//Usage
HttpResponseMessage response = client.GetAsync("api/importresults/1").Result;
if (response.IsSuccessStatusCode){var dto = response.Content.ReadAsAsync<ImportResultDTO>().Result;}
else{Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);}


text:
Q: django: Language-aware Drop-down I am new to django and i am loving it so far especially its nice community. Here is my question: I have this model
class Nationality(models.Model):
  nationality_fr = models.CharField(max_length=50)
  nationality_en = models.CharField(max_length=50)
  show_flag = models.BooleanField()
  display_order = models.PositiveSmallIntegerField()

  def __str__(self):
    return self.nationality_fr

I want to change the __ str __ function to return nationality_fr if the language selected (by the user) is "fr" and language_en if the selected language is "en". the reason i need this is because i am showing a drop-down for selecting nationalities for the user to choose and he/she should see the choices in his/her language. what is the best to way to deal with this?
Note: I know there is a nice app for countries but i should be able to do that for other scenarios other than this countries scenario.

A: The simplest method is get_language(), that tells you the language in the current thread based on settings.LANGUAGE_CODE setting.
from django.utils.translation import get_language

def __str__(self):
    if get_language().startswith('fr'):
        return self.nationality_fr
    else:
        return self.nationality_en

If you let Django set the language dynamically, based on request parameters like URL substring or browser header, use django.utils.translation.get_language_from_request instead (since Django 1.8). See docs here

A: After some research, i found the solution: django.utils.translation.get_language(). It returns the language used in the current thread and u can use it in models like so:
from django.utils import translation

@property
def nationality(self):
    lang = translation.get_language()
    if lang == "fr":
        return self.nationality_fr
    else:
        return self.nationality_en

def __str__(self):
    return self.nationality


text:
Q: Create Header and Footer in the .docx report using R? I want the header and footer to repeat in every page of the .docx report.
Everyone is suggesting use the RMarkdown to get the header and footer. Is it possible using R?
I am using Officer package for .docx report. I want this header & footer in the Clinical reports.
In SAS we can get using the "Header" & "Footer statement". How to get it in the R?
Please help me on this, as am new to R programming.
Thanks & Regards
Vamsi

A: Using 'officer', you can design a content-empty .docx file with  your header and footer first,  and read it and merge your report, then,    the h&f will repeat in your report.


text:
Q: Kendo DropDownListFor возвращает выбранный текст а не значение @Html.Kendo().DropDownListFor(model => model.Status).ValuePrimitive(true).DataTextField("Aspirants1").DataValueField("New_kod").BindTo(ViewBag.Type).Value(((IEnumerable<Aspirants>)ViewBag.Type).First().New_Kod.ToString())

$("#Status").data("kendoDropDownList").value()

или
    $('#Status').val()
возвращает DataTextField а не DataValueField
хотя на этой же странице есть элемент
    @Html.Kendo().DropDownListFor(x => x.Kod_tipap).ValuePrimitive(true).DataTextField("Tipp1").DataValueField("Kod_tipp").BindTo(ViewBag.Tipp).Value(((IEnumerable)ViewBag.Tipp).First().Kod_tipp.ToString())
и здесь всё работает
        ViewBag.Tipp = _db.Tipp.ToList();
        ViewBag.Type = _db.AspiratsTypes.ToList();

public virtual DbSet<Aspirants> AspiratsTypes { get; set; }

public partial class Aspirants
{
    [Key]
    public int New_Kod { get; set; }

    [Column("Aspirants")]
    public string Aspirants1 { get; set; }
}

A: New_Kod регистр буквы не совпадал. В классе свойство отличалось от того что прописано в определении DDL DataValueField.


text:
Q: from python, creating data block & passing its pointer into c program via SWIG I've just started learning Python a few weeks ago (noob). We are using Python (2.7 dictated by the company) as test front-end, and I'm trying to test a C routine that takes a pointer (buried within a data structure) to a binary block of data as an input parameter. I'm probably doing many things wrong, so please help me understand.
It looks like bytearray(size) makes a packed block of data, but let me know if that's wrong. I also tried using a create_string_buffer(size+1), which seems to work a little better. However I still cannot get it to work the way I need.
We are using SWIG as the go-between (also dictated by company, no option to change at the moment), which may be a complicating factor. I can make modifications to the .i files used by SWIG, if that is something that will help.
Any thoughts on how to make this happen within the constraints of SWIG & Python 2.7? I am open to using other packages or toolsets, so long as the learning curve isn't terribly steep (just need it for this one capability) and they are free (no budget for extra tools).
The C data structures (stripped down - existing code, can't change)
typedef struct pb_callback_s pb_callback_t;
struct pb_callback_s
{   void *arg;
};

typedef struct _file_page_type
{   uint32_t page_length;  //nominal 256 bytes
    pb_callback_t data_ptr_handler;
} file_page_type;

//function prototype
void post_software_management_load(file_page_type file_page);

Python code (stripped down)
myFP = h_api.file_page_type()            #SWIG constructor
dataBlock = bytearray(totalUpdateSize)
#here is where we need to create a pointer to the byte array
#here is where we need to put that info into myFP.data_ptr_handler.arg
h_api.post_software_management_load(myFP)

Some data points:
-print "myFP.data_ptr_handler.arg", type(myFP.data_ptr_handler.arg)
  Results: myFP.data_ptr_handler.arg <type 'NoneType'>
-the function `pointer()` seems to work for `create_string_buffer()` objects, but not for `bytearray()` objects (although both the object and the pointer appear to be of type `ctypes.c_char_Array_257`)
-the function `byref()` works for `create_string_buffer()` objects (results in a type of type `CArgObject` back from `byref()`), but not for `bytearray()` objects

I'm trying to do these things, in this order which are all closely related:

*

*get the Python script to generate an object that is compatible with C (ie a contiguous block of binary data) and

*get a C compatible pointer pointed at it

*get that pointer assigned into a structure and passed into the C function (via SWIG)

I kept getting "code that is not properly formatted" errors, listing the info that used to be in this section, so it was moved to the "some data points" tag in the code section, above.

A: Ultimately, I found that trying to convert the data from C to Python was more pain than it was worth. The company that was providing the C interface provided the proper functionality (the necessary C-Pointer-embedded-in-Python) to me, and that worked. Sorry for not knowing exactly what the helper code (C->Py) is called as I am no longer at that company.
Thanks for all the help, and sorry it took me so long to get back to answer the question.


text:
Q: Разбить элементы вектора по парам Есть вектор vector<vector<string> >kosz;, В нем содержатся векторы с разным количеством элементов. Нужно разбить элементы каждого из векторов по парам, но при этом нужно перебрать все возможные варианты соединения, тоесть к примеру первый элемент со вторым - одна пара, первый с третьим - вторая пара, второй с третьим - еще одна пара, ну и тд. И так нужно перебрать все и посчитать количество одинаковых пар во всех векторах. Тоесть, к примеру есть вектор kosz {{a,b,c,d}, {b,c,d}. В результате должно получится примерно так:{a,b} - 1 раз, {b,c} - 2 раза, {c,d} - 2 раза, {b,d} - 1 раз,.... ну и в таком духе. Смог только придумать как разбить векторы по парам, но чтобы перебрать все варианты, так не выходит.

A: map <string/string; int>  // ключ - пара строк
for v in vectors
    for i = 0; i< v.size - 1
        for j = i + 1; i < v.size
             map[v[i]+v[j]] ++

Это просто перебор всех возможных пар в каждом векторе с добавлением их в словарь. Если в словаре нет такого ключа -  добавить ключ со значением 1, иначе увеличить значение на 1.
#include "pch.h"
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
    vector<vector<string>> vectors = { { "a", "b", "c"},
                                       { "a", "b", "d"},
                                       { "a", "c", "d"},
                                       { "a", "b"}};
    map<pair<string, string>, int> dict;
    for (auto v: vectors) {
        for (int i = 0; i < v.size() - 1; i++)
            for (int j = i + 1; j < v.size(); j++) {
                pair<string, string> p = { v[i], v[j] };
                if (dict.find(p) == dict.end())
                    dict[p] = 1;
                else
                    dict[p]++;
            }
    }
    map<pair<string, string>, int>::iterator it;
    for (it = dict.begin(); it != dict.end(); ++it)
        cout <<it->second<<"\n";
    return 0;
}

Как пару строк (ключ) вывести, я что- то не пойму.
Вывод {"a", "b"} встречается три раза и т.д.)
3 2 2 1 1 1


text:
Q: How to link excel file to sql server 2008r2 management studio we have recently adopted to sql server 2008r2 from access. We are completely new to it. We need to work on data which comes in excel spreadsheets. In access we directly link the data to it and run the queries. This similar approach is available in sql server also? If not how to link the excel files into sql server?
what is sql server compact?

A: In order to link the excel files : In excel go to data tab. There you will find the From Other Sources option. A wizard will appear requesting the Server name and your credentials to the db -> next -> select the db you want to connect to and then the table and click finish.
Hope it helps.

A: I don't know about "linking" your Excel workbook or sheets to SQLServer database. Are these always on the same host?
In any case, you can easily import your Excel data into a SQLServer table:
INSERT INTO sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

INSERT INTO dbo.YOUR_SQL_TABLENAME
SELECT EXCEL_COLUMN_NAME1 [, EXCEL_COLUMN_NAME2...] FROM
OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
'Data Source=C:\YOUR_EXCEL_FILENAME.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

This will import from Sheet1$, if you have named your worksheets, then use the name.


text:
Q: Why can't I drag and drop widgets into a toolbar in Android Studio? I have an Android activity with a Toolbar inside an AppBarLayout and I would like to add widgets to it. When I try to drag and drop a widget onto the Toolbar in the Designer, it doesn't work and the cursor shows a symbol indicating that it can't be added.
There are many questions on StackOverflow all asking the same thing but the answers all seem to be about the distinction between activity_*.xml and content_*.xml. This is not the issue for me, I'm using the activity_*.xml file which definitely includes the Toolbar. I can also add widgets manually in the XML file and they appear in the designer; it's only the drag and drop that isn't working.
Any ideas why this doesn't work or how to make it work?

A: I'm sorry I still don't have enough reps to comment because this is a new account. But have you tried writing on the xml instead? Right below the palette toolbox, you can switch from design to text and vice versa. And the xml code can easily be googled.


text:
Q: Is homoscedasticity met? I'm fairly new to statistics. Could you help me, please?
I've got the scatterplot of residuals versus predicted value. It seems that the data points aren't scattered around zero with a constant width.
Am I right that homoscedasticity hasn't been met? What should I do? I have 5 independent variables, two of which are categorical. Can I make a prediction in this case?

A: This looks reasonable to me.  Heterogeneity of variance is only an issue for inference, not prediction.  If you're worried about homogeneity of variance being violated, you could use a sandwhich estimator instead.  In the case where there is no heterogeneity of variance and you use the sandwhich, you lose a bit of power.  Seems like a worth while tradeoff to me.

A: Just from Visual inspection, I cannot detect heteroskedasticity. But I advice you to run some statistical tests like White Test


text:
Q: How do 'Modify All Data' and 'View All Data' affect Field-Level Security settings Does the Modify All Data or View All Data permission allow a user/profile to ignore the FLS settings for an object? The documentation would seem to suggest that this is the case, but I've found conflicting results.
Using Schema.SObjectField.getDescribe().isUpdateable() to perform a FLS check will return return false if the 'Edit' permission isn't granted for the field. This behavior holds while running as a user with the View All Data or Modify All Data permission.
This would seem to indicate that FLS is independent from the Modify All Data and View All Data permissions. However, I can write a unit test that runs as a user with the Modify All Data and successfully perform an update to the field that the FLS check said wasn't updatable.

A: It's worth noting that apex does not enforce field level security, even if run with sharing. Typically visualforce handles enforcement of these for you by doing things like not rendering apex:inputField or apex:outputField tags referencing a field the user has no FLS access to.
This automatic enforcement of FLS is only done at the presentation layer by the platform, enforcing it within apex contexts must be done explicitly in your classes (with isAccessible(), isUpdatable(), etc) if you want it to be done at all.
Thus regardless of the running user's access to a field your apex tests would be allowed to read and write said field.

A: Modify All Data and View All Data do not, in any way, affect Field Level Security. The only permission that affects Field Level Security is Edit Read Only Fields. Apex Code generally ignores Field Level Security, while Visualforce generally honors Field Level Security. This is the reason why the "isAccessible" calls are available. The "with sharing" and "without sharing" keywords refer to record visibility and record editablity, not field accessibility.

A: Yes, this is one of the reasons that I normally ratchet down all record access and functionality for ALL users to start with and then "build up" based upon their requirements (leveraging profiles, roles, permission sets and sharing rules). This normally starts by removing MAD and VAD.
For me the only exception to this would be some form of Administrator account.
Some security options such as MAD and VAD are quite often too powerful and I shy away from using them.